blob: 1cddcb065845f531ceb44819435af995aaf5a82d [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000022extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimesd3eb5a152008-02-24 00:38:49 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
28#endif
29
Guido van Rossum21d335e1993-10-15 13:01:11 +000030
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000031/* Magic word to reject .pyc files generated by other Python versions.
32 It should change for each incompatible change to the bytecode.
33
34 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000035 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000036 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000037
Guido van Rossum45aecf42006-03-15 04:58:47 +000038 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000039 -U interpeter flag will cause MAGIC+1 being used. They have been
40 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000041
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000042 There were a variety of old schemes for setting the magic number.
43 The current working scheme is to increment the previous value by
44 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000045
Barry Warsaw28a691b2010-04-17 00:19:56 +000046 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
47 number also includes a new "magic tag", i.e. a human readable string used
48 to represent the magic number in __pycache__ directories. When you change
49 the magic number, you must also set a new unique magic tag. Generally this
50 can be named after the Python major version of the magic number bump, but
51 it can really be anything, as long as it's different than anything else
52 that's come before. The tags are included in the following table, starting
53 with Python 3.2a0.
54
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000055 Known values:
56 Python 1.5: 20121
57 Python 1.5.1: 20121
58 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000060 Python 2.0: 50823
61 Python 2.0.1: 50823
62 Python 2.1: 60202
63 Python 2.1.1: 60202
64 Python 2.1.2: 60202
65 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000066 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000067 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000068 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000069 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000070 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000071 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000072 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000073 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000074 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000075 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
77 Python 2.5b3: 62111 (fix wrong code: x += yield)
78 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
79 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000080 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000081 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000082 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000083 Python 3000: 3000
Brett Cannone2e23ef2006-08-25 05:05:30 +000084 3010 (removed UNARY_CONVERT)
Guido van Rossum86e58e22006-08-28 15:27:34 +000085 3020 (added BUILD_SET)
Guido van Rossum4f72a782006-10-27 23:31:49 +000086 3030 (added keyword-only parameters)
Guido van Rossum3203bdc2006-12-28 21:03:31 +000087 3040 (added signature annotations)
Guido van Rossum452bf512007-02-09 05:32:43 +000088 3050 (print becomes a function)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000089 3060 (PEP 3115 metaclass syntax)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000090 3061 (string literals become unicode)
91 3071 (PEP 3109 raise changes)
92 3081 (PEP 3137 make __file__ and __name__ unicode)
93 3091 (kill str8 interning)
94 3101 (merge from 2.6a0, see 62151)
95 3103 (__file__ points to source file)
96 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
97 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
98 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf289ae62008-12-18 11:06:25 +000099 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +0000100 Python 3.1a0: 3151 (optimize conditional branches:
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +0000101 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000102 Python 3.2a0: 3160 (add SETUP_WITH)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000103 tag: cpython-32
Tim Peters36515e22001-11-18 04:06:29 +0000104*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000105
Barry Warsaw28a691b2010-04-17 00:19:56 +0000106/* If you change MAGIC, you must change TAG and you must insert the old value
107 into _PyMagicNumberTags below.
108*/
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000109#define MAGIC (3160 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000110#define TAG "cpython-32"
111#define CACHEDIR "__pycache__"
112/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000113static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116/* See _PyImport_FixupExtension() below */
117static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000118
Guido van Rossum771c6c81997-10-31 18:37:24 +0000119/* This table is defined in config.c: */
120extern struct _inittab _PyImport_Inittab[];
121
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000122/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000123extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000124
Guido van Rossum771c6c81997-10-31 18:37:24 +0000125struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000126
Guido van Rossumed1170e1999-12-20 21:23:41 +0000127/* these tables define the module suffixes that Python recognizes */
128struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000129
Guido van Rossumed1170e1999-12-20 21:23:41 +0000130static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000131 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000132#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000133 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000134#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135 {".pyc", "rb", PY_COMPILED},
136 {0, 0}
137};
138
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000140/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141
142void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000143_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000145 const struct filedescr *scan;
146 struct filedescr *filetab;
147 int countD = 0;
148 int countS = 0;
149
150 /* prepare _PyImport_Filetab: copy entries from
151 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
152 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000153#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000154 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
155 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000156#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000157 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
158 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000159 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160 if (filetab == NULL)
161 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000162#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000163 memcpy(filetab, _PyImport_DynLoadFiletab,
164 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000165#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000166 memcpy(filetab + countD, _PyImport_StandardFiletab,
167 countS * sizeof(struct filedescr));
168 filetab[countD + countS].suffix = NULL;
169
170 _PyImport_Filetab = filetab;
171
Guido van Rossum0824f631997-03-11 18:37:35 +0000172 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000173 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
174 for (; filetab->suffix != NULL; filetab++) {
175 if (strcmp(filetab->suffix, ".pyc") == 0)
176 filetab->suffix = ".pyo";
Guido van Rossum0824f631997-03-11 18:37:35 +0000177 }
178 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179}
180
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181void
Just van Rossum52e14d62002-12-30 22:08:05 +0000182_PyImportHooks_Init(void)
183{
184 PyObject *v, *path_hooks = NULL, *zimpimport;
185 int err = 0;
186
187 /* adding sys.path_hooks and sys.path_importer_cache, setting up
188 zipimport */
Christian Heimes9cd17752007-11-18 19:35:23 +0000189 if (PyType_Ready(&PyNullImporter_Type) < 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000190 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000191
192 if (Py_VerboseFlag)
193 PySys_WriteStderr("# installing zipimport hook\n");
194
195 v = PyList_New(0);
196 if (v == NULL)
197 goto error;
198 err = PySys_SetObject("meta_path", v);
199 Py_DECREF(v);
200 if (err)
201 goto error;
202 v = PyDict_New();
203 if (v == NULL)
204 goto error;
205 err = PySys_SetObject("path_importer_cache", v);
206 Py_DECREF(v);
207 if (err)
208 goto error;
209 path_hooks = PyList_New(0);
210 if (path_hooks == NULL)
211 goto error;
212 err = PySys_SetObject("path_hooks", path_hooks);
213 if (err) {
214 error:
215 PyErr_Print();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000216 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
217 "path_importer_cache, or NullImporter failed"
218 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000219 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000220
Just van Rossum52e14d62002-12-30 22:08:05 +0000221 zimpimport = PyImport_ImportModule("zipimport");
222 if (zimpimport == NULL) {
223 PyErr_Clear(); /* No zip import module -- okay */
224 if (Py_VerboseFlag)
225 PySys_WriteStderr("# can't import zipimport\n");
226 }
227 else {
228 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
229 "zipimporter");
230 Py_DECREF(zimpimport);
231 if (zipimporter == NULL) {
232 PyErr_Clear(); /* No zipimporter object -- okay */
233 if (Py_VerboseFlag)
234 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000235 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000236 }
237 else {
238 /* sys.path_hooks.append(zipimporter) */
239 err = PyList_Append(path_hooks, zipimporter);
240 Py_DECREF(zipimporter);
241 if (err)
242 goto error;
243 if (Py_VerboseFlag)
244 PySys_WriteStderr(
245 "# installed zipimport hook\n");
246 }
247 }
248 Py_DECREF(path_hooks);
249}
250
251void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000252_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000253{
254 Py_XDECREF(extensions);
255 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000256 PyMem_DEL(_PyImport_Filetab);
257 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000258}
259
260
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000261/* Locking primitives to prevent parallel imports of the same module
262 in different threads to return with a partially loaded module.
263 These calls are serialized by the global interpreter lock. */
264
265#ifdef WITH_THREAD
266
Guido van Rossum49b56061998-10-01 20:42:43 +0000267#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000268
Guido van Rossum65d5b571998-12-21 19:32:43 +0000269static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000270static long import_lock_thread = -1;
271static int import_lock_level = 0;
272
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000273void
274_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000275{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000276 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277 if (me == -1)
278 return; /* Too bad */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000279 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000280 import_lock = PyThread_allocate_lock();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000281 if (import_lock == NULL)
282 return; /* Nothing much we can do. */
283 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000284 if (import_lock_thread == me) {
285 import_lock_level++;
286 return;
287 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000288 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
289 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000291 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000292 PyEval_RestoreThread(tstate);
293 }
294 import_lock_thread = me;
295 import_lock_level = 1;
296}
297
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000298int
299_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000301 long me = PyThread_get_thread_ident();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000302 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000303 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000305 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000306 import_lock_level--;
307 if (import_lock_level == 0) {
308 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000309 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000310 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000311 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000312}
313
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000314/* This function is called from PyOS_AfterFork to ensure that newly
315 created child processes do not share locks with the parent.
316 We now acquire the import lock around fork() calls but on some platforms
317 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000318
319void
320_PyImport_ReInitLock(void)
321{
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000322 if (import_lock != NULL)
323 import_lock = PyThread_allocate_lock();
324 import_lock_thread = -1;
325 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000326}
327
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000328#endif
329
Tim Peters69232342001-08-30 05:16:13 +0000330static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000331imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000332{
Tim Peters69232342001-08-30 05:16:13 +0000333#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000334 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000335#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000336 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000337#endif
338}
339
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000340static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000341imp_acquire_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
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000344 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000346 Py_INCREF(Py_None);
347 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348}
349
350static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000351imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353#ifdef WITH_THREAD
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000354 if (_PyImport_ReleaseLock() < 0) {
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000355 PyErr_SetString(PyExc_RuntimeError,
356 "not holding the import lock");
357 return NULL;
358 }
359#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000360 Py_INCREF(Py_None);
361 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000362}
363
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364static void
365imp_modules_reloading_clear(void)
366{
367 PyInterpreterState *interp = PyThreadState_Get()->interp;
368 if (interp->modules_reloading != NULL)
369 PyDict_Clear(interp->modules_reloading);
370}
371
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372/* Helper for sys */
373
374PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000377 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378 if (interp->modules == NULL)
379 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
380 return interp->modules;
381}
382
Guido van Rossum3f5da241990-12-20 15:06:42 +0000383
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000384/* List of names to clear in sys */
385static char* sys_deletes[] = {
Collin Winter670e6922007-03-21 02:57:17 +0000386 "path", "argv", "ps1", "ps2",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000387 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000388 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000389 /* misc stuff */
390 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000391 NULL
392};
393
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000394static char* sys_files[] = {
395 "stdin", "__stdin__",
396 "stdout", "__stdout__",
397 "stderr", "__stderr__",
398 NULL
399};
400
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000401
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000402/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000403
Guido van Rossum3f5da241990-12-20 15:06:42 +0000404void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000405PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000406{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000407 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000408 char *name;
409 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000410 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000411 PyObject *modules = interp->modules;
412
413 if (modules == NULL)
414 return; /* Already done */
415
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000416 /* Delete some special variables first. These are common
417 places where user values hide and people complain when their
418 destructors fail. Since the modules containing them are
419 deleted *last* of all, they would come too late in the normal
420 destruction order. Sigh. */
421
Georg Brandl1a3284e2007-12-02 09:40:06 +0000422 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000423 if (value != NULL && PyModule_Check(value)) {
424 dict = PyModule_GetDict(value);
425 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000426 PySys_WriteStderr("# clear builtins._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000427 PyDict_SetItemString(dict, "_", Py_None);
428 }
429 value = PyDict_GetItemString(modules, "sys");
430 if (value != NULL && PyModule_Check(value)) {
431 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000432 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000433 dict = PyModule_GetDict(value);
434 for (p = sys_deletes; *p != NULL; p++) {
435 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000436 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437 PyDict_SetItemString(dict, *p, Py_None);
438 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000439 for (p = sys_files; *p != NULL; p+=2) {
440 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000441 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000442 v = PyDict_GetItemString(dict, *(p+1));
443 if (v == NULL)
444 v = Py_None;
445 PyDict_SetItemString(dict, *p, v);
446 }
447 }
448
449 /* First, delete __main__ */
450 value = PyDict_GetItemString(modules, "__main__");
451 if (value != NULL && PyModule_Check(value)) {
452 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000453 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000454 _PyModule_Clear(value);
455 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000456 }
457
Georg Brandl1a3284e2007-12-02 09:40:06 +0000458 /* The special treatment of "builtins" here is because even
Guido van Rossum758eec01998-01-19 21:58:26 +0000459 when it's not referenced as a module, its dictionary is
460 referenced by almost every module's __builtins__. Since
461 deleting a module clears its dictionary (even if there are
Georg Brandl1a3284e2007-12-02 09:40:06 +0000462 references left to it), we need to delete the "builtins"
Guido van Rossum758eec01998-01-19 21:58:26 +0000463 module last. Likewise, we don't delete sys until the very
464 end because it is implicitly referenced (e.g. by print).
465
466 Also note that we 'delete' modules by replacing their entry
467 in the modules dict with None, rather than really deleting
468 them; this avoids a rehash of the modules dictionary and
469 also marks them as "non existent" so they won't be
470 re-imported. */
471
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000472 /* Next, repeatedly delete modules with a reference count of
Georg Brandl1a3284e2007-12-02 09:40:06 +0000473 one (skipping builtins and sys) and delete them */
Guido van Rossum758eec01998-01-19 21:58:26 +0000474 do {
475 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000476 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000477 while (PyDict_Next(modules, &pos, &key, &value)) {
478 if (value->ob_refcnt != 1)
479 continue;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000480 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000481 name = _PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000482 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000483 continue;
484 if (strcmp(name, "sys") == 0)
485 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000486 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000487 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000488 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000489 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000490 PyDict_SetItem(modules, key, Py_None);
491 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000492 }
493 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000494 } while (ndone > 0);
495
Georg Brandl1a3284e2007-12-02 09:40:06 +0000496 /* Next, delete all modules (still skipping builtins and sys) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000497 pos = 0;
498 while (PyDict_Next(modules, &pos, &key, &value)) {
Neal Norwitz80e7f272007-08-26 06:45:23 +0000499 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000500 name = _PyUnicode_AsString(key);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000501 if (strcmp(name, "builtins") == 0)
Guido van Rossum758eec01998-01-19 21:58:26 +0000502 continue;
503 if (strcmp(name, "sys") == 0)
504 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000505 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000506 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000507 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000508 PyDict_SetItem(modules, key, Py_None);
509 }
510 }
511
Georg Brandl1a3284e2007-12-02 09:40:06 +0000512 /* Next, delete sys and builtins (in that order) */
Guido van Rossum758eec01998-01-19 21:58:26 +0000513 value = PyDict_GetItemString(modules, "sys");
514 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000515 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000516 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000517 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000518 PyDict_SetItemString(modules, "sys", Py_None);
519 }
Georg Brandl1a3284e2007-12-02 09:40:06 +0000520 value = PyDict_GetItemString(modules, "builtins");
Guido van Rossum758eec01998-01-19 21:58:26 +0000521 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000522 if (Py_VerboseFlag)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000523 PySys_WriteStderr("# cleanup builtins\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000524 _PyModule_Clear(value);
Georg Brandl1a3284e2007-12-02 09:40:06 +0000525 PyDict_SetItemString(modules, "builtins", Py_None);
Guido van Rossum758eec01998-01-19 21:58:26 +0000526 }
527
528 /* Finally, clear and delete the modules directory */
529 PyDict_Clear(modules);
530 interp->modules = NULL;
531 Py_DECREF(modules);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000532 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000533}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000534
535
Barry Warsaw28a691b2010-04-17 00:19:56 +0000536/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000537
538long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000539PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000540{
Guido van Rossum96774c12000-05-01 20:19:08 +0000541 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000542}
543
544
Barry Warsaw28a691b2010-04-17 00:19:56 +0000545const char *
546PyImport_GetMagicTag(void)
547{
548 return pyc_tag;
549}
550
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551/* Magic for extension modules (built-in as well as dynamically
552 loaded). To prevent initializing an extension module more than
553 once, we keep a static dictionary 'extensions' keyed by module name
554 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000555 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556 dictionary is stored by calling _PyImport_FixupExtension()
557 immediately after the module initialization function succeeds. A
558 copy can be retrieved from there by calling
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000559 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560
Martin v. Löwis1a214512008-06-11 05:26:20 +0000561 Modules which do support multiple multiple initialization set
562 their m_size field to a non-negative number (indicating the size
563 of the module-specific state). They are still recorded in the
564 extensions dictionary, to avoid loading shared libraries twice.
565*/
566
567int
568_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000569{
Martin v. Löwis1a214512008-06-11 05:26:20 +0000570 PyObject *modules, *dict;
571 struct PyModuleDef *def;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572 if (extensions == NULL) {
573 extensions = PyDict_New();
574 if (extensions == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000575 return -1;
576 }
577 if (mod == NULL || !PyModule_Check(mod)) {
578 PyErr_BadInternalCall();
579 return -1;
580 }
581 def = PyModule_GetDef(mod);
582 if (!def) {
583 PyErr_BadInternalCall();
584 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585 }
586 modules = PyImport_GetModuleDict();
Martin v. Löwis1a214512008-06-11 05:26:20 +0000587 if (PyDict_SetItemString(modules, name, mod) < 0)
588 return -1;
589 if (_PyState_AddModule(mod, def) < 0) {
590 PyDict_DelItemString(modules, name);
591 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592 }
Martin v. Löwis1a214512008-06-11 05:26:20 +0000593 if (def->m_size == -1) {
594 if (def->m_base.m_copy) {
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000595 /* Somebody already imported the module,
Martin v. Löwis1a214512008-06-11 05:26:20 +0000596 likely under a different name.
597 XXX this should really not happen. */
598 Py_DECREF(def->m_base.m_copy);
599 def->m_base.m_copy = NULL;
600 }
601 dict = PyModule_GetDict(mod);
602 if (dict == NULL)
603 return -1;
604 def->m_base.m_copy = PyDict_Copy(dict);
605 if (def->m_base.m_copy == NULL)
606 return -1;
607 }
608 PyDict_SetItemString(extensions, filename, (PyObject*)def);
609 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610}
611
612PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000613_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614{
Martin v. Löwis1a214512008-06-11 05:26:20 +0000615 PyObject *mod, *mdict;
616 PyModuleDef* def;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617 if (extensions == NULL)
618 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000619 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
620 if (def == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000622 if (def->m_size == -1) {
623 /* Module does not support repeated initialization */
624 if (def->m_base.m_copy == NULL)
625 return NULL;
626 mod = PyImport_AddModule(name);
627 if (mod == NULL)
628 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000629 mdict = PyModule_GetDict(mod);
630 if (mdict == NULL)
631 return NULL;
632 if (PyDict_Update(mdict, def->m_base.m_copy))
633 return NULL;
634 }
635 else {
636 if (def->m_base.m_init == NULL)
637 return NULL;
638 mod = def->m_base.m_init();
639 if (mod == NULL)
640 return NULL;
641 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
Benjamin Petersonad956532008-09-04 02:28:15 +0000642 Py_DECREF(mod);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000643 }
644 if (_PyState_AddModule(mod, def) < 0) {
645 PyDict_DelItemString(PyImport_GetModuleDict(), name);
646 Py_DECREF(mod);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647 return NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000648 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000650 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Martin v. Löwis1a214512008-06-11 05:26:20 +0000651 name, filename);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000652 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000653
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000654}
655
656
657/* Get the module object corresponding to a module name.
658 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000659 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000660 Because the former action is most common, THIS DOES NOT RETURN A
661 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662
Guido van Rossum79f25d91997-04-29 20:08:16 +0000663PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000664PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000665{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000666 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000667 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000668
Guido van Rossum25ce5661997-08-02 03:10:38 +0000669 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000670 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000671 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000672 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673 if (m == NULL)
674 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000675 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000676 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677 return NULL;
678 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000679 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
681 return m;
682}
683
Tim Peters1cd70172004-08-02 03:52:12 +0000684/* Remove name from sys.modules, if it's there. */
685static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000686remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000687{
688 PyObject *modules = PyImport_GetModuleDict();
689 if (PyDict_GetItemString(modules, name) == NULL)
690 return;
691 if (PyDict_DelItemString(modules, name) < 0)
692 Py_FatalError("import: deleting existing key in"
693 "sys.modules failed");
694}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695
Barry Warsaw28a691b2010-04-17 00:19:56 +0000696static PyObject * get_sourcefile(char *file);
697static char *make_source_pathname(char *pathname, char *buf);
698static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
699 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000700
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000701/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000702 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
703 * removed from sys.modules, to avoid leaving damaged module objects
704 * in sys.modules. The caller may wish to restore the original
705 * module object (if any) in this case; PyImport_ReloadModule is an
706 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000707 *
708 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
709 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000710 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000713{
Barry Warsaw28a691b2010-04-17 00:19:56 +0000714 return PyImport_ExecCodeModuleWithPathnames(
715 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000716}
717
718PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000719PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000720{
Barry Warsaw28a691b2010-04-17 00:19:56 +0000721 return PyImport_ExecCodeModuleWithPathnames(
722 name, co, pathname, (char *)NULL);
723}
724
725PyObject *
726PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
727 char *cpathname)
728{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000729 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000730 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
Guido van Rossum79f25d91997-04-29 20:08:16 +0000732 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000733 if (m == NULL)
734 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000735 /* If the module is being reloaded, we get the old module back
736 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000737 d = PyModule_GetDict(m);
738 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
739 if (PyDict_SetItemString(d, "__builtins__",
740 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000741 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000742 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000743 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000744 v = NULL;
745 if (pathname != NULL) {
Christian Heimes3b06e532008-01-07 20:12:44 +0000746 v = get_sourcefile(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000747 if (v == NULL)
748 PyErr_Clear();
749 }
750 if (v == NULL) {
751 v = ((PyCodeObject *)co)->co_filename;
752 Py_INCREF(v);
753 }
754 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000756 Py_DECREF(v);
757
Barry Warsaw28a691b2010-04-17 00:19:56 +0000758 /* Remember the pyc path name as the __cached__ attribute. */
759 if (cpathname == NULL) {
760 v = Py_None;
761 Py_INCREF(v);
762 }
763 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
764 PyErr_Clear(); /* Not important enough to report */
765 v = Py_None;
766 Py_INCREF(v);
767 }
768 if (PyDict_SetItemString(d, "__cached__", v) != 0)
769 PyErr_Clear(); /* Not important enough to report */
770 Py_DECREF(v);
771
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000772 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000773 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000774 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000775 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000776
Guido van Rossum25ce5661997-08-02 03:10:38 +0000777 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000778 PyErr_Format(PyExc_ImportError,
779 "Loaded module %.200s not found in sys.modules",
780 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000781 return NULL;
782 }
783
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785
786 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000787
788 error:
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000789 remove_module(name);
Tim Peters1cd70172004-08-02 03:52:12 +0000790 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791}
792
793
Barry Warsaw28a691b2010-04-17 00:19:56 +0000794/* Like strrchr(string, '/') but searches for the rightmost of either SEP
795 or ALTSEP, if the latter is defined.
796*/
797static char *
798rightmost_sep(char *s)
799{
800 char *found, c;
801 for (found = NULL; (c = *s); s++) {
802 if (c == SEP
803#ifdef ALTSEP
804 || c == ALTSEP
805#endif
806 )
807 {
808 found = s;
809 }
810 }
811 return found;
812}
813
814
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815/* Given a pathname for a Python source file, fill a buffer with the
816 pathname for the corresponding compiled file. Return the pathname
817 for the compiled file, or NULL if there's no space in the buffer.
818 Doesn't set an exception. */
819
820static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000821make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822{
Barry Warsaw28a691b2010-04-17 00:19:56 +0000823 /* foo.py -> __pycache__/foo.<tag>.pyc */
Tim Petersc1731372001-08-04 08:12:36 +0000824 size_t len = strlen(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000825 size_t i, save;
826 char *pos;
827 int sep = SEP;
828
829 /* Sanity check that the buffer has roughly enough space to hold what
830 will eventually be the full path to the compiled file. The 5 extra
831 bytes include the slash afer __pycache__, the two extra dots, the
832 extra trailing character ('c' or 'o') and null. This isn't exact
833 because the contents of the buffer can affect how many actual
834 characters of the string get into the buffer. We'll do a final
835 sanity check before writing the extension to ensure we do not
836 overflow the buffer.
837 */
838 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000839 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000840
Barry Warsaw28a691b2010-04-17 00:19:56 +0000841 /* Find the last path separator and copy everything from the start of
842 the source string up to and including the separator.
843 */
844 if ((pos = rightmost_sep(pathname)) == NULL) {
845 i = 0;
846 }
847 else {
848 sep = *pos;
849 i = pos - pathname + 1;
850 strncpy(buf, pathname, i);
851 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000852
Barry Warsaw28a691b2010-04-17 00:19:56 +0000853 save = i;
854 buf[i++] = '\0';
855 /* Add __pycache__/ */
856 strcat(buf, CACHEDIR);
857 i += strlen(CACHEDIR) - 1;
858 buf[i++] = sep;
859 buf[i++] = '\0';
860 /* Add the base filename, but remove the .py or .pyw extension, since
861 the tag name must go before the extension.
862 */
863 strcat(buf, pathname + save);
864 if ((pos = strrchr(buf, '.')) != NULL)
865 *++pos = '\0';
866 strcat(buf, pyc_tag);
867 /* The length test above assumes that we're only adding one character
868 to the end of what would normally be the extension. What if there
869 is no extension, or the string ends in '.' or '.p', and otherwise
870 fills the buffer? By appending 4 more characters onto the string
871 here, we could overrun the buffer.
872
873 As a simple example, let's say buflen=32 and the input string is
874 'xxx.py'. strlen() would be 6 and the test above would yield:
875
876 (6 + 11 + 10 + 5 == 32) > 32
877
878 which is false and so the name mangling would continue. This would
879 be fine because we'd end up with this string in buf:
880
881 __pycache__/xxx.cpython-32.pyc\0
882
883 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
884 We can even handle an input string of say 'xxxxx' above because
885 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
886 mangling that yields:
887
888 __pycache__/xxxxxcpython-32.pyc\0
889
890 which is 32 characters including the nul, and thus fits in the
891 buffer. However, an input string of 'xxxxxx' would yield a result
892 string of:
893
894 __pycache__/xxxxxxcpython-32.pyc\0
895
896 which is 33 characters long (including the nul), thus overflowing
897 the buffer, even though the first test would fail, i.e.: the input
898 string is also 6 characters long, so 32 > 32 is false.
899
900 The reason the first test fails but we still overflow the buffer is
901 that the test above only expects to add one extra character to be
902 added to the extension, and here we're adding three (pyc). We
903 don't add the first dot, so that reclaims one of expected
904 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
905 dot - 1 expected extra == 1 overflowed).
906
907 The best we can do is ensure that we still have enough room in the
908 target buffer before we write the extension. Because it's always
909 only the extension that can cause the overflow, and never the other
910 path bytes we've written, it's sufficient to just do one more test
911 here. Still, the assertion that follows can't hurt.
912 */
913#if 0
914 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
915#endif
916 if (strlen(buf) + 5 > buflen)
917 return NULL;
918 strcat(buf, debug ? ".pyc" : ".pyo");
919 assert(strlen(buf) < buflen);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000920 return buf;
921}
922
923
Barry Warsaw28a691b2010-04-17 00:19:56 +0000924/* Given a pathname to a Python byte compiled file, return the path to the
925 source file, if the path matches the PEP 3147 format. This does not check
926 for any file existence, however, if the pyc file name does not match PEP
927 3147 style, NULL is returned. buf must be at least as big as pathname;
928 the resulting path will always be shorter. */
929
930static char *
931make_source_pathname(char *pathname, char *buf)
932{
933 /* __pycache__/foo.<tag>.pyc -> foo.py */
934 size_t i, j;
935 char *left, *right, *dot0, *dot1, sep;
936
937 /* Look back two slashes from the end. In between these two slashes
938 must be the string __pycache__ or this is not a PEP 3147 style
939 path. It's possible for there to be only one slash.
940 */
941 if ((right = rightmost_sep(pathname)) == NULL)
942 return NULL;
943 sep = *right;
944 *right = '\0';
945 left = rightmost_sep(pathname);
946 *right = sep;
947 if (left == NULL)
948 left = pathname;
949 else
950 left++;
951 if (right-left != strlen(CACHEDIR) ||
952 strncmp(left, CACHEDIR, right-left) != 0)
953 return NULL;
954
955 /* Now verify that the path component to the right of the last slash
956 has two dots in it.
957 */
958 if ((dot0 = strchr(right + 1, '.')) == NULL)
959 return NULL;
960 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
961 return NULL;
962 /* Too many dots? */
963 if (strchr(dot1 + 1, '.') != NULL)
964 return NULL;
965
966 /* This is a PEP 3147 path. Start by copying everything from the
967 start of pathname up to and including the leftmost slash. Then
968 copy the file's basename, removing the magic tag and adding a .py
969 suffix.
970 */
971 strncpy(buf, pathname, (i=left-pathname));
972 strncpy(buf+i, right+1, (j=dot0-right));
973 strcpy(buf+i+j, "py");
974 return buf;
975}
976
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000977/* Given a pathname for a Python source file, its time of last
978 modification, and a pathname for a compiled file, check whether the
979 compiled file represents the same version of the source. If so,
980 return a FILE pointer for the compiled file, positioned just after
981 the header; if not, return NULL.
982 Doesn't set an exception. */
983
984static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000985check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000986{
987 FILE *fp;
988 long magic;
989 long pyc_mtime;
990
991 fp = fopen(cpathname, "rb");
992 if (fp == NULL)
993 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000994 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000995 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000996 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000997 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000998 fclose(fp);
999 return NULL;
1000 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001001 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001002 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001003 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001004 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001005 fclose(fp);
1006 return NULL;
1007 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001008 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001009 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010 return fp;
1011}
1012
1013
1014/* Read a code object from a file and check it for validity */
1015
Guido van Rossum79f25d91997-04-29 20:08:16 +00001016static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001017read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001018{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001019 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001020
Tim Petersd9b9ac82001-01-28 00:27:39 +00001021 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +00001022 if (co == NULL)
1023 return NULL;
1024 if (!PyCode_Check(co)) {
1025 PyErr_Format(PyExc_ImportError,
1026 "Non-code object in %.200s", cpathname);
1027 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001028 return NULL;
1029 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001030 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001031}
1032
1033
1034/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001035 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001036
Guido van Rossum79f25d91997-04-29 20:08:16 +00001037static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001038load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001039{
1040 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001041 PyCodeObject *co;
1042 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001043
Guido van Rossum79f25d91997-04-29 20:08:16 +00001044 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +00001045 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001046 PyErr_Format(PyExc_ImportError,
1047 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048 return NULL;
1049 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001050 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001052 if (co == NULL)
1053 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001054 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001055 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001056 name, cpathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001057 m = PyImport_ExecCodeModuleWithPathnames(
1058 name, (PyObject *)co, cpathname, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001059 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001060
1061 return m;
1062}
1063
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064/* Parse a source file and return the corresponding code object */
1065
Guido van Rossum79f25d91997-04-29 20:08:16 +00001066static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069 PyCodeObject *co = NULL;
1070 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001071 PyCompilerFlags flags;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001072 PyArena *arena = PyArena_New();
1073 if (arena == NULL)
1074 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001075
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001076 flags.cf_flags = 0;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001077 mod = PyParser_ASTFromFile(fp, pathname, NULL,
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001078 Py_file_input, 0, 0, &flags,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001079 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001081 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001084 return co;
1085}
1086
1087
Guido van Rossum55a83382000-09-20 20:31:38 +00001088/* Helper to open a bytecode file for writing in exclusive mode */
1089
1090static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001091open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001092{
1093#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
1094 /* Use O_EXCL to avoid a race condition when another process tries to
1095 write the same file. When that happens, our open() call fails,
1096 which is just fine (since it's only a cache).
1097 XXX If the file exists and is writable but the directory is not
1098 writable, the file will never be written. Oh well.
1099 */
1100 int fd;
1101 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +00001102 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
1103#ifdef O_BINARY
1104 |O_BINARY /* necessary for Windows */
1105#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001106#ifdef __VMS
Christian Heimes05e8be12008-02-23 18:30:17 +00001107 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001108#else
Christian Heimes05e8be12008-02-23 18:30:17 +00001109 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001110#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111 );
Guido van Rossum55a83382000-09-20 20:31:38 +00001112 if (fd < 0)
1113 return NULL;
1114 return fdopen(fd, "wb");
1115#else
1116 /* Best we can do -- on Windows this can't happen anyway */
1117 return fopen(filename, "wb");
1118#endif
1119}
1120
1121
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122/* Write a compiled module to a file, placing the time of last
1123 modification of its source into the header.
1124 Errors are ignored, if a write error occurs an attempt is made to
1125 remove the file. */
1126
1127static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001128write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001129{
1130 FILE *fp;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001131 char *dirpath;
Christian Heimes05e8be12008-02-23 18:30:17 +00001132 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001133#ifdef MS_WINDOWS /* since Windows uses different permissions */
1134 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001135 mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct
1136 for Windows?
1137 2010-04-07 BAW */
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001138#else
1139 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001140 mode_t dirmode = (srcstat->st_mode |
1141 S_IXUSR | S_IXGRP | S_IXOTH |
1142 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001143#endif
Barry Warsaw28a691b2010-04-17 00:19:56 +00001144 int saved;
1145
1146 /* Ensure that the __pycache__ directory exists. */
1147 dirpath = rightmost_sep(cpathname);
1148 if (dirpath == NULL) {
1149 if (Py_VerboseFlag)
1150 PySys_WriteStderr(
1151 "# no %s path found %s\n",
1152 CACHEDIR, cpathname);
1153 return;
1154 }
1155 saved = *dirpath;
1156 *dirpath = '\0';
1157 /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */
1158 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
1159 *dirpath = saved;
1160 if (Py_VerboseFlag)
1161 PySys_WriteStderr(
1162 "# cannot create cache dir %s\n", cpathname);
1163 return;
1164 }
1165 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001166
Christian Heimes05e8be12008-02-23 18:30:17 +00001167 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001168 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001169 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001170 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171 "# can't create %s\n", cpathname);
1172 return;
1173 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +00001174 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001175 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +00001176 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1177 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +00001178 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001179 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001180 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001181 /* Don't keep partial file */
1182 fclose(fp);
1183 (void) unlink(cpathname);
1184 return;
1185 }
1186 /* Now write the true mtime */
1187 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +00001189 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001190 fflush(fp);
1191 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001192 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001193 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001194}
1195
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001196static void
1197update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1198{
1199 PyObject *constants, *tmp;
1200 Py_ssize_t i, n;
1201
1202 if (PyUnicode_Compare(co->co_filename, oldname))
1203 return;
1204
1205 tmp = co->co_filename;
1206 co->co_filename = newname;
1207 Py_INCREF(co->co_filename);
1208 Py_DECREF(tmp);
1209
1210 constants = co->co_consts;
1211 n = PyTuple_GET_SIZE(constants);
1212 for (i = 0; i < n; i++) {
1213 tmp = PyTuple_GET_ITEM(constants, i);
1214 if (PyCode_Check(tmp))
1215 update_code_filenames((PyCodeObject *)tmp,
1216 oldname, newname);
1217 }
1218}
1219
1220static int
1221update_compiled_module(PyCodeObject *co, char *pathname)
1222{
1223 PyObject *oldname, *newname;
1224
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001225 newname = PyUnicode_DecodeFSDefault(pathname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001226 if (newname == NULL)
1227 return -1;
1228
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001229 if (!PyUnicode_Compare(co->co_filename, newname)) {
1230 Py_DECREF(newname);
1231 return 0;
1232 }
1233
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001234 oldname = co->co_filename;
1235 Py_INCREF(oldname);
1236 update_code_filenames(co, oldname, newname);
1237 Py_DECREF(oldname);
1238 Py_DECREF(newname);
1239 return 1;
1240}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001241
1242/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001243 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1244 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001245
Guido van Rossum79f25d91997-04-29 20:08:16 +00001246static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001247load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001248{
Christian Heimes05e8be12008-02-23 18:30:17 +00001249 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001250 FILE *fpc;
1251 char buf[MAXPATHLEN+1];
1252 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001253 PyCodeObject *co;
1254 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001255
Christian Heimes05e8be12008-02-23 18:30:17 +00001256 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +00001257 PyErr_Format(PyExc_RuntimeError,
Christian Heimes05e8be12008-02-23 18:30:17 +00001258 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +00001259 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +00001260 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +00001261 }
Fred Drake4c82b232000-06-30 16:18:57 +00001262#if SIZEOF_TIME_T > 4
1263 /* Python's .pyc timestamp handling presumes that the timestamp fits
1264 in 4 bytes. This will be fine until sometime in the year 2038,
1265 when a 4-byte signed time_t will overflow.
1266 */
Christian Heimes05e8be12008-02-23 18:30:17 +00001267 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +00001268 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +00001269 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +00001270 return NULL;
1271 }
1272#endif
Barry Warsaw28a691b2010-04-17 00:19:56 +00001273 cpathname = make_compiled_pathname(
1274 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001275 if (cpathname != NULL &&
Christian Heimes05e8be12008-02-23 18:30:17 +00001276 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001277 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001278 fclose(fpc);
1279 if (co == NULL)
1280 return NULL;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001281 if (update_compiled_module(co, pathname) < 0)
1282 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001283 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001284 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001285 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +00001286 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001287 }
1288 else {
1289 co = parse_source_module(pathname, fp);
1290 if (co == NULL)
1291 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001292 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001293 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001294 name, pathname);
Christian Heimes790c8232008-01-07 21:14:23 +00001295 if (cpathname) {
1296 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1297 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes05e8be12008-02-23 18:30:17 +00001298 write_compiled_module(co, cpathname, &st);
Christian Heimes790c8232008-01-07 21:14:23 +00001299 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001300 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001301 m = PyImport_ExecCodeModuleWithPathnames(
1302 name, (PyObject *)co, pathname, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001303 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001304
1305 return m;
1306}
1307
Christian Heimes3b06e532008-01-07 20:12:44 +00001308/* Get source file -> unicode or None
1309 * Returns the path to the py file if available, else the given path
1310 */
1311static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001312get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001313{
1314 char py[MAXPATHLEN + 1];
1315 Py_ssize_t len;
1316 PyObject *u;
1317 struct stat statbuf;
1318
1319 if (!file || !*file) {
1320 Py_RETURN_NONE;
1321 }
1322
1323 len = strlen(file);
Christian Heimes3540b502008-01-11 07:03:05 +00001324 /* match '*.py?' */
1325 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
Christian Heimes3b06e532008-01-07 20:12:44 +00001326 return PyUnicode_DecodeFSDefault(file);
1327 }
1328
Barry Warsaw28a691b2010-04-17 00:19:56 +00001329 /* Start by trying to turn PEP 3147 path into source path. If that
1330 * fails, just chop off the trailing character, i.e. legacy pyc path
1331 * to py.
1332 */
1333 if (make_source_pathname(file, py) == NULL) {
1334 strncpy(py, file, len-1);
1335 py[len-1] = '\0';
1336 }
1337
Christian Heimes3b06e532008-01-07 20:12:44 +00001338 if (stat(py, &statbuf) == 0 &&
1339 S_ISREG(statbuf.st_mode)) {
1340 u = PyUnicode_DecodeFSDefault(py);
1341 }
1342 else {
1343 u = PyUnicode_DecodeFSDefault(file);
1344 }
1345 return u;
1346}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001347
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001348/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001349static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1350static struct filedescr *find_module(char *, char *, PyObject *,
1351 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001352static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001353
1354/* Load a package and return its module object WITH INCREMENTED
1355 REFERENCE COUNT */
1356
1357static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001358load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001359{
Tim Peters1cd70172004-08-02 03:52:12 +00001360 PyObject *m, *d;
1361 PyObject *file = NULL;
1362 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001363 int err;
1364 char buf[MAXPATHLEN+1];
1365 FILE *fp = NULL;
1366 struct filedescr *fdp;
1367
1368 m = PyImport_AddModule(name);
1369 if (m == NULL)
1370 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001371 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001372 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001373 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001374 d = PyModule_GetDict(m);
Christian Heimes3b06e532008-01-07 20:12:44 +00001375 file = get_sourcefile(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001376 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +00001377 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001378 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001379 if (path == NULL)
1380 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001381 err = PyDict_SetItemString(d, "__file__", file);
1382 if (err == 0)
1383 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001384 if (err != 0)
1385 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001386 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001387 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001388 if (fdp == NULL) {
1389 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1390 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001391 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001392 }
1393 else
1394 m = NULL;
1395 goto cleanup;
1396 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001397 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001398 if (fp != NULL)
1399 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001400 goto cleanup;
1401
1402 error:
1403 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001404 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001405 Py_XDECREF(path);
1406 Py_XDECREF(file);
1407 return m;
1408}
1409
1410
1411/* Helper to test for built-in module */
1412
1413static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001414is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001415{
1416 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001417 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1418 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1419 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001420 return -1;
1421 else
1422 return 1;
1423 }
1424 }
1425 return 0;
1426}
1427
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001428
Just van Rossum52e14d62002-12-30 22:08:05 +00001429/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1430 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001431 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001432 that can handle the path item. Return None if no hook could;
1433 this tells our caller it should fall back to the builtin
1434 import mechanism. Cache the result in path_importer_cache.
1435 Returns a borrowed reference. */
1436
1437static PyObject *
1438get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1439 PyObject *p)
1440{
1441 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001442 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001443
1444 /* These conditions are the caller's responsibility: */
1445 assert(PyList_Check(path_hooks));
1446 assert(PyDict_Check(path_importer_cache));
1447
1448 nhooks = PyList_Size(path_hooks);
1449 if (nhooks < 0)
1450 return NULL; /* Shouldn't happen */
1451
1452 importer = PyDict_GetItem(path_importer_cache, p);
1453 if (importer != NULL)
1454 return importer;
1455
1456 /* set path_importer_cache[p] to None to avoid recursion */
1457 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1458 return NULL;
1459
1460 for (j = 0; j < nhooks; j++) {
1461 PyObject *hook = PyList_GetItem(path_hooks, j);
1462 if (hook == NULL)
1463 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001464 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001465 if (importer != NULL)
1466 break;
1467
1468 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1469 return NULL;
1470 }
1471 PyErr_Clear();
1472 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001473 if (importer == NULL) {
1474 importer = PyObject_CallFunctionObjArgs(
Christian Heimes9cd17752007-11-18 19:35:23 +00001475 (PyObject *)&PyNullImporter_Type, p, NULL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001476 );
1477 if (importer == NULL) {
1478 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1479 PyErr_Clear();
1480 return Py_None;
1481 }
1482 }
1483 }
1484 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001485 int err = PyDict_SetItem(path_importer_cache, p, importer);
1486 Py_DECREF(importer);
1487 if (err != 0)
1488 return NULL;
1489 }
1490 return importer;
1491}
1492
Christian Heimes9cd17752007-11-18 19:35:23 +00001493PyAPI_FUNC(PyObject *)
1494PyImport_GetImporter(PyObject *path) {
1495 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1496
1497 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1498 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1499 importer = get_path_importer(path_importer_cache,
1500 path_hooks, path);
1501 }
1502 }
1503 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1504 return importer;
1505}
1506
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001507/* Search the path (default sys.path) for a module. Return the
1508 corresponding filedescr struct, and (via return arguments) the
1509 pathname and an open file. Return NULL if the module is not found. */
1510
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001511#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001512extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001513 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001514#endif
1515
Martin v. Löwis18e16552006-02-15 17:27:45 +00001516static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001517static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001518static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001519
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001520static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001521find_module(char *fullname, char *subname, PyObject *path, char *buf,
1522 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001523{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001524 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001525 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001526 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001527 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001528 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001529 PyObject *path_hooks, *path_importer_cache;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001530 struct stat statbuf;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001531 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1532 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1533 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001534 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001535#if defined(PYOS_OS2)
1536 size_t saved_len;
1537 size_t saved_namelen;
1538 char *saved_buf = NULL;
1539#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001540 if (p_loader != NULL)
1541 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001542
Just van Rossum52e14d62002-12-30 22:08:05 +00001543 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001544 PyErr_SetString(PyExc_OverflowError,
1545 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001546 return NULL;
1547 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001548 strcpy(name, subname);
1549
1550 /* sys.meta_path import hook */
1551 if (p_loader != NULL) {
1552 PyObject *meta_path;
1553
1554 meta_path = PySys_GetObject("meta_path");
1555 if (meta_path == NULL || !PyList_Check(meta_path)) {
1556 PyErr_SetString(PyExc_ImportError,
1557 "sys.meta_path must be a list of "
1558 "import hooks");
1559 return NULL;
1560 }
1561 Py_INCREF(meta_path); /* zap guard */
1562 npath = PyList_Size(meta_path);
1563 for (i = 0; i < npath; i++) {
1564 PyObject *loader;
1565 PyObject *hook = PyList_GetItem(meta_path, i);
1566 loader = PyObject_CallMethod(hook, "find_module",
1567 "sO", fullname,
1568 path != NULL ?
1569 path : Py_None);
1570 if (loader == NULL) {
1571 Py_DECREF(meta_path);
1572 return NULL; /* true error */
1573 }
1574 if (loader != Py_None) {
1575 /* a loader was found */
1576 *p_loader = loader;
1577 Py_DECREF(meta_path);
1578 return &importhookdescr;
1579 }
1580 Py_DECREF(loader);
1581 }
1582 Py_DECREF(meta_path);
1583 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001584
Benjamin Petersond968e272008-11-05 22:48:33 +00001585 if (find_frozen(fullname) != NULL) {
1586 strcpy(buf, fullname);
1587 return &fd_frozen;
Guido van Rossum0506a431998-08-11 15:07:39 +00001588 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001589
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001590 if (path == NULL) {
1591 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001592 strcpy(buf, name);
1593 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001594 }
Guido van Rossumac279101996-08-22 23:10:58 +00001595#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001596 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1597 if (fp != NULL) {
1598 *p_fp = fp;
1599 return fdp;
1600 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001601#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001602 path = PySys_GetObject("path");
1603 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001604
Guido van Rossum79f25d91997-04-29 20:08:16 +00001605 if (path == NULL || !PyList_Check(path)) {
1606 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001607 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001608 return NULL;
1609 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001610
1611 path_hooks = PySys_GetObject("path_hooks");
1612 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1613 PyErr_SetString(PyExc_ImportError,
1614 "sys.path_hooks must be a list of "
1615 "import hooks");
1616 return NULL;
1617 }
1618 path_importer_cache = PySys_GetObject("path_importer_cache");
1619 if (path_importer_cache == NULL ||
1620 !PyDict_Check(path_importer_cache)) {
1621 PyErr_SetString(PyExc_ImportError,
1622 "sys.path_importer_cache must be a dict");
1623 return NULL;
1624 }
1625
Guido van Rossum79f25d91997-04-29 20:08:16 +00001626 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001627 namelen = strlen(name);
1628 for (i = 0; i < npath; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001629 PyObject *v = PyList_GetItem(path, i);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001630 PyObject *origv = v;
Guido van Rossum6262cc72007-05-09 23:29:27 +00001631 const char *base;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001632 Py_ssize_t size;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001633 if (!v)
1634 return NULL;
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001635 if (PyUnicode_Check(v)) {
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001636 v = PyUnicode_AsEncodedString(v,
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001637 Py_FileSystemDefaultEncoding, NULL);
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001638 if (v == NULL)
1639 return NULL;
1640 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001641 else if (!PyBytes_Check(v))
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001642 continue;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001643 else
1644 Py_INCREF(v);
1645
Christian Heimes72b710a2008-05-26 13:28:38 +00001646 base = PyBytes_AS_STRING(v);
1647 size = PyBytes_GET_SIZE(v);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001648 len = size;
Walter Dörwald3430d702002-06-17 10:43:59 +00001649 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001650 Py_DECREF(v);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001651 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001652 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001653 strcpy(buf, base);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001654 Py_DECREF(v);
1655
Walter Dörwald3430d702002-06-17 10:43:59 +00001656 if (strlen(buf) != len) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001657 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001658 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001659
1660 /* sys.path_hooks import hook */
1661 if (p_loader != NULL) {
1662 PyObject *importer;
1663
1664 importer = get_path_importer(path_importer_cache,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001665 path_hooks, origv);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001666 if (importer == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001667 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001668 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001669 /* Note: importer is a borrowed reference */
1670 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001671 PyObject *loader;
1672 loader = PyObject_CallMethod(importer,
1673 "find_module",
1674 "s", fullname);
1675 if (loader == NULL)
1676 return NULL; /* error */
1677 if (loader != Py_None) {
1678 /* a loader was found */
1679 *p_loader = loader;
1680 return &importhookdescr;
1681 }
1682 Py_DECREF(loader);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001683 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001684 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001685 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001686 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001687
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001688 if (len > 0 && buf[len-1] != SEP
1689#ifdef ALTSEP
1690 && buf[len-1] != ALTSEP
1691#endif
1692 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001693 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001694 strcpy(buf+len, name);
1695 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001696
1697 /* Check for package import (buf holds a directory name,
1698 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001699#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001700 if (stat(buf, &statbuf) == 0 && /* it exists */
1701 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001702 case_ok(buf, len, namelen, name)) { /* case matches */
1703 if (find_init_module(buf)) { /* and has __init__.py */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001704 return &fd_package;
1705 }
1706 else {
1707 char warnstr[MAXPATHLEN+80];
1708 sprintf(warnstr, "Not importing directory "
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001709 "'%.*s': missing __init__.py",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001710 MAXPATHLEN, buf);
Skip Montanaro46fc3372007-08-12 11:44:53 +00001711 if (PyErr_WarnEx(PyExc_ImportWarning,
1712 warnstr, 1)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001713 return NULL;
1714 }
1715 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001716 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001717#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001718#if defined(PYOS_OS2)
1719 /* take a snapshot of the module spec for restoration
1720 * after the 8 character DLL hackery
1721 */
1722 saved_buf = strdup(buf);
1723 saved_len = len;
1724 saved_namelen = namelen;
1725#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001726 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001727#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001728 /* OS/2 limits DLLs to 8 character names (w/o
1729 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001730 * so if the name is longer than that and its a
1731 * dynamically loaded module we're going to try,
1732 * truncate the name before trying
1733 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001734 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001735 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001736 const struct filedescr *scan;
1737 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001738 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001739 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001740 break;
1741 else
1742 scan++;
1743 }
1744 if (scan->suffix != NULL) {
1745 /* yes, so truncate the name */
1746 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001747 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001748 buf[len] = '\0';
1749 }
1750 }
1751#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001752 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001753 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001754 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001755 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001756 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001757 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001758 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001759 if (fp != NULL) {
1760 if (case_ok(buf, len, namelen, name))
1761 break;
1762 else { /* continue search */
1763 fclose(fp);
1764 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001765 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001766 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001767#if defined(PYOS_OS2)
1768 /* restore the saved snapshot */
1769 strcpy(buf, saved_buf);
1770 len = saved_len;
1771 namelen = saved_namelen;
1772#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001773 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001774#if defined(PYOS_OS2)
1775 /* don't need/want the module name snapshot anymore */
1776 if (saved_buf)
1777 {
1778 free(saved_buf);
1779 saved_buf = NULL;
1780 }
1781#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001782 if (fp != NULL)
1783 break;
1784 }
1785 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001786 PyErr_Format(PyExc_ImportError,
1787 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001788 return NULL;
1789 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001790 *p_fp = fp;
1791 return fdp;
1792}
1793
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001794/* Helpers for main.c
1795 * Find the source file corresponding to a named module
1796 */
1797struct filedescr *
1798_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1799 size_t buflen, FILE **p_fp, PyObject **p_loader)
1800{
1801 return find_module((char *) name, (char *) name, path,
1802 buf, buflen, p_fp, p_loader);
1803}
1804
1805PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1806{
1807 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1808}
1809
Martin v. Löwis18e16552006-02-15 17:27:45 +00001810/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001811 * The arguments here are tricky, best shown by example:
1812 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1813 * ^ ^ ^ ^
1814 * |--------------------- buf ---------------------|
1815 * |------------------- len ------------------|
1816 * |------ name -------|
1817 * |----- namelen -----|
1818 * buf is the full path, but len only counts up to (& exclusive of) the
1819 * extension. name is the module name, also exclusive of extension.
1820 *
1821 * We've already done a successful stat() or fopen() on buf, so know that
1822 * there's some match, possibly case-insensitive.
1823 *
Tim Peters50d8d372001-02-28 05:34:27 +00001824 * case_ok() is to return 1 if there's a case-sensitive match for
1825 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1826 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001827 *
Tim Peters50d8d372001-02-28 05:34:27 +00001828 * case_ok() is used to implement case-sensitive import semantics even
1829 * on platforms with case-insensitive filesystems. It's trivial to implement
1830 * for case-sensitive filesystems. It's pretty much a cross-platform
1831 * nightmare for systems with case-insensitive filesystems.
1832 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001833
Tim Peters50d8d372001-02-28 05:34:27 +00001834/* First we may need a pile of platform-specific header files; the sequence
1835 * of #if's here should match the sequence in the body of case_ok().
1836 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001837#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001838#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001839
Tim Peters50d8d372001-02-28 05:34:27 +00001840#elif defined(DJGPP)
1841#include <dir.h>
1842
Jason Tishler7961aa62005-05-20 00:56:54 +00001843#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001844#include <sys/types.h>
1845#include <dirent.h>
1846
Andrew MacIntyred9400542002-02-26 11:41:34 +00001847#elif defined(PYOS_OS2)
1848#define INCL_DOS
1849#define INCL_DOSERRORS
1850#define INCL_NOPMAPI
1851#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001852#endif
1853
Guido van Rossum0980bd91998-02-13 17:18:36 +00001854static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001855case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001856{
Tim Peters50d8d372001-02-28 05:34:27 +00001857/* Pick a platform-specific implementation; the sequence of #if's here should
1858 * match the sequence just above.
1859 */
1860
Jason Tishler7961aa62005-05-20 00:56:54 +00001861/* MS_WINDOWS */
1862#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001863 WIN32_FIND_DATA data;
1864 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001865
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001866 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001867 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001868
Guido van Rossum0980bd91998-02-13 17:18:36 +00001869 h = FindFirstFile(buf, &data);
1870 if (h == INVALID_HANDLE_VALUE) {
1871 PyErr_Format(PyExc_NameError,
1872 "Can't find file for module %.100s\n(filename %.300s)",
1873 name, buf);
1874 return 0;
1875 }
1876 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001877 return strncmp(data.cFileName, name, namelen) == 0;
1878
1879/* DJGPP */
1880#elif defined(DJGPP)
1881 struct ffblk ffblk;
1882 int done;
1883
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001884 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001885 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001886
1887 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1888 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001889 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001890 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001891 name, buf);
1892 return 0;
1893 }
Tim Peters50d8d372001-02-28 05:34:27 +00001894 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001895
Jason Tishler7961aa62005-05-20 00:56:54 +00001896/* new-fangled macintosh (macosx) or Cygwin */
1897#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001898 DIR *dirp;
1899 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001900 char dirname[MAXPATHLEN + 1];
1901 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001902
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001903 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001904 return 1;
1905
Tim Petersd1e87a82001-03-01 18:12:00 +00001906 /* Copy the dir component into dirname; substitute "." if empty */
1907 if (dirlen <= 0) {
1908 dirname[0] = '.';
1909 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001910 }
1911 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001912 assert(dirlen <= MAXPATHLEN);
1913 memcpy(dirname, buf, dirlen);
1914 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001915 }
1916 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001917 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001918 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001919 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001920 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001921 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001922#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001923 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001924#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001925 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001926#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001927 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001928 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001929 (void)closedir(dirp);
1930 return 1; /* Found */
1931 }
1932 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001933 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001934 }
Tim Peters430f5d42001-03-01 01:30:56 +00001935 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001936
Andrew MacIntyred9400542002-02-26 11:41:34 +00001937/* OS/2 */
1938#elif defined(PYOS_OS2)
1939 HDIR hdir = 1;
1940 ULONG srchcnt = 1;
1941 FILEFINDBUF3 ffbuf;
1942 APIRET rc;
1943
Christian Heimes790c8232008-01-07 21:14:23 +00001944 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001945 return 1;
1946
1947 rc = DosFindFirst(buf,
1948 &hdir,
1949 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1950 &ffbuf, sizeof(ffbuf),
1951 &srchcnt,
1952 FIL_STANDARD);
1953 if (rc != NO_ERROR)
1954 return 0;
1955 return strncmp(ffbuf.achName, name, namelen) == 0;
1956
Tim Peters50d8d372001-02-28 05:34:27 +00001957/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1958#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001959 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001960
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001961#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001962}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001963
Guido van Rossum0980bd91998-02-13 17:18:36 +00001964
Guido van Rossum197346f1997-10-31 18:38:52 +00001965#ifdef HAVE_STAT
1966/* Helper to look for __init__.py or __init__.py[co] in potential package */
1967static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001968find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001969{
Tim Peters0f9431f2001-07-05 03:47:53 +00001970 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001971 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001972 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001973 struct stat statbuf;
1974
Tim Peters0f9431f2001-07-05 03:47:53 +00001975/* For calling case_ok(buf, len, namelen, name):
1976 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1977 * ^ ^ ^ ^
1978 * |--------------------- buf ---------------------|
1979 * |------------------- len ------------------|
1980 * |------ name -------|
1981 * |----- namelen -----|
1982 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001983 if (save_len + 13 >= MAXPATHLEN)
1984 return 0;
1985 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001986 pname = buf + i;
1987 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001988 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001989 if (case_ok(buf,
1990 save_len + 9, /* len("/__init__") */
1991 8, /* len("__init__") */
1992 pname)) {
1993 buf[save_len] = '\0';
1994 return 1;
1995 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001996 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001997 i += strlen(pname);
1998 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001999 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00002000 if (case_ok(buf,
2001 save_len + 9, /* len("/__init__") */
2002 8, /* len("__init__") */
2003 pname)) {
2004 buf[save_len] = '\0';
2005 return 1;
2006 }
Guido van Rossum197346f1997-10-31 18:38:52 +00002007 }
2008 buf[save_len] = '\0';
2009 return 0;
2010}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002011
Guido van Rossum197346f1997-10-31 18:38:52 +00002012#endif /* HAVE_STAT */
2013
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002014
Tim Petersdbd9ba62000-07-09 03:09:57 +00002015static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002016
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002017/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002018 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002019
Guido van Rossum79f25d91997-04-29 20:08:16 +00002020static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002021load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002022{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002023 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002024 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002025 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002026
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002027 /* First check that there's an open file (if we need one) */
2028 switch (type) {
2029 case PY_SOURCE:
2030 case PY_COMPILED:
2031 if (fp == NULL) {
2032 PyErr_Format(PyExc_ValueError,
2033 "file object required for import (type code %d)",
2034 type);
2035 return NULL;
2036 }
2037 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002038
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002039 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002040
2041 case PY_SOURCE:
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002042 m = load_source_module(name, pathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002043 break;
2044
2045 case PY_COMPILED:
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002046 m = load_compiled_module(name, pathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002047 break;
2048
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002049#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002050 case C_EXTENSION:
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002051 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002052 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002053#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002054
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002055 case PKG_DIRECTORY:
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002056 m = load_package(name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002057 break;
2058
2059 case C_BUILTIN:
2060 case PY_FROZEN:
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002061 if (pathname != NULL && pathname[0] != '\0')
2062 name = pathname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002063 if (type == C_BUILTIN)
2064 err = init_builtin(name);
2065 else
2066 err = PyImport_ImportFrozenModule(name);
2067 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00002068 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002069 if (err == 0) {
2070 PyErr_Format(PyExc_ImportError,
2071 "Purported %s module %.200s not found",
2072 type == C_BUILTIN ?
2073 "builtin" : "frozen",
2074 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00002075 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002076 }
2077 modules = PyImport_GetModuleDict();
2078 m = PyDict_GetItemString(modules, name);
2079 if (m == NULL) {
2080 PyErr_Format(
2081 PyExc_ImportError,
2082 "%s module %.200s not properly initialized",
2083 type == C_BUILTIN ?
2084 "builtin" : "frozen",
2085 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00002086 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002087 }
2088 Py_INCREF(m);
2089 break;
2090
Just van Rossum52e14d62002-12-30 22:08:05 +00002091 case IMP_HOOK: {
2092 if (loader == NULL) {
2093 PyErr_SetString(PyExc_ImportError,
2094 "import hook without loader");
2095 return NULL;
2096 }
2097 m = PyObject_CallMethod(loader, "load_module", "s", name);
2098 break;
2099 }
2100
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002102 PyErr_Format(PyExc_ImportError,
2103 "Don't know how to import %.200s (type code %d)",
2104 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002105 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002106
2107 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002108
2109 return m;
2110}
2111
2112
2113/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002114 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002115 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002116
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002117static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002118init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002119{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002120 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002121
Greg Ward201baee2001-10-04 14:52:06 +00002122 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002123 return 1;
2124
Guido van Rossum771c6c81997-10-31 18:37:24 +00002125 for (p = PyImport_Inittab; p->name != NULL; p++) {
Martin v. Löwis1a214512008-06-11 05:26:20 +00002126 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002127 if (strcmp(name, p->name) == 0) {
2128 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002129 PyErr_Format(PyExc_ImportError,
2130 "Cannot re-init internal module %.200s",
2131 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00002132 return -1;
2133 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002134 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00002135 PySys_WriteStderr("import %s # builtin\n", name);
Martin v. Löwis1a214512008-06-11 05:26:20 +00002136 mod = (*p->initfunc)();
2137 if (mod == 0)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002138 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00002139 if (_PyImport_FixupExtension(mod, name, name) < 0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002140 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00002141 /* FixupExtension has put the module into sys.modules,
2142 so we can release our own reference. */
2143 Py_DECREF(mod);
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002144 return 1;
2145 }
2146 }
2147 return 0;
2148}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002149
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002151/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002152
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002153static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002154find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002155{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002156 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002157
Benjamin Petersond968e272008-11-05 22:48:33 +00002158 if (!name)
2159 return NULL;
2160
Guido van Rossum79f25d91997-04-29 20:08:16 +00002161 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002162 if (p->name == NULL)
2163 return NULL;
2164 if (strcmp(p->name, name) == 0)
2165 break;
2166 }
2167 return p;
2168}
2169
Guido van Rossum79f25d91997-04-29 20:08:16 +00002170static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002171get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002172{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002173 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00002174 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002175
2176 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002177 PyErr_Format(PyExc_ImportError,
2178 "No such frozen object named %.200s",
2179 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002180 return NULL;
2181 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00002182 if (p->code == NULL) {
2183 PyErr_Format(PyExc_ImportError,
2184 "Excluded frozen object named %.200s",
2185 name);
2186 return NULL;
2187 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00002188 size = p->size;
2189 if (size < 0)
2190 size = -size;
2191 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002192}
2193
Brett Cannon8d110132009-03-15 02:20:16 +00002194static PyObject *
2195is_frozen_package(char *name)
2196{
2197 struct _frozen *p = find_frozen(name);
2198 int size;
2199
2200 if (p == NULL) {
2201 PyErr_Format(PyExc_ImportError,
2202 "No such frozen object named %.200s",
2203 name);
2204 return NULL;
2205 }
2206
2207 size = p->size;
2208
2209 if (size < 0)
2210 Py_RETURN_TRUE;
2211 else
2212 Py_RETURN_FALSE;
2213}
2214
2215
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002216/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002217 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002218 an exception set if the initialization failed.
2219 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002220
2221int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002222PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002223{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002224 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002225 PyObject *co;
2226 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002227 int ispackage;
2228 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002229
2230 if (p == NULL)
2231 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00002232 if (p->code == NULL) {
2233 PyErr_Format(PyExc_ImportError,
2234 "Excluded frozen object named %.200s",
2235 name);
2236 return -1;
2237 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00002238 size = p->size;
2239 ispackage = (size < 0);
2240 if (ispackage)
2241 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002242 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00002243 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00002244 name, ispackage ? " package" : "");
2245 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002246 if (co == NULL)
2247 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002248 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002249 PyErr_Format(PyExc_TypeError,
2250 "frozen object %.200s is not a code object",
2251 name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002252 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002253 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00002254 if (ispackage) {
2255 /* Set __path__ to the package name */
Benjamin Petersond968e272008-11-05 22:48:33 +00002256 PyObject *d, *s, *l;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002257 int err;
2258 m = PyImport_AddModule(name);
2259 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002260 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002261 d = PyModule_GetDict(m);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002262 s = PyUnicode_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00002263 if (s == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002264 goto err_return;
Benjamin Petersond968e272008-11-05 22:48:33 +00002265 l = PyList_New(1);
2266 if (l == NULL) {
2267 Py_DECREF(s);
2268 goto err_return;
2269 }
2270 PyList_SET_ITEM(l, 0, s);
2271 err = PyDict_SetItemString(d, "__path__", l);
2272 Py_DECREF(l);
Guido van Rossuma5568d31998-03-05 03:45:08 +00002273 if (err != 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002274 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00002275 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00002276 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002277 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002278 goto err_return;
2279 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002280 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002281 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002282err_return:
2283 Py_DECREF(co);
2284 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002285}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002286
2287
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002288/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002289 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002290
Guido van Rossum79f25d91997-04-29 20:08:16 +00002291PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002292PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002293{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002294 PyObject *pname;
2295 PyObject *result;
2296
Martin v. Löwis5b222132007-06-10 09:51:05 +00002297 pname = PyUnicode_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00002298 if (pname == NULL)
2299 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002300 result = PyImport_Import(pname);
2301 Py_DECREF(pname);
2302 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002303}
2304
Christian Heimes072c0f12008-01-03 23:01:04 +00002305/* Import a module without blocking
2306 *
2307 * At first it tries to fetch the module from sys.modules. If the module was
2308 * never loaded before it loads it with PyImport_ImportModule() unless another
2309 * thread holds the import lock. In the latter case the function raises an
2310 * ImportError instead of blocking.
2311 *
2312 * Returns the module object with incremented ref count.
2313 */
2314PyObject *
2315PyImport_ImportModuleNoBlock(const char *name)
2316{
2317 PyObject *result;
2318 PyObject *modules;
2319 long me;
2320
2321 /* Try to get the module from sys.modules[name] */
2322 modules = PyImport_GetModuleDict();
2323 if (modules == NULL)
2324 return NULL;
2325
2326 result = PyDict_GetItemString(modules, name);
2327 if (result != NULL) {
2328 Py_INCREF(result);
2329 return result;
2330 }
2331 else {
2332 PyErr_Clear();
2333 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002334#ifdef WITH_THREAD
Christian Heimes072c0f12008-01-03 23:01:04 +00002335 /* check the import lock
2336 * me might be -1 but I ignore the error here, the lock function
2337 * takes care of the problem */
2338 me = PyThread_get_thread_ident();
2339 if (import_lock_thread == -1 || import_lock_thread == me) {
2340 /* no thread or me is holding the lock */
2341 return PyImport_ImportModule(name);
2342 }
2343 else {
2344 PyErr_Format(PyExc_ImportError,
2345 "Failed to import %.200s because the import lock"
2346 "is held by another thread.",
2347 name);
2348 return NULL;
2349 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002350#else
2351 return PyImport_ImportModule(name);
2352#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002353}
2354
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002355/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002356static PyObject *get_parent(PyObject *globals, char *buf,
2357 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002358static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002359 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002360static int mark_miss(char *name);
2361static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002362 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002363static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002364
2365/* The Magnum Opus of dotted-name import :-) */
2366
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002367static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002368import_module_level(char *name, PyObject *globals, PyObject *locals,
2369 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002370{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002371 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002372 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002373 PyObject *parent, *head, *next, *tail;
2374
Christian Heimes454f37b2008-01-10 00:10:02 +00002375 if (strchr(name, '/') != NULL
2376#ifdef MS_WINDOWS
2377 || strchr(name, '\\') != NULL
2378#endif
2379 ) {
2380 PyErr_SetString(PyExc_ImportError,
2381 "Import by filename is not supported.");
2382 return NULL;
2383 }
2384
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002385 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002386 if (parent == NULL)
2387 return NULL;
2388
2389 head = load_next(parent, Py_None, &name, buf, &buflen);
2390 if (head == NULL)
2391 return NULL;
2392
2393 tail = head;
2394 Py_INCREF(tail);
2395 while (name) {
2396 next = load_next(tail, tail, &name, buf, &buflen);
2397 Py_DECREF(tail);
2398 if (next == NULL) {
2399 Py_DECREF(head);
2400 return NULL;
2401 }
2402 tail = next;
2403 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002404 if (tail == Py_None) {
2405 /* If tail is Py_None, both get_parent and load_next found
2406 an empty module name: someone called __import__("") or
2407 doctored faulty bytecode */
2408 Py_DECREF(tail);
2409 Py_DECREF(head);
2410 PyErr_SetString(PyExc_ValueError,
2411 "Empty module name");
2412 return NULL;
2413 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002414
2415 if (fromlist != NULL) {
2416 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2417 fromlist = NULL;
2418 }
2419
2420 if (fromlist == NULL) {
2421 Py_DECREF(tail);
2422 return head;
2423 }
2424
2425 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002426 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002427 Py_DECREF(tail);
2428 return NULL;
2429 }
2430
2431 return tail;
2432}
2433
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002434PyObject *
2435PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2436 PyObject *fromlist, int level)
2437{
2438 PyObject *result;
Benjamin Peterson0df35a92009-10-04 20:32:25 +00002439 _PyImport_AcquireLock();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002440 result = import_module_level(name, globals, locals, fromlist, level);
Benjamin Peterson0df35a92009-10-04 20:32:25 +00002441 if (_PyImport_ReleaseLock() < 0) {
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002442 Py_XDECREF(result);
2443 PyErr_SetString(PyExc_RuntimeError,
2444 "not holding the import lock");
2445 return NULL;
2446 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002447 return result;
2448}
2449
Fred Drake87590902004-05-28 20:21:36 +00002450/* Return the package that an import is being performed in. If globals comes
2451 from the module foo.bar.bat (not itself a package), this returns the
2452 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002453 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002454
2455 The *name* of the returned package is returned in buf, with the length of
2456 the name in *p_buflen.
2457
2458 If globals doesn't come from a package or a module in a package, or a
2459 corresponding entry is not found in sys.modules, Py_None is returned.
2460*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002461static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002462get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002463{
2464 static PyObject *namestr = NULL;
2465 static PyObject *pathstr = NULL;
Nick Coghlande10c852007-12-04 12:22:52 +00002466 static PyObject *pkgstr = NULL;
2467 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Georg Brandl2ee470f2008-07-16 12:55:28 +00002468 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002469
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002470 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002471 return Py_None;
2472
2473 if (namestr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002474 namestr = PyUnicode_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002475 if (namestr == NULL)
2476 return NULL;
2477 }
2478 if (pathstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002479 pathstr = PyUnicode_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002480 if (pathstr == NULL)
2481 return NULL;
2482 }
Nick Coghlande10c852007-12-04 12:22:52 +00002483 if (pkgstr == NULL) {
2484 pkgstr = PyUnicode_InternFromString("__package__");
2485 if (pkgstr == NULL)
2486 return NULL;
2487 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002488
2489 *buf = '\0';
2490 *p_buflen = 0;
Nick Coghlande10c852007-12-04 12:22:52 +00002491 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002492
Nick Coghlande10c852007-12-04 12:22:52 +00002493 if ((pkgname != NULL) && (pkgname != Py_None)) {
2494 /* __package__ is set, so use it */
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002495 char *pkgname_str;
Nick Coghlande10c852007-12-04 12:22:52 +00002496 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002497
Nick Coghlande10c852007-12-04 12:22:52 +00002498 if (!PyUnicode_Check(pkgname)) {
2499 PyErr_SetString(PyExc_ValueError,
2500 "__package__ set to non-string");
2501 return NULL;
2502 }
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00002503 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
Nick Coghlande10c852007-12-04 12:22:52 +00002504 if (len == 0) {
2505 if (level > 0) {
2506 PyErr_SetString(PyExc_ValueError,
2507 "Attempted relative import in non-package");
2508 return NULL;
2509 }
2510 return Py_None;
2511 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002512 if (len > MAXPATHLEN) {
2513 PyErr_SetString(PyExc_ValueError,
Nick Coghlande10c852007-12-04 12:22:52 +00002514 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002515 return NULL;
2516 }
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002517 strcpy(buf, pkgname_str);
Nick Coghlande10c852007-12-04 12:22:52 +00002518 } else {
2519 /* __package__ not set, so figure it out and set it */
2520 modname = PyDict_GetItem(globals, namestr);
2521 if (modname == NULL || !PyUnicode_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002522 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002523
Nick Coghlande10c852007-12-04 12:22:52 +00002524 modpath = PyDict_GetItem(globals, pathstr);
2525 if (modpath != NULL) {
2526 /* __path__ is set, so modname is already the package name */
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002527 char *modname_str;
2528 Py_ssize_t len;
Nick Coghlande10c852007-12-04 12:22:52 +00002529 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002530
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00002531 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
Nick Coghlande10c852007-12-04 12:22:52 +00002532 if (len > MAXPATHLEN) {
2533 PyErr_SetString(PyExc_ValueError,
2534 "Module name too long");
2535 return NULL;
2536 }
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002537 strcpy(buf, modname_str);
Nick Coghlande10c852007-12-04 12:22:52 +00002538 error = PyDict_SetItem(globals, pkgstr, modname);
2539 if (error) {
2540 PyErr_SetString(PyExc_ValueError,
2541 "Could not set __package__");
2542 return NULL;
2543 }
2544 } else {
2545 /* Normal module, so work out the package name if any */
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00002546 char *start = _PyUnicode_AsString(modname);
Nick Coghlande10c852007-12-04 12:22:52 +00002547 char *lastdot = strrchr(start, '.');
2548 size_t len;
2549 int error;
2550 if (lastdot == NULL && level > 0) {
2551 PyErr_SetString(PyExc_ValueError,
2552 "Attempted relative import in non-package");
2553 return NULL;
2554 }
2555 if (lastdot == NULL) {
2556 error = PyDict_SetItem(globals, pkgstr, Py_None);
2557 if (error) {
2558 PyErr_SetString(PyExc_ValueError,
2559 "Could not set __package__");
2560 return NULL;
2561 }
2562 return Py_None;
2563 }
2564 len = lastdot - start;
2565 if (len >= MAXPATHLEN) {
2566 PyErr_SetString(PyExc_ValueError,
2567 "Module name too long");
2568 return NULL;
2569 }
2570 strncpy(buf, start, len);
2571 buf[len] = '\0';
2572 pkgname = PyUnicode_FromString(buf);
2573 if (pkgname == NULL) {
2574 return NULL;
2575 }
2576 error = PyDict_SetItem(globals, pkgstr, pkgname);
2577 Py_DECREF(pkgname);
2578 if (error) {
2579 PyErr_SetString(PyExc_ValueError,
2580 "Could not set __package__");
2581 return NULL;
2582 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002583 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002584 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002585 while (--level > 0) {
2586 char *dot = strrchr(buf, '.');
2587 if (dot == NULL) {
2588 PyErr_SetString(PyExc_ValueError,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002589 "Attempted relative import beyond "
2590 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002591 return NULL;
2592 }
2593 *dot = '\0';
2594 }
2595 *p_buflen = strlen(buf);
2596
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002597 modules = PyImport_GetModuleDict();
2598 parent = PyDict_GetItemString(modules, buf);
Georg Brandl2ee470f2008-07-16 12:55:28 +00002599 if (parent == NULL) {
2600 if (orig_level < 1) {
2601 PyObject *err_msg = PyBytes_FromFormat(
2602 "Parent module '%.200s' not found "
2603 "while handling absolute import", buf);
2604 if (err_msg == NULL) {
2605 return NULL;
2606 }
2607 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2608 PyBytes_AsString(err_msg), 1)) {
2609 *buf = '\0';
2610 *p_buflen = 0;
2611 parent = Py_None;
2612 }
2613 Py_DECREF(err_msg);
2614 } else {
2615 PyErr_Format(PyExc_SystemError,
2616 "Parent module '%.200s' not loaded, "
2617 "cannot perform relative import", buf);
2618 }
2619 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002620 return parent;
2621 /* We expect, but can't guarantee, if parent != None, that:
2622 - parent.__name__ == buf
2623 - parent.__dict__ is globals
2624 If this is violated... Who cares? */
2625}
2626
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002627/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002628static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002629load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002630 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002631{
2632 char *name = *p_name;
2633 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002634 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002635 char *p;
2636 PyObject *result;
2637
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002638 if (strlen(name) == 0) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639 /* completely empty module name should only happen in
2640 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002641 Py_INCREF(mod);
2642 *p_name = NULL;
2643 return mod;
2644 }
2645
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002646 if (dot == NULL) {
2647 *p_name = NULL;
2648 len = strlen(name);
2649 }
2650 else {
2651 *p_name = dot+1;
2652 len = dot-name;
2653 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002654 if (len == 0) {
2655 PyErr_SetString(PyExc_ValueError,
2656 "Empty module name");
2657 return NULL;
2658 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002659
2660 p = buf + *p_buflen;
2661 if (p != buf)
2662 *p++ = '.';
2663 if (p+len-buf >= MAXPATHLEN) {
2664 PyErr_SetString(PyExc_ValueError,
2665 "Module name too long");
2666 return NULL;
2667 }
2668 strncpy(p, name, len);
2669 p[len] = '\0';
2670 *p_buflen = p+len-buf;
2671
2672 result = import_submodule(mod, p, buf);
2673 if (result == Py_None && altmod != mod) {
2674 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002675 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002676 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002677 if (result != NULL && result != Py_None) {
2678 if (mark_miss(buf) != 0) {
2679 Py_DECREF(result);
2680 return NULL;
2681 }
2682 strncpy(buf, name, len);
2683 buf[len] = '\0';
2684 *p_buflen = len;
2685 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002686 }
2687 if (result == NULL)
2688 return NULL;
2689
2690 if (result == Py_None) {
2691 Py_DECREF(result);
2692 PyErr_Format(PyExc_ImportError,
2693 "No module named %.200s", name);
2694 return NULL;
2695 }
2696
2697 return result;
2698}
2699
2700static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002701mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002702{
2703 PyObject *modules = PyImport_GetModuleDict();
2704 return PyDict_SetItemString(modules, name, Py_None);
2705}
2706
2707static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002708ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002709 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002710{
2711 int i;
2712
2713 if (!PyObject_HasAttrString(mod, "__path__"))
2714 return 1;
2715
2716 for (i = 0; ; i++) {
2717 PyObject *item = PySequence_GetItem(fromlist, i);
2718 int hasit;
2719 if (item == NULL) {
2720 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2721 PyErr_Clear();
2722 return 1;
2723 }
2724 return 0;
2725 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002726 if (!PyUnicode_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002727 PyErr_SetString(PyExc_TypeError,
Neal Norwitz80e7f272007-08-26 06:45:23 +00002728 "Item in ``from list'' not a string");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002729 Py_DECREF(item);
2730 return 0;
2731 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002732 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002733 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002734 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002735 /* See if the package defines __all__ */
2736 if (recursive)
2737 continue; /* Avoid endless recursion */
2738 all = PyObject_GetAttrString(mod, "__all__");
2739 if (all == NULL)
2740 PyErr_Clear();
2741 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002742 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002743 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002744 if (!ret)
2745 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002746 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002747 continue;
2748 }
2749 hasit = PyObject_HasAttr(mod, item);
2750 if (!hasit) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002751 PyObject *item8;
2752 char *subname;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002753 PyObject *submod;
2754 char *p;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002755 if (!Py_FileSystemDefaultEncoding) {
2756 item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item),
2757 PyUnicode_GetSize(item),
Martin v. Löwis427dbff2007-06-12 05:53:00 +00002758 NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002759 } else {
Guido van Rossum98297ee2007-11-06 21:34:58 +00002760 item8 = PyUnicode_AsEncodedString(item,
2761 Py_FileSystemDefaultEncoding, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002762 }
2763 if (!item8) {
2764 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2765 return 0;
2766 }
Christian Heimes72b710a2008-05-26 13:28:38 +00002767 subname = PyBytes_AS_STRING(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002768 if (buflen + strlen(subname) >= MAXPATHLEN) {
2769 PyErr_SetString(PyExc_ValueError,
2770 "Module name too long");
2771 Py_DECREF(item);
2772 return 0;
2773 }
2774 p = buf + buflen;
2775 *p++ = '.';
2776 strcpy(p, subname);
2777 submod = import_submodule(mod, subname, buf);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002778 Py_DECREF(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002779 Py_XDECREF(submod);
2780 if (submod == NULL) {
2781 Py_DECREF(item);
2782 return 0;
2783 }
2784 }
2785 Py_DECREF(item);
2786 }
2787
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002788 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002789}
2790
Neil Schemenauer00b09662003-06-16 21:03:07 +00002791static int
2792add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2793 PyObject *modules)
2794{
2795 if (mod == Py_None)
2796 return 1;
2797 /* Irrespective of the success of this load, make a
2798 reference to it in the parent package module. A copy gets
2799 saved in the modules dictionary under the full name, so get a
2800 reference from there, if need be. (The exception is when the
2801 load failed with a SyntaxError -- then there's no trace in
2802 sys.modules. In that case, of course, do nothing extra.) */
2803 if (submod == NULL) {
2804 submod = PyDict_GetItemString(modules, fullname);
2805 if (submod == NULL)
2806 return 1;
2807 }
2808 if (PyModule_Check(mod)) {
2809 /* We can't use setattr here since it can give a
2810 * spurious warning if the submodule name shadows a
2811 * builtin name */
2812 PyObject *dict = PyModule_GetDict(mod);
2813 if (!dict)
2814 return 0;
2815 if (PyDict_SetItemString(dict, subname, submod) < 0)
2816 return 0;
2817 }
2818 else {
2819 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2820 return 0;
2821 }
2822 return 1;
2823}
2824
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002825static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002826import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002827{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002828 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002829 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002830
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002831 /* Require:
2832 if mod == None: subname == fullname
2833 else: mod.__name__ + "." + subname == fullname
2834 */
2835
Tim Peters50d8d372001-02-28 05:34:27 +00002836 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002837 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002838 }
2839 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002840 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002841 char buf[MAXPATHLEN+1];
2842 struct filedescr *fdp;
2843 FILE *fp = NULL;
2844
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002845 if (mod == Py_None)
2846 path = NULL;
2847 else {
2848 path = PyObject_GetAttrString(mod, "__path__");
2849 if (path == NULL) {
2850 PyErr_Clear();
2851 Py_INCREF(Py_None);
2852 return Py_None;
2853 }
2854 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002855
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002856 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002857 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2858 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002859 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002860 if (fdp == NULL) {
2861 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2862 return NULL;
2863 PyErr_Clear();
2864 Py_INCREF(Py_None);
2865 return Py_None;
2866 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002867 m = load_module(fullname, fp, buf, fdp->type, loader);
2868 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002869 if (fp)
2870 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002871 if (!add_submodule(mod, m, fullname, subname, modules)) {
2872 Py_XDECREF(m);
2873 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002874 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002875 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876
2877 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002878}
2879
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002880
2881/* Re-import a module of any kind and return its module object, WITH
2882 INCREMENTED REFERENCE COUNT */
2883
Guido van Rossum79f25d91997-04-29 20:08:16 +00002884PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002885PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002886{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002887 PyInterpreterState *interp = PyThreadState_Get()->interp;
2888 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002889 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumd8faa362007-04-27 19:54:29 +00002890 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002891 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002892 char buf[MAXPATHLEN+1];
2893 struct filedescr *fdp;
2894 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002895 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002896
Guido van Rossumd8faa362007-04-27 19:54:29 +00002897 if (modules_reloading == NULL) {
2898 Py_FatalError("PyImport_ReloadModule: "
Guido van Rossume7ba4952007-06-06 23:52:48 +00002899 "no modules_reloading dictionary!");
Guido van Rossumd8faa362007-04-27 19:54:29 +00002900 return NULL;
2901 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002902
Guido van Rossum79f25d91997-04-29 20:08:16 +00002903 if (m == NULL || !PyModule_Check(m)) {
2904 PyErr_SetString(PyExc_TypeError,
2905 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002906 return NULL;
2907 }
Neal Norwitz5616c6d2007-08-26 05:32:41 +00002908 name = (char*)PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002909 if (name == NULL)
2910 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002911 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002912 PyErr_Format(PyExc_ImportError,
2913 "reload(): module %.200s not in sys.modules",
2914 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002915 return NULL;
2916 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002917 existing_m = PyDict_GetItemString(modules_reloading, name);
2918 if (existing_m != NULL) {
2919 /* Due to a recursive reload, this module is already
2920 being reloaded. */
2921 Py_INCREF(existing_m);
2922 return existing_m;
2923 }
2924 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2925 return NULL;
2926
Guido van Rossum222ef561997-09-06 19:41:09 +00002927 subname = strrchr(name, '.');
2928 if (subname == NULL)
2929 subname = name;
2930 else {
2931 PyObject *parentname, *parent;
Christian Heimesc4cb3b82007-11-04 12:10:01 +00002932 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002933 if (parentname == NULL) {
2934 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002935 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002936 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002937 parent = PyDict_GetItem(modules, parentname);
2938 if (parent == NULL) {
2939 PyErr_Format(PyExc_ImportError,
Victor Stinner3f1af5c2010-03-12 17:00:41 +00002940 "reload(): parent %U not in sys.modules",
2941 parentname);
Georg Brandl0c55f292005-09-14 06:56:20 +00002942 Py_DECREF(parentname);
Guido van Rossume7ba4952007-06-06 23:52:48 +00002943 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002944 return NULL;
2945 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002946 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002947 subname++;
2948 path = PyObject_GetAttrString(parent, "__path__");
2949 if (path == NULL)
2950 PyErr_Clear();
2951 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002952 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002953 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002954 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002955
2956 if (fdp == NULL) {
2957 Py_XDECREF(loader);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002958 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002959 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002960 }
2961
2962 newm = load_module(name, fp, buf, fdp->type, loader);
2963 Py_XDECREF(loader);
2964
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002965 if (fp)
2966 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002967 if (newm == NULL) {
2968 /* load_module probably removed name from modules because of
2969 * the error. Put back the original module object. We're
2970 * going to return NULL in this case regardless of whether
2971 * replacing name succeeds, so the return value is ignored.
2972 */
2973 PyDict_SetItemString(modules, name, m);
2974 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002975 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002976 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002977}
2978
2979
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002980/* Higher-level import emulator which emulates the "import" statement
2981 more accurately -- it invokes the __import__() function from the
2982 builtins of the current globals. This means that the import is
2983 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002984 environment, e.g. by "rexec".
2985 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002986 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002987 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002988
2989PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002990PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002991{
2992 static PyObject *silly_list = NULL;
2993 static PyObject *builtins_str = NULL;
2994 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002995 PyObject *globals = NULL;
2996 PyObject *import = NULL;
2997 PyObject *builtins = NULL;
2998 PyObject *r = NULL;
2999
3000 /* Initialize constant string objects */
3001 if (silly_list == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00003002 import_str = PyUnicode_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003003 if (import_str == NULL)
3004 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00003005 builtins_str = PyUnicode_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003006 if (builtins_str == NULL)
3007 return NULL;
3008 silly_list = Py_BuildValue("[s]", "__doc__");
3009 if (silly_list == NULL)
3010 return NULL;
3011 }
3012
3013 /* Get the builtins from current globals */
3014 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00003015 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00003016 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003017 builtins = PyObject_GetItem(globals, builtins_str);
3018 if (builtins == NULL)
3019 goto err;
3020 }
3021 else {
3022 /* No globals -- use standard builtins, and fake globals */
Georg Brandl1a3284e2007-12-02 09:40:06 +00003023 builtins = PyImport_ImportModuleLevel("builtins",
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003024 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00003025 if (builtins == NULL)
3026 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003027 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3028 if (globals == NULL)
3029 goto err;
3030 }
3031
3032 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003033 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00003034 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003035 if (import == NULL)
3036 PyErr_SetObject(PyExc_KeyError, import_str);
3037 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003038 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00003039 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003040 if (import == NULL)
3041 goto err;
3042
Christian Heimes072c0f12008-01-03 23:01:04 +00003043 /* Call the __import__ function with the proper argument list
3044 * Always use absolute import here. */
3045 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3046 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003047
3048 err:
3049 Py_XDECREF(globals);
3050 Py_XDECREF(builtins);
3051 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003052
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003053 return r;
3054}
3055
3056
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003057/* Module 'imp' provides Python access to the primitives used for
3058 importing modules.
3059*/
3060
Guido van Rossum79f25d91997-04-29 20:08:16 +00003061static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003062imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003063{
3064 char buf[4];
3065
Barry Warsaw28a691b2010-04-17 00:19:56 +00003066 buf[0] = (char) ((magic >> 0) & 0xff);
3067 buf[1] = (char) ((magic >> 8) & 0xff);
3068 buf[2] = (char) ((magic >> 16) & 0xff);
3069 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003070
Christian Heimes72b710a2008-05-26 13:28:38 +00003071 return PyBytes_FromStringAndSize(buf, 4);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003072};
3073
3074static PyObject *
3075imp_get_magic(PyObject *self, PyObject *noargs)
3076{
3077 return imp_make_magic(pyc_magic);
3078}
3079
3080static PyObject *
3081imp_get_tag(PyObject *self, PyObject *noargs)
3082{
3083 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003084}
3085
Guido van Rossum79f25d91997-04-29 20:08:16 +00003086static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003087imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003088{
Guido van Rossum79f25d91997-04-29 20:08:16 +00003089 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003090 struct filedescr *fdp;
3091
Guido van Rossum79f25d91997-04-29 20:08:16 +00003092 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003093 if (list == NULL)
3094 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003095 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3096 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003097 fdp->suffix, fdp->mode, fdp->type);
3098 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00003099 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003100 return NULL;
3101 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00003102 if (PyList_Append(list, item) < 0) {
3103 Py_DECREF(list);
3104 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003105 return NULL;
3106 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00003107 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003108 }
3109 return list;
3110}
3111
Guido van Rossum79f25d91997-04-29 20:08:16 +00003112static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003113call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003114{
Tim Petersdbd9ba62000-07-09 03:09:57 +00003115 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00003116 PyObject *fob, *ret;
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +00003117 PyObject *pathobj;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003118 struct filedescr *fdp;
3119 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003120 FILE *fp = NULL;
Guido van Rossum40d20bc2007-10-22 00:09:51 +00003121 int fd = -1;
Brett Cannon3bb42d92007-10-20 03:43:15 +00003122 char *found_encoding = NULL;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00003123 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003124
3125 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003126 if (path == Py_None)
3127 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00003128 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003129 if (fdp == NULL)
3130 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003131 if (fp != NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00003132 fd = fileno(fp);
3133 if (fd != -1)
3134 fd = dup(fd);
3135 fclose(fp);
3136 fp = NULL;
3137 }
3138 if (fd != -1) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00003139 if (strchr(fdp->mode, 'b') == NULL) {
Brett Cannon3bb42d92007-10-20 03:43:15 +00003140 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3141 memory. */
Guido van Rossum40d20bc2007-10-22 00:09:51 +00003142 found_encoding = PyTokenizer_FindEncoding(fd);
3143 lseek(fd, 0, 0); /* Reset position */
Amaury Forgeot d'Arc1b933ed2008-09-04 22:34:09 +00003144 if (found_encoding == NULL && PyErr_Occurred())
3145 return NULL;
Brett Cannon3bb42d92007-10-20 03:43:15 +00003146 encoding = (found_encoding != NULL) ? found_encoding :
Guido van Rossumce3a72a2007-10-19 23:16:50 +00003147 (char*)PyUnicode_GetDefaultEncoding();
3148 }
Guido van Rossum40d20bc2007-10-22 00:09:51 +00003149 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
Guido van Rossume7fc50f2007-12-03 22:54:21 +00003150 (char*)encoding, NULL, NULL, 1);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003151 if (fob == NULL) {
Guido van Rossum40d20bc2007-10-22 00:09:51 +00003152 close(fd);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003153 PyMem_FREE(found_encoding);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003154 return NULL;
3155 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003156 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003157 else {
3158 fob = Py_None;
3159 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00003160 }
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +00003161 pathobj = PyUnicode_DecodeFSDefault(pathname);
3162 ret = Py_BuildValue("NN(ssi)",
3163 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003164 PyMem_FREE(found_encoding);
3165
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003166 return ret;
3167}
3168
Guido van Rossum79f25d91997-04-29 20:08:16 +00003169static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003170imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003171{
3172 char *name;
Hirokazu Yamamoto90eaaf62009-01-30 03:15:05 +00003173 PyObject *ret, *path = NULL;
Amaury Forgeot d'Arc9a5499b2008-11-11 23:04:59 +00003174 if (!PyArg_ParseTuple(args, "es|O:find_module",
3175 Py_FileSystemDefaultEncoding, &name,
3176 &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003177 return NULL;
Hirokazu Yamamoto90eaaf62009-01-30 03:15:05 +00003178 ret = call_find_module(name, path);
3179 PyMem_Free(name);
3180 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003181}
3182
3183static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003184imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003185{
3186 char *name;
3187 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003188 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00003189 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003190 return NULL;
3191 ret = init_builtin(name);
3192 if (ret < 0)
3193 return NULL;
3194 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00003195 Py_INCREF(Py_None);
3196 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003197 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00003198 m = PyImport_AddModule(name);
3199 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003200 return m;
3201}
3202
Guido van Rossum79f25d91997-04-29 20:08:16 +00003203static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003204imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003205{
3206 char *name;
3207 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003208 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00003209 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003210 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003211 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003212 if (ret < 0)
3213 return NULL;
3214 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00003215 Py_INCREF(Py_None);
3216 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003217 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00003218 m = PyImport_AddModule(name);
3219 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003220 return m;
3221}
3222
Guido van Rossum79f25d91997-04-29 20:08:16 +00003223static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003224imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003225{
3226 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003227
Guido van Rossum43713e52000-02-29 13:59:29 +00003228 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003229 return NULL;
3230 return get_frozen_object(name);
3231}
3232
Guido van Rossum79f25d91997-04-29 20:08:16 +00003233static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003234imp_is_frozen_package(PyObject *self, PyObject *args)
3235{
3236 char *name;
3237
3238 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3239 return NULL;
3240 return is_frozen_package(name);
3241}
3242
3243static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003244imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003245{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003246 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00003247 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003248 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00003249 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003250}
3251
Guido van Rossum79f25d91997-04-29 20:08:16 +00003252static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003253imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003254{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003255 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00003256 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00003257 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003258 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00003259 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00003260 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003261}
3262
3263static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003264get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003265{
3266 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00003267 if (mode[0] == 'U')
3268 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003269 if (fob == NULL) {
3270 fp = fopen(pathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003271 }
3272 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00003273 int fd = PyObject_AsFileDescriptor(fob);
3274 if (fd == -1)
3275 return NULL;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003276 if (!_PyVerify_fd(fd))
3277 goto error;
3278 /* the FILE struct gets a new fd, so that it can be closed
3279 * independently of the file descriptor given
3280 */
3281 fd = dup(fd);
3282 if (fd == -1)
3283 goto error;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00003284 fp = fdopen(fd, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003285 }
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003286 if (fp)
3287 return fp;
3288error:
3289 PyErr_SetFromErrno(PyExc_IOError);
3290 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003291}
3292
Guido van Rossum79f25d91997-04-29 20:08:16 +00003293static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003294imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003295{
3296 char *name;
3297 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003298 PyObject *fob = NULL;
3299 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003300 FILE *fp;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003301 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003302 &name,
3303 Py_FileSystemDefaultEncoding, &pathname,
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003304 &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003305 return NULL;
3306 fp = get_file(pathname, fob, "rb");
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003307 if (fp == NULL) {
3308 PyMem_Free(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003309 return NULL;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003310 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003311 m = load_compiled_module(name, pathname, fp);
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003312 fclose(fp);
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003313 PyMem_Free(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003314 return m;
3315}
3316
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003317#ifdef HAVE_DYNAMIC_LOADING
3318
Guido van Rossum79f25d91997-04-29 20:08:16 +00003319static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003320imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003321{
3322 char *name;
3323 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003324 PyObject *fob = NULL;
3325 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00003326 FILE *fp = NULL;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003327 if (!PyArg_ParseTuple(args, "ses|O:load_dynamic",
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003328 &name,
3329 Py_FileSystemDefaultEncoding, &pathname,
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003330 &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003331 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003332 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00003333 fp = get_file(pathname, fob, "r");
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003334 if (fp == NULL) {
3335 PyMem_Free(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003336 return NULL;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003337 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003338 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00003339 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003340 PyMem_Free(pathname);
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003341 if (fp)
3342 fclose(fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00003343 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003344}
3345
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003346#endif /* HAVE_DYNAMIC_LOADING */
3347
Guido van Rossum79f25d91997-04-29 20:08:16 +00003348static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003349imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003350{
3351 char *name;
3352 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003353 PyObject *fob = NULL;
3354 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003355 FILE *fp;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003356 if (!PyArg_ParseTuple(args, "ses|O:load_source",
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003357 &name,
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003358 Py_FileSystemDefaultEncoding, &pathname,
3359 &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003360 return NULL;
3361 fp = get_file(pathname, fob, "r");
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003362 if (fp == NULL) {
3363 PyMem_Free(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003364 return NULL;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003365 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003366 m = load_source_module(name, pathname, fp);
Kristján Valur Jónsson92af5d92009-03-31 17:47:50 +00003367 PyMem_Free(pathname);
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003368 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003369 return m;
3370}
3371
Guido van Rossum79f25d91997-04-29 20:08:16 +00003372static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003373imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003374{
3375 char *name;
3376 PyObject *fob;
3377 char *pathname;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003378 PyObject * ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003379 char *suffix; /* Unused */
3380 char *mode;
3381 int type;
3382 FILE *fp;
3383
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003384 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003385 &name, &fob,
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003386 Py_FileSystemDefaultEncoding, &pathname,
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003387 &suffix, &mode, &type))
3388 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003389 if (*mode) {
3390 /* Mode must start with 'r' or 'U' and must not contain '+'.
3391 Implicit in this test is the assumption that the mode
3392 may contain other modifiers like 'b' or 't'. */
3393
3394 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00003395 PyErr_Format(PyExc_ValueError,
3396 "invalid file open mode %.200s", mode);
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003397 PyMem_Free(pathname);
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00003398 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003399 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003400 }
3401 if (fob == Py_None)
3402 fp = NULL;
3403 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00003404 fp = get_file(NULL, fob, mode);
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003405 if (fp == NULL) {
3406 PyMem_Free(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003407 return NULL;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003408 }
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003409 }
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003410 ret = load_module(name, fp, pathname, type, NULL);
3411 PyMem_Free(pathname);
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003412 if (fp)
3413 fclose(fp);
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003414 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003415}
3416
3417static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003418imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003419{
3420 char *name;
3421 char *pathname;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003422 PyObject * ret;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003423 if (!PyArg_ParseTuple(args, "ses:load_package",
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003424 &name, Py_FileSystemDefaultEncoding, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003425 return NULL;
Guido van Rossum0ad59d42009-03-30 22:01:35 +00003426 ret = load_package(name, pathname);
3427 PyMem_Free(pathname);
3428 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003429}
3430
3431static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003432imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003433{
3434 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00003435 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003436 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003437 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003438}
3439
Christian Heimes13a7a212008-01-07 17:13:09 +00003440static PyObject *
3441imp_reload(PyObject *self, PyObject *v)
3442{
3443 return PyImport_ReloadModule(v);
3444}
3445
3446PyDoc_STRVAR(doc_reload,
3447"reload(module) -> module\n\
3448\n\
3449Reload the module. The module must have been successfully imported before.");
3450
Barry Warsaw28a691b2010-04-17 00:19:56 +00003451static PyObject *
3452imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3453{
3454 static char *kwlist[] = {"path", "debug_override", NULL};
3455
3456 char buf[MAXPATHLEN+1];
3457 char *pathname, *cpathname;
3458 PyObject *debug_override = Py_None;
3459 int debug = !Py_OptimizeFlag;
3460
3461 if (!PyArg_ParseTupleAndKeywords(
3462 args, kws, "es|O", kwlist,
3463 Py_FileSystemDefaultEncoding, &pathname, &debug_override))
3464 return NULL;
3465
3466 if (debug_override != Py_None)
3467 if ((debug = PyObject_IsTrue(debug_override)) < 0)
3468 return NULL;
3469
3470 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug);
3471 PyMem_Free(pathname);
3472
3473 if (cpathname == NULL) {
3474 PyErr_Format(PyExc_SystemError, "path buffer too short");
3475 return NULL;
3476 }
3477 return PyUnicode_FromString(buf);
3478}
3479
3480PyDoc_STRVAR(doc_cache_from_source,
3481"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3482\n\
3483The .py file does not need to exist; this simply returns the path to the\n\
3484.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3485will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3486\n\
3487If debug_override is not None, then it must be a boolean and is taken as\n\
3488the value of __debug__ instead.");
3489
3490static PyObject *
3491imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3492{
3493 static char *kwlist[] = {"path", NULL};
3494
3495 char *pathname;
3496 char buf[MAXPATHLEN+1];
3497
3498 if (!PyArg_ParseTupleAndKeywords(
3499 args, kws, "es", kwlist,
3500 Py_FileSystemDefaultEncoding, &pathname))
3501 return NULL;
3502
3503 if (make_source_pathname(pathname, buf) == NULL) {
3504 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3505 pathname);
3506 PyMem_Free(pathname);
3507 return NULL;
3508 }
3509 PyMem_Free(pathname);
3510 return PyUnicode_FromString(buf);
3511}
3512
3513PyDoc_STRVAR(doc_source_from_cache,
3514"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3515\n\
3516The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3517the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3518does not conform to PEP 3147 format, ValueError will be raised.");
3519
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003520/* Doc strings */
3521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003522PyDoc_STRVAR(doc_imp,
3523"This module provides the components needed to build your own\n\
3524__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003526PyDoc_STRVAR(doc_find_module,
3527"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003528Search for a module. If path is omitted or None, search for a\n\
3529built-in, frozen or special module and continue search in sys.path.\n\
3530The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003531package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003533PyDoc_STRVAR(doc_load_module,
3534"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003535Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003536The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003538PyDoc_STRVAR(doc_get_magic,
3539"get_magic() -> string\n\
3540Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003541
Barry Warsaw28a691b2010-04-17 00:19:56 +00003542PyDoc_STRVAR(doc_get_tag,
3543"get_tag() -> string\n\
3544Return the magic tag for .pyc or .pyo files.");
3545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003546PyDoc_STRVAR(doc_get_suffixes,
3547"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003548Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003549that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003551PyDoc_STRVAR(doc_new_module,
3552"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003553Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003554The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003556PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003557"lock_held() -> boolean\n\
3558Return True if the import lock is currently held, else False.\n\
3559On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003560
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003561PyDoc_STRVAR(doc_acquire_lock,
3562"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003563Acquires the interpreter's import lock for the current thread.\n\
3564This lock should be used by import hooks to ensure thread-safety\n\
3565when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003566On platforms without threads, this function does nothing.");
3567
3568PyDoc_STRVAR(doc_release_lock,
3569"release_lock() -> None\n\
3570Release the interpreter's import lock.\n\
3571On platforms without threads, this function does nothing.");
3572
Guido van Rossum79f25d91997-04-29 20:08:16 +00003573static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003574 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3575 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
Barry Warsaw28a691b2010-04-17 00:19:56 +00003576 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003577 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3578 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3579 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3580 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3581 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3582 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Christian Heimes13a7a212008-01-07 17:13:09 +00003583 {"reload", imp_reload, METH_O, doc_reload},
Barry Warsaw28a691b2010-04-17 00:19:56 +00003584 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3585 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3586 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3587 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003588 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003589 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
Brett Cannon8d110132009-03-15 02:20:16 +00003590 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003591 {"init_builtin", imp_init_builtin, METH_VARARGS},
3592 {"init_frozen", imp_init_frozen, METH_VARARGS},
3593 {"is_builtin", imp_is_builtin, METH_VARARGS},
3594 {"is_frozen", imp_is_frozen, METH_VARARGS},
3595 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003596#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003597 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003598#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003599 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003600 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003601 {NULL, NULL} /* sentinel */
3602};
3603
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003604static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003605setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003606{
3607 PyObject *v;
3608 int err;
3609
Christian Heimes217cfd12007-12-02 14:31:20 +00003610 v = PyLong_FromLong((long)value);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003611 err = PyDict_SetItemString(d, name, v);
3612 Py_XDECREF(v);
3613 return err;
3614}
3615
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003616typedef struct {
3617 PyObject_HEAD
3618} NullImporter;
3619
3620static int
3621NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3622{
3623 char *path;
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003624 Py_ssize_t pathlen;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003625
3626 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3627 return -1;
3628
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00003629 if (!PyArg_ParseTuple(args, "es:NullImporter",
3630 Py_FileSystemDefaultEncoding, &path))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003631 return -1;
3632
Christian Heimes7d3bc0a2007-11-07 17:26:16 +00003633 pathlen = strlen(path);
3634 if (pathlen == 0) {
Georg Brandl8494d572008-07-19 10:13:15 +00003635 PyMem_Free(path);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003636 PyErr_SetString(PyExc_ImportError, "empty pathname");
3637 return -1;
3638 } else {
Hirokazu Yamamoto21cbf5f2009-01-23 07:23:03 +00003639#ifndef MS_WINDOWS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003640 struct stat statbuf;
3641 int rv;
3642
3643 rv = stat(path, &statbuf);
Georg Brandl8494d572008-07-19 10:13:15 +00003644 PyMem_Free(path);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003645 if (rv == 0) {
3646 /* it exists */
3647 if (S_ISDIR(statbuf.st_mode)) {
3648 /* it's a directory */
3649 PyErr_SetString(PyExc_ImportError,
3650 "existing directory");
3651 return -1;
3652 }
3653 }
Hirokazu Yamamoto21cbf5f2009-01-23 07:23:03 +00003654#else /* MS_WINDOWS */
3655 DWORD rv;
3656 /* see issue1293 and issue3677:
3657 * stat() on Windows doesn't recognise paths like
3658 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3659 */
3660 rv = GetFileAttributesA(path);
Kristján Valur Jónsson92cb4382009-01-24 10:33:25 +00003661 PyMem_Free(path);
Hirokazu Yamamoto21cbf5f2009-01-23 07:23:03 +00003662 if (rv != INVALID_FILE_ATTRIBUTES) {
3663 /* it exists */
3664 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3665 /* it's a directory */
3666 PyErr_SetString(PyExc_ImportError,
3667 "existing directory");
3668 return -1;
3669 }
3670 }
3671#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003672 }
3673 return 0;
3674}
3675
3676static PyObject *
3677NullImporter_find_module(NullImporter *self, PyObject *args)
3678{
3679 Py_RETURN_NONE;
3680}
3681
3682static PyMethodDef NullImporter_methods[] = {
3683 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3684 "Always return None"
3685 },
3686 {NULL} /* Sentinel */
3687};
3688
3689
Christian Heimes9cd17752007-11-18 19:35:23 +00003690PyTypeObject PyNullImporter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003691 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003692 "imp.NullImporter", /*tp_name*/
3693 sizeof(NullImporter), /*tp_basicsize*/
3694 0, /*tp_itemsize*/
3695 0, /*tp_dealloc*/
3696 0, /*tp_print*/
3697 0, /*tp_getattr*/
3698 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00003699 0, /*tp_reserved*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003700 0, /*tp_repr*/
3701 0, /*tp_as_number*/
3702 0, /*tp_as_sequence*/
3703 0, /*tp_as_mapping*/
3704 0, /*tp_hash */
3705 0, /*tp_call*/
3706 0, /*tp_str*/
3707 0, /*tp_getattro*/
3708 0, /*tp_setattro*/
3709 0, /*tp_as_buffer*/
3710 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3711 "Null importer object", /* tp_doc */
3712 0, /* tp_traverse */
3713 0, /* tp_clear */
3714 0, /* tp_richcompare */
3715 0, /* tp_weaklistoffset */
3716 0, /* tp_iter */
3717 0, /* tp_iternext */
3718 NullImporter_methods, /* tp_methods */
3719 0, /* tp_members */
3720 0, /* tp_getset */
3721 0, /* tp_base */
3722 0, /* tp_dict */
3723 0, /* tp_descr_get */
3724 0, /* tp_descr_set */
3725 0, /* tp_dictoffset */
3726 (initproc)NullImporter_init, /* tp_init */
3727 0, /* tp_alloc */
3728 PyType_GenericNew /* tp_new */
3729};
3730
Martin v. Löwis1a214512008-06-11 05:26:20 +00003731static struct PyModuleDef impmodule = {
3732 PyModuleDef_HEAD_INIT,
3733 "imp",
3734 doc_imp,
3735 0,
3736 imp_methods,
3737 NULL,
3738 NULL,
3739 NULL,
3740 NULL
3741};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003742
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003743PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003744PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003745{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003746 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003747
Christian Heimes9cd17752007-11-18 19:35:23 +00003748 if (PyType_Ready(&PyNullImporter_Type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00003749 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003750
Martin v. Löwis1a214512008-06-11 05:26:20 +00003751 m = PyModule_Create(&impmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003752 if (m == NULL)
3753 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003754 d = PyModule_GetDict(m);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003755 if (d == NULL)
3756 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003757
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003758 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3759 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3760 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3761 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3762 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3763 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3764 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3765 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003766 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003767 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003768
Christian Heimes9cd17752007-11-18 19:35:23 +00003769 Py_INCREF(&PyNullImporter_Type);
3770 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Martin v. Löwis1a214512008-06-11 05:26:20 +00003771 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003772 failure:
Martin v. Löwis1a214512008-06-11 05:26:20 +00003773 Py_XDECREF(m);
3774 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003775}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003776
3777
Guido van Rossumb18618d2000-05-03 23:44:39 +00003778/* API for embedding applications that want to add their own entries
3779 to the table of built-in modules. This should normally be called
3780 *before* Py_Initialize(). When the table resize fails, -1 is
3781 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003782
3783 After a similar function by Just van Rossum. */
3784
3785int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003786PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003787{
3788 static struct _inittab *our_copy = NULL;
3789 struct _inittab *p;
3790 int i, n;
3791
3792 /* Count the number of entries in both tables */
3793 for (n = 0; newtab[n].name != NULL; n++)
3794 ;
3795 if (n == 0)
3796 return 0; /* Nothing to do */
3797 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3798 ;
3799
3800 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003801 p = our_copy;
3802 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003803 if (p == NULL)
3804 return -1;
3805
3806 /* Copy the tables into the new memory */
3807 if (our_copy != PyImport_Inittab)
3808 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3809 PyImport_Inittab = our_copy = p;
3810 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3811
3812 return 0;
3813}
3814
3815/* Shorthand to add a single entry given a name and a function */
3816
3817int
Brett Cannona826f322009-04-02 03:41:46 +00003818PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003819{
3820 struct _inittab newtab[2];
3821
3822 memset(newtab, '\0', sizeof newtab);
3823
Brett Cannona826f322009-04-02 03:41:46 +00003824 newtab[0].name = (char *)name;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003825 newtab[0].initfunc = initfunc;
3826
3827 return PyImport_ExtendInittab(newtab);
3828}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003829
3830#ifdef __cplusplus
3831}
3832#endif