blob: d5b89d59668f562d17d39ce41a4e026f3f965041 [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 */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000011#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000012#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013
Guido van Rossum55a83382000-09-20 20:31:38 +000014#ifdef HAVE_FCNTL_H
15#include <fcntl.h>
16#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000018extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000020
Christian Heimesd3eb5a152008-02-24 00:38:49 +000021#ifdef MS_WINDOWS
22/* for stat.st_mode */
23typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000024/* for _mkdir */
25#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000026#endif
27
Guido van Rossum21d335e1993-10-15 13:01:11 +000028
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000029/* Magic word to reject .pyc files generated by other Python versions.
30 It should change for each incompatible change to the bytecode.
31
32 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000033 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000034 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000035
Guido van Rossum45aecf42006-03-15 04:58:47 +000036 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000037 -U interpeter flag will cause MAGIC+1 being used. They have been
38 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000040 There were a variety of old schemes for setting the magic number.
41 The current working scheme is to increment the previous value by
42 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000043
Barry Warsaw28a691b2010-04-17 00:19:56 +000044 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
45 number also includes a new "magic tag", i.e. a human readable string used
46 to represent the magic number in __pycache__ directories. When you change
47 the magic number, you must also set a new unique magic tag. Generally this
48 can be named after the Python major version of the magic number bump, but
49 it can really be anything, as long as it's different than anything else
50 that's come before. The tags are included in the following table, starting
51 with Python 3.2a0.
52
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Known values:
54 Python 1.5: 20121
55 Python 1.5.1: 20121
56 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000058 Python 2.0: 50823
59 Python 2.0.1: 50823
60 Python 2.1: 60202
61 Python 2.1.1: 60202
62 Python 2.1.2: 60202
63 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000064 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000065 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000066 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000067 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000068 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000069 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000070 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000071 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000072 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000073 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
75 Python 2.5b3: 62111 (fix wrong code: x += yield)
76 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000078 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000079 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000081 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 3010 (removed UNARY_CONVERT)
83 3020 (added BUILD_SET)
84 3030 (added keyword-only parameters)
85 3040 (added signature annotations)
86 3050 (print becomes a function)
87 3060 (PEP 3115 metaclass syntax)
88 3061 (string literals become unicode)
89 3071 (PEP 3109 raise changes)
90 3081 (PEP 3137 make __file__ and __name__ unicode)
91 3091 (kill str8 interning)
92 3101 (merge from 2.6a0, see 62151)
93 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000094 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
95 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
96 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000100 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000102 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
103 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000104 Python 3.2a2 3180 (add DELETE_DEREF)
Benjamin Petersone7c15fa2011-06-19 19:54:45 -0500105 Python 3.3a0 3190 __class__ super closure changed
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 Python 3.3a0 3200 (__qualname__ added)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100107 3210 (added size modulo 2**32 to the pyc header)
Tim Peters36515e22001-11-18 04:06:29 +0000108*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000109
Nick Coghlancd419ab2010-09-11 00:39:25 +0000110/* MAGIC must change whenever the bytecode emitted by the compiler may no
111 longer be understood by older implementations of the eval loop (usually
112 due to the addition of new opcodes)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200113 TAG must change for each major Python release. The magic number will take
114 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000115*/
Benjamin Peterson48deae12011-06-03 17:50:16 -0500116#define QUOTE(arg) #arg
117#define STRIFY(name) QUOTE(name)
118#define MAJOR STRIFY(PY_MAJOR_VERSION)
119#define MINOR STRIFY(PY_MINOR_VERSION)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100120#define MAGIC (3210 | ((long)'\r'<<16) | ((long)'\n'<<24))
Benjamin Peterson48deae12011-06-03 17:50:16 -0500121#define TAG "cpython-" MAJOR MINOR;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122#define CACHEDIR "__pycache__"
123/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000124static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000125static const char *pyc_tag = TAG;
Benjamin Peterson48deae12011-06-03 17:50:16 -0500126#undef QUOTE
127#undef STRIFY
128#undef MAJOR
129#undef MINOR
Guido van Rossum96774c12000-05-01 20:19:08 +0000130
Victor Stinner95872862011-03-07 18:20:56 +0100131/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000133
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200134/* Function from Parser/tokenizer.c */
135extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
136
Guido van Rossum771c6c81997-10-31 18:37:24 +0000137/* This table is defined in config.c: */
138extern struct _inittab _PyImport_Inittab[];
139
140struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000141
Guido van Rossumed1170e1999-12-20 21:23:41 +0000142/* these tables define the module suffixes that Python recognizes */
143struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000144
Guido van Rossumed1170e1999-12-20 21:23:41 +0000145static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000147#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000149#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 {".pyc", "rb", PY_COMPILED},
151 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000152};
153
Victor Stinnerd0296212011-03-14 14:04:10 -0400154static PyObject *initstr = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200155_Py_IDENTIFIER(__path__);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000157/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158
159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 const struct filedescr *scan;
163 struct filedescr *filetab;
164 int countD = 0;
165 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000166
Victor Stinnerd0296212011-03-14 14:04:10 -0400167 initstr = PyUnicode_InternFromString("__init__");
168 if (initstr == NULL)
169 Py_FatalError("Can't initialize import variables");
170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* prepare _PyImport_Filetab: copy entries from
172 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
173 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000174#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
176 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
179 ++countS;
180 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
181 if (filetab == NULL)
182 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000183#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 memcpy(filetab, _PyImport_DynLoadFiletab,
185 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000186#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 memcpy(filetab + countD, _PyImport_StandardFiletab,
188 countS * sizeof(struct filedescr));
189 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (Py_OptimizeFlag) {
194 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
195 for (; filetab->suffix != NULL; filetab++) {
196 if (strcmp(filetab->suffix, ".pyc") == 0)
197 filetab->suffix = ".pyo";
198 }
199 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202void
Just van Rossum52e14d62002-12-30 22:08:05 +0000203_PyImportHooks_Init(void)
204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyObject *v, *path_hooks = NULL, *zimpimport;
206 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* adding sys.path_hooks and sys.path_importer_cache, setting up
209 zipimport */
210 if (PyType_Ready(&PyNullImporter_Type) < 0)
211 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (Py_VerboseFlag)
214 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 v = PyList_New(0);
217 if (v == NULL)
218 goto error;
219 err = PySys_SetObject("meta_path", v);
220 Py_DECREF(v);
221 if (err)
222 goto error;
223 v = PyDict_New();
224 if (v == NULL)
225 goto error;
226 err = PySys_SetObject("path_importer_cache", v);
227 Py_DECREF(v);
228 if (err)
229 goto error;
230 path_hooks = PyList_New(0);
231 if (path_hooks == NULL)
232 goto error;
233 err = PySys_SetObject("path_hooks", path_hooks);
234 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000235 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyErr_Print();
237 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
238 "path_importer_cache, or NullImporter failed"
239 );
240 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 zimpimport = PyImport_ImportModule("zipimport");
243 if (zimpimport == NULL) {
244 PyErr_Clear(); /* No zip import module -- okay */
245 if (Py_VerboseFlag)
246 PySys_WriteStderr("# can't import zipimport\n");
247 }
248 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200249 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200250 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
251 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_DECREF(zimpimport);
253 if (zipimporter == NULL) {
254 PyErr_Clear(); /* No zipimporter object -- okay */
255 if (Py_VerboseFlag)
256 PySys_WriteStderr(
257 "# can't import zipimport.zipimporter\n");
258 }
259 else {
260 /* sys.path_hooks.append(zipimporter) */
261 err = PyList_Append(path_hooks, zipimporter);
262 Py_DECREF(zipimporter);
263 if (err)
264 goto error;
265 if (Py_VerboseFlag)
266 PySys_WriteStderr(
267 "# installed zipimport hook\n");
268 }
269 }
270 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000271}
272
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000273/* Locking primitives to prevent parallel imports of the same module
274 in different threads to return with a partially loaded module.
275 These calls are serialized by the global interpreter lock. */
276
277#ifdef WITH_THREAD
278
Guido van Rossum49b56061998-10-01 20:42:43 +0000279#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280
Guido van Rossum65d5b571998-12-21 19:32:43 +0000281static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000282static long import_lock_thread = -1;
283static int import_lock_level = 0;
284
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000285void
286_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 long me = PyThread_get_thread_ident();
289 if (me == -1)
290 return; /* Too bad */
291 if (import_lock == NULL) {
292 import_lock = PyThread_allocate_lock();
293 if (import_lock == NULL)
294 return; /* Nothing much we can do. */
295 }
296 if (import_lock_thread == me) {
297 import_lock_level++;
298 return;
299 }
300 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
301 {
302 PyThreadState *tstate = PyEval_SaveThread();
303 PyThread_acquire_lock(import_lock, 1);
304 PyEval_RestoreThread(tstate);
305 }
306 import_lock_thread = me;
307 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000308}
309
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000310int
311_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 long me = PyThread_get_thread_ident();
314 if (me == -1 || import_lock == NULL)
315 return 0; /* Too bad */
316 if (import_lock_thread != me)
317 return -1;
318 import_lock_level--;
319 if (import_lock_level == 0) {
320 import_lock_thread = -1;
321 PyThread_release_lock(import_lock);
322 }
323 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000324}
325
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000326/* This function is called from PyOS_AfterFork to ensure that newly
327 created child processes do not share locks with the parent.
328 We now acquire the import lock around fork() calls but on some platforms
329 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000330
331void
332_PyImport_ReInitLock(void)
333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (import_lock != NULL)
335 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000336 if (import_lock_level > 1) {
337 /* Forked as a side effect of import */
338 long me = PyThread_get_thread_ident();
339 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100340 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000341 import_lock_thread = me;
342 import_lock_level--;
343 } else {
344 import_lock_thread = -1;
345 import_lock_level = 0;
346 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000347}
348
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000349#endif
350
Tim Peters69232342001-08-30 05:16:13 +0000351static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000352imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000353{
Tim Peters69232342001-08-30 05:16:13 +0000354#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000356#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000358#endif
359}
360
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000362imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000363{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000364#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000366#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 Py_INCREF(Py_None);
368 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000369}
370
371static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000372imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000373{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000374#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (_PyImport_ReleaseLock() < 0) {
376 PyErr_SetString(PyExc_RuntimeError,
377 "not holding the import lock");
378 return NULL;
379 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000380#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 Py_INCREF(Py_None);
382 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000383}
384
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100385void
386_PyImport_Fini(void)
387{
388 Py_XDECREF(extensions);
389 extensions = NULL;
390 PyMem_DEL(_PyImport_Filetab);
391 _PyImport_Filetab = NULL;
392#ifdef WITH_THREAD
393 if (import_lock != NULL) {
394 PyThread_free_lock(import_lock);
395 import_lock = NULL;
396 }
397#endif
398}
399
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400static void
401imp_modules_reloading_clear(void)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyInterpreterState *interp = PyThreadState_Get()->interp;
404 if (interp->modules_reloading != NULL)
405 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406}
407
Guido van Rossum25ce5661997-08-02 03:10:38 +0000408/* Helper for sys */
409
410PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000411PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 PyInterpreterState *interp = PyThreadState_GET()->interp;
414 if (interp->modules == NULL)
415 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
416 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000417}
418
Guido van Rossum3f5da241990-12-20 15:06:42 +0000419
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000420/* List of names to clear in sys */
421static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 "path", "argv", "ps1", "ps2",
423 "last_type", "last_value", "last_traceback",
424 "path_hooks", "path_importer_cache", "meta_path",
425 /* misc stuff */
426 "flags", "float_info",
427 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000428};
429
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 "stdin", "__stdin__",
432 "stdout", "__stdout__",
433 "stderr", "__stderr__",
434 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435};
436
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000438/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000439
Guido van Rossum3f5da241990-12-20 15:06:42 +0000440void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000441PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *key, *value, *dict;
445 PyInterpreterState *interp = PyThreadState_GET()->interp;
446 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (modules == NULL)
449 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* Delete some special variables first. These are common
452 places where user values hide and people complain when their
453 destructors fail. Since the modules containing them are
454 deleted *last* of all, they would come too late in the normal
455 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 value = PyDict_GetItemString(modules, "builtins");
458 if (value != NULL && PyModule_Check(value)) {
459 dict = PyModule_GetDict(value);
460 if (Py_VerboseFlag)
461 PySys_WriteStderr("# clear builtins._\n");
462 PyDict_SetItemString(dict, "_", Py_None);
463 }
464 value = PyDict_GetItemString(modules, "sys");
465 if (value != NULL && PyModule_Check(value)) {
466 char **p;
467 PyObject *v;
468 dict = PyModule_GetDict(value);
469 for (p = sys_deletes; *p != NULL; p++) {
470 if (Py_VerboseFlag)
471 PySys_WriteStderr("# clear sys.%s\n", *p);
472 PyDict_SetItemString(dict, *p, Py_None);
473 }
474 for (p = sys_files; *p != NULL; p+=2) {
475 if (Py_VerboseFlag)
476 PySys_WriteStderr("# restore sys.%s\n", *p);
477 v = PyDict_GetItemString(dict, *(p+1));
478 if (v == NULL)
479 v = Py_None;
480 PyDict_SetItemString(dict, *p, v);
481 }
482 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* First, delete __main__ */
485 value = PyDict_GetItemString(modules, "__main__");
486 if (value != NULL && PyModule_Check(value)) {
487 if (Py_VerboseFlag)
488 PySys_WriteStderr("# cleanup __main__\n");
489 _PyModule_Clear(value);
490 PyDict_SetItemString(modules, "__main__", Py_None);
491 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* The special treatment of "builtins" here is because even
494 when it's not referenced as a module, its dictionary is
495 referenced by almost every module's __builtins__. Since
496 deleting a module clears its dictionary (even if there are
497 references left to it), we need to delete the "builtins"
498 module last. Likewise, we don't delete sys until the very
499 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 Also note that we 'delete' modules by replacing their entry
502 in the modules dict with None, rather than really deleting
503 them; this avoids a rehash of the modules dictionary and
504 also marks them as "non existent" so they won't be
505 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Next, repeatedly delete modules with a reference count of
508 one (skipping builtins and sys) and delete them */
509 do {
510 ndone = 0;
511 pos = 0;
512 while (PyDict_Next(modules, &pos, &key, &value)) {
513 if (value->ob_refcnt != 1)
514 continue;
515 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100516 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100518 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 continue;
520 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100521 PySys_FormatStderr(
522 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 _PyModule_Clear(value);
524 PyDict_SetItem(modules, key, Py_None);
525 ndone++;
526 }
527 }
528 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* Next, delete all modules (still skipping builtins and sys) */
531 pos = 0;
532 while (PyDict_Next(modules, &pos, &key, &value)) {
533 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100534 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100536 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 continue;
538 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100539 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 _PyModule_Clear(value);
541 PyDict_SetItem(modules, key, Py_None);
542 }
543 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* Next, delete sys and builtins (in that order) */
546 value = PyDict_GetItemString(modules, "sys");
547 if (value != NULL && PyModule_Check(value)) {
548 if (Py_VerboseFlag)
549 PySys_WriteStderr("# cleanup sys\n");
550 _PyModule_Clear(value);
551 PyDict_SetItemString(modules, "sys", Py_None);
552 }
553 value = PyDict_GetItemString(modules, "builtins");
554 if (value != NULL && PyModule_Check(value)) {
555 if (Py_VerboseFlag)
556 PySys_WriteStderr("# cleanup builtins\n");
557 _PyModule_Clear(value);
558 PyDict_SetItemString(modules, "builtins", Py_None);
559 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* Finally, clear and delete the modules directory */
562 PyDict_Clear(modules);
563 interp->modules = NULL;
564 Py_DECREF(modules);
565 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000566}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000567
568
Barry Warsaw28a691b2010-04-17 00:19:56 +0000569/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570
571long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000575}
576
577
Barry Warsaw28a691b2010-04-17 00:19:56 +0000578const char *
579PyImport_GetMagicTag(void)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000582}
583
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584/* Magic for extension modules (built-in as well as dynamically
585 loaded). To prevent initializing an extension module more than
586 once, we keep a static dictionary 'extensions' keyed by module name
587 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000588 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100589 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 immediately after the module initialization function succeeds. A
591 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100592 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000593
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000594 Modules which do support multiple initialization set their m_size
595 field to a non-negative number (indicating the size of the
596 module-specific state). They are still recorded in the extensions
597 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000598*/
599
600int
Victor Stinner95872862011-03-07 18:20:56 +0100601_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
602 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyObject *modules, *dict;
605 struct PyModuleDef *def;
606 if (extensions == NULL) {
607 extensions = PyDict_New();
608 if (extensions == NULL)
609 return -1;
610 }
611 if (mod == NULL || !PyModule_Check(mod)) {
612 PyErr_BadInternalCall();
613 return -1;
614 }
615 def = PyModule_GetDef(mod);
616 if (!def) {
617 PyErr_BadInternalCall();
618 return -1;
619 }
620 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100621 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return -1;
623 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100624 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return -1;
626 }
627 if (def->m_size == -1) {
628 if (def->m_base.m_copy) {
629 /* Somebody already imported the module,
630 likely under a different name.
631 XXX this should really not happen. */
632 Py_DECREF(def->m_base.m_copy);
633 def->m_base.m_copy = NULL;
634 }
635 dict = PyModule_GetDict(mod);
636 if (dict == NULL)
637 return -1;
638 def->m_base.m_copy = PyDict_Copy(dict);
639 if (def->m_base.m_copy == NULL)
640 return -1;
641 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000642 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644}
645
Victor Stinner49d3f252010-10-17 01:24:53 +0000646int
647_PyImport_FixupBuiltin(PyObject *mod, char *name)
648{
649 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100650 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100651 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100652 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000653 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100654 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
655 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000656 return res;
657}
658
Guido van Rossum25ce5661997-08-02 03:10:38 +0000659PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100660_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *mod, *mdict;
663 PyModuleDef* def;
664 if (extensions == NULL)
665 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000666 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (def == NULL)
668 return NULL;
669 if (def->m_size == -1) {
670 /* Module does not support repeated initialization */
671 if (def->m_base.m_copy == NULL)
672 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100673 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (mod == NULL)
675 return NULL;
676 mdict = PyModule_GetDict(mod);
677 if (mdict == NULL)
678 return NULL;
679 if (PyDict_Update(mdict, def->m_base.m_copy))
680 return NULL;
681 }
682 else {
683 if (def->m_base.m_init == NULL)
684 return NULL;
685 mod = def->m_base.m_init();
686 if (mod == NULL)
687 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100688 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_DECREF(mod);
690 }
691 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100692 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_DECREF(mod);
694 return NULL;
695 }
696 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100697 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 name, filename);
699 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000700
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000701}
702
Victor Stinner49d3f252010-10-17 01:24:53 +0000703PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000704_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000705{
Victor Stinner95872862011-03-07 18:20:56 +0100706 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100707 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100708 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000709 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100710 res = _PyImport_FindExtensionObject(nameobj, nameobj);
711 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000712 return res;
713}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
715/* Get the module object corresponding to a module name.
716 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000717 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000718 Because the former action is most common, THIS DOES NOT RETURN A
719 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000720
Guido van Rossum79f25d91997-04-29 20:08:16 +0000721PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000722PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyObject *modules = PyImport_GetModuleDict();
725 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000726
Victor Stinner27ee0892011-03-04 12:57:09 +0000727 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyModule_Check(m))
729 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000730 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (m == NULL)
732 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000733 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 Py_DECREF(m);
735 return NULL;
736 }
737 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740}
741
Victor Stinner27ee0892011-03-04 12:57:09 +0000742PyObject *
743PyImport_AddModule(const char *name)
744{
745 PyObject *nameobj, *module;
746 nameobj = PyUnicode_FromString(name);
747 if (nameobj == NULL)
748 return NULL;
749 module = PyImport_AddModuleObject(nameobj);
750 Py_DECREF(nameobj);
751 return module;
752}
753
754
Tim Peters1cd70172004-08-02 03:52:12 +0000755/* Remove name from sys.modules, if it's there. */
756static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000757remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000760 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000762 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 Py_FatalError("import: deleting existing key in"
764 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000765}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000766
Victor Stinnerc9abda02011-03-14 13:33:46 -0400767static PyObject * get_sourcefile(PyObject *filename);
768static PyObject *make_source_pathname(PyObject *pathname);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200769static PyObject* make_compiled_pathname(PyObject *pathname, int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000770
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000771/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000772 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
773 * removed from sys.modules, to avoid leaving damaged module objects
774 * in sys.modules. The caller may wish to restore the original
775 * module object (if any) in this case; PyImport_ReloadModule is an
776 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000777 *
778 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
779 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000780 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000781PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000782PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 return PyImport_ExecCodeModuleWithPathnames(
785 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000786}
787
788PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000789PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return PyImport_ExecCodeModuleWithPathnames(
792 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000793}
794
795PyObject *
796PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000798{
Victor Stinner27ee0892011-03-04 12:57:09 +0000799 PyObject *m = NULL;
800 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
801
802 nameobj = PyUnicode_FromString(name);
803 if (nameobj == NULL)
804 return NULL;
805
806 if (pathname != NULL) {
807 pathobj = PyUnicode_DecodeFSDefault(pathname);
808 if (pathobj == NULL)
809 goto error;
810 } else
811 pathobj = NULL;
812 if (cpathname != NULL) {
813 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
814 if (cpathobj == NULL)
815 goto error;
816 } else
817 cpathobj = NULL;
818 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
819error:
820 Py_DECREF(nameobj);
821 Py_XDECREF(pathobj);
822 Py_XDECREF(cpathobj);
823 return m;
824}
825
826PyObject*
827PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
828 PyObject *cpathname)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *modules = PyImport_GetModuleDict();
831 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000832
Victor Stinner27ee0892011-03-04 12:57:09 +0000833 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (m == NULL)
835 return NULL;
836 /* If the module is being reloaded, we get the old module back
837 and re-use its dict to exec the new code. */
838 d = PyModule_GetDict(m);
839 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
840 if (PyDict_SetItemString(d, "__builtins__",
841 PyEval_GetBuiltins()) != 0)
842 goto error;
843 }
844 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400846 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (v == NULL)
848 PyErr_Clear();
849 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000850 else
851 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (v == NULL) {
853 v = ((PyCodeObject *)co)->co_filename;
854 Py_INCREF(v);
855 }
856 if (PyDict_SetItemString(d, "__file__", v) != 0)
857 PyErr_Clear(); /* Not important enough to report */
858 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000861 if (cpathname != NULL)
862 v = cpathname;
863 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (PyDict_SetItemString(d, "__cached__", v) != 0)
866 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000867
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000868 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (v == NULL)
870 goto error;
871 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000872
Victor Stinner27ee0892011-03-04 12:57:09 +0000873 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000875 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 name);
877 return NULL;
878 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000883
884 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 remove_module(name);
886 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887}
888
889
Barry Warsaw28a691b2010-04-17 00:19:56 +0000890/* Like strrchr(string, '/') but searches for the rightmost of either SEP
891 or ALTSEP, if the latter is defined.
892*/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200893static Py_UCS4*
894rightmost_sep(Py_UCS4 *s)
Victor Stinnerc9abda02011-03-14 13:33:46 -0400895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 Py_UCS4 *found, c;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400897 for (found = NULL; (c = *s); s++) {
898 if (c == SEP
899#ifdef ALTSEP
900 || c == ALTSEP
901#endif
902 )
903 {
904 found = s;
905 }
906 }
907 return found;
908}
909
Martin v. Löwis2db72862011-10-23 17:29:08 +0200910/* Like rightmost_sep, but operate on unicode objects. */
911static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200912rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200913{
914 Py_ssize_t found, i;
915 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200916 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200917 c = PyUnicode_READ_CHAR(o, i);
918 if (c == SEP
919#ifdef ALTSEP
920 || c == ALTSEP
921#endif
922 )
923 {
924 found = i;
925 }
926 }
927 return found;
928}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400929
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000930/* Given a pathname for a Python source file, fill a buffer with the
931 pathname for the corresponding compiled file. Return the pathname
932 for the compiled file, or NULL if there's no space in the buffer.
Victor Stinner2f42ae52011-03-20 00:41:24 +0100933 Doesn't set an exception.
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000934
Martin v. Löwis30260a72011-10-23 17:35:46 +0200935 foo.py -> __pycache__/foo.<tag>.pyc
936
937 pathstr is assumed to be "ready".
938*/
Victor Stinner2f42ae52011-03-20 00:41:24 +0100939
940static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200941make_compiled_pathname(PyObject *pathstr, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000942{
Martin v. Löwis2db72862011-10-23 17:29:08 +0200943 PyObject *result;
944 Py_ssize_t fname, ext, len, i, pos, taglen;
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200945 Py_ssize_t pycache_len = sizeof(CACHEDIR) - 1;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200946 int kind;
947 void *data;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200948 Py_UCS4 lastsep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000949
Martin v. Löwis2db72862011-10-23 17:29:08 +0200950 /* Compute the output string size. */
951 len = PyUnicode_GET_LENGTH(pathstr);
952 /* If there is no separator, this returns -1, so
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200953 fname will be 0. */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200954 fname = rightmost_sep_obj(pathstr, 0, len) + 1;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200955 /* Windows: re-use the last separator character (/ or \\) when
956 appending the __pycache__ path. */
957 if (fname > 0)
958 lastsep = PyUnicode_READ_CHAR(pathstr, fname -1);
959 else
960 lastsep = SEP;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200961 ext = fname - 1;
962 for(i = fname; i < len; i++)
963 if (PyUnicode_READ_CHAR(pathstr, i) == '.')
964 ext = i + 1;
965 if (ext < fname)
966 /* No dot in filename; use entire filename */
967 ext = len;
968
969 /* result = pathstr[:fname] + "__pycache__" + SEP +
970 pathstr[fname:ext] + tag + ".py[co]" */
971 taglen = strlen(pyc_tag);
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200972 result = PyUnicode_New(ext + pycache_len + 1 + taglen + 4,
Martin v. Löwis2db72862011-10-23 17:29:08 +0200973 PyUnicode_MAX_CHAR_VALUE(pathstr));
974 if (!result)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 return NULL;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200976 kind = PyUnicode_KIND(result);
977 data = PyUnicode_DATA(result);
978 PyUnicode_CopyCharacters(result, 0, pathstr, 0, fname);
979 pos = fname;
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200980 for (i = 0; i < pycache_len; i++)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200981 PyUnicode_WRITE(kind, data, pos++, CACHEDIR[i]);
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200982 PyUnicode_WRITE(kind, data, pos++, lastsep);
Martin v. Löwis2db72862011-10-23 17:29:08 +0200983 PyUnicode_CopyCharacters(result, pos, pathstr,
984 fname, ext - fname);
985 pos += ext - fname;
986 for (i = 0; pyc_tag[i]; i++)
987 PyUnicode_WRITE(kind, data, pos++, pyc_tag[i]);
988 PyUnicode_WRITE(kind, data, pos++, '.');
989 PyUnicode_WRITE(kind, data, pos++, 'p');
990 PyUnicode_WRITE(kind, data, pos++, 'y');
991 PyUnicode_WRITE(kind, data, pos++, debug ? 'c' : 'o');
992 return result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000993}
994
995
Barry Warsaw28a691b2010-04-17 00:19:56 +0000996/* Given a pathname to a Python byte compiled file, return the path to the
997 source file, if the path matches the PEP 3147 format. This does not check
998 for any file existence, however, if the pyc file name does not match PEP
999 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001000 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001
Victor Stinnerc9abda02011-03-14 13:33:46 -04001002 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
1003
1004static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001005make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +00001006{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001007 Py_ssize_t left, right, dot0, dot1, len;
1008 Py_ssize_t i, j;
1009 PyObject *result;
1010 int kind;
1011 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001012
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001013 len = PyUnicode_GET_LENGTH(path);
1014 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Look back two slashes from the end. In between these two slashes
1018 must be the string __pycache__ or this is not a PEP 3147 style
1019 path. It's possible for there to be only one slash.
1020 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001021 right = rightmost_sep_obj(path, 0, len);
1022 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001024 left = rightmost_sep_obj(path, 0, right);
1025 if (left == -1)
1026 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 else
1028 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001029 if (right-left != sizeof(CACHEDIR)-1)
1030 return NULL;
1031 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
1032 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
1033 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Now verify that the path component to the right of the last slash
1036 has two dots in it.
1037 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001038 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
1039 if (dot0 < 0)
1040 return NULL;
1041 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
1042 if (dot1 < 0)
1043 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001045 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
1046 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* This is a PEP 3147 path. Start by copying everything from the
1049 start of pathname up to and including the leftmost slash. Then
1050 copy the file's basename, removing the magic tag and adding a .py
1051 suffix.
1052 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001053 result = PyUnicode_New(left + (dot0-right) + 2,
1054 PyUnicode_MAX_CHAR_VALUE(path));
1055 if (!result)
1056 return NULL;
1057 kind = PyUnicode_KIND(result);
1058 data = PyUnicode_DATA(result);
1059 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
1060 PyUnicode_CopyCharacters(result, left, path, right+1,
1061 (j = dot0-right));
1062 PyUnicode_WRITE(kind, data, i+j, 'p');
1063 PyUnicode_WRITE(kind, data, i+j+1, 'y');
1064 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001065}
1066
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001067/* Given a pathname for a Python source file, its time of last
1068 modification, and a pathname for a compiled file, check whether the
1069 compiled file represents the same version of the source. If so,
1070 return a FILE pointer for the compiled file, positioned just after
1071 the header; if not, return NULL.
1072 Doesn't set an exception. */
1073
1074static FILE *
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001075check_compiled_module(PyObject *pathname, struct stat *srcstat, PyObject *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 FILE *fp;
1078 long magic;
1079 long pyc_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001080 long pyc_size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001081
Victor Stinner2f42ae52011-03-20 00:41:24 +01001082 fp = _Py_fopen(cpathname, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (fp == NULL)
1084 return NULL;
1085 magic = PyMarshal_ReadLongFromFile(fp);
1086 if (magic != pyc_magic) {
1087 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001088 PySys_FormatStderr("# %R has bad magic\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 fclose(fp);
1090 return NULL;
1091 }
1092 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001093 if (pyc_mtime != srcstat->st_mtime) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001095 PySys_FormatStderr("# %R has bad mtime\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 fclose(fp);
1097 return NULL;
1098 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001099 pyc_size = PyMarshal_ReadLongFromFile(fp);
1100 if (pyc_size != (srcstat->st_size & 0xFFFFFFFF)) {
1101 if (Py_VerboseFlag)
1102 PySys_FormatStderr("# %R has bad size\n", cpathname);
1103 fclose(fp);
1104 return NULL;
1105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001107 PySys_FormatStderr("# %R matches %R\n", cpathname, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001109}
1110
1111
1112/* Read a code object from a file and check it for validity */
1113
Guido van Rossum79f25d91997-04-29 20:08:16 +00001114static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001115read_compiled_module(PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 co = PyMarshal_ReadLastObjectFromFile(fp);
1120 if (co == NULL)
1121 return NULL;
1122 if (!PyCode_Check(co)) {
1123 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001124 "Non-code object in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 Py_DECREF(co);
1126 return NULL;
1127 }
1128 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001129}
1130
1131
1132/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001133 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001134
Guido van Rossum79f25d91997-04-29 20:08:16 +00001135static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001136load_compiled_module(PyObject *name, PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 long magic;
1139 PyCodeObject *co;
1140 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 magic = PyMarshal_ReadLongFromFile(fp);
1143 if (magic != pyc_magic) {
1144 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001145 "Bad magic number in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return NULL;
1147 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001148 /* Skip mtime and size */
1149 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 (void) PyMarshal_ReadLongFromFile(fp);
1151 co = read_compiled_module(cpathname, fp);
1152 if (co == NULL)
1153 return NULL;
1154 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001155 PySys_FormatStderr("import %U # precompiled from %R\n",
1156 name, cpathname);
1157 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1158 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001162}
1163
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001164/* Parse a source file and return the corresponding code object */
1165
Guido van Rossum79f25d91997-04-29 20:08:16 +00001166static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001167parse_source_module(PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001168{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001169 PyCodeObject *co;
1170 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 mod_ty mod;
1172 PyCompilerFlags flags;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001173 PyArena *arena;
1174
1175 pathbytes = PyUnicode_EncodeFSDefault(pathname);
1176 if (pathbytes == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001178
Victor Stinner2f42ae52011-03-20 00:41:24 +01001179 arena = PyArena_New();
1180 if (arena == NULL) {
1181 Py_DECREF(pathbytes);
1182 return NULL;
1183 }
1184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 flags.cf_flags = 0;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001186 mod = PyParser_ASTFromFile(fp, PyBytes_AS_STRING(pathbytes), NULL,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_file_input, 0, 0, &flags,
1188 NULL, arena);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001189 if (mod != NULL)
1190 co = PyAST_Compile(mod, PyBytes_AS_STRING(pathbytes), NULL, arena);
1191 else
1192 co = NULL;
1193 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyArena_Free(arena);
1195 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001196}
1197
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001198/* Write a compiled module to a file, placing the time of last
1199 modification of its source into the header.
1200 Errors are ignored, if a write error occurs an attempt is made to
1201 remove the file. */
1202
1203static void
Victor Stinner2f42ae52011-03-20 00:41:24 +01001204write_compiled_module(PyCodeObject *co, PyObject *cpathname,
1205 struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001206{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207 Py_UCS4 *cpathname_ucs4;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 time_t mtime = srcstat->st_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001210 long size = srcstat->st_size & 0xFFFFFFFF;
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001211 PyObject *cpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001212#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Victor Stinner1f795172011-11-17 00:45:54 +01001214 wchar_t *wdirname, *wpathname, *wpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001215#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 mode_t dirmode = (srcstat->st_mode |
1217 S_IXUSR | S_IXGRP | S_IXOTH |
1218 S_IWUSR | S_IWGRP | S_IWOTH);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001219 PyObject *dirbytes;
Antoine Pitrou707033a2011-10-17 19:28:44 +02001220 PyObject *cpathbytes, *cpathbytes_tmp;
Victor Stinner783c82c2011-04-20 03:27:51 +02001221#endif
Charles-François Natali0c929d92011-11-10 19:12:29 +01001222 int fd;
Victor Stinner783c82c2011-04-20 03:27:51 +02001223 PyObject *dirname;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 Py_UCS4 *dirsep;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001225 int res, ok;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 /* Ensure that the __pycache__ directory exists. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 cpathname_ucs4 = PyUnicode_AsUCS4Copy(cpathname);
1229 if (!cpathname_ucs4)
1230 return;
1231 dirsep = rightmost_sep(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001232 if (dirsep == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001234 PySys_FormatStderr("# no %s path found %R\n", CACHEDIR, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return;
1236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001237 dirname = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
1238 cpathname_ucs4,
1239 dirsep - cpathname_ucs4);
1240 PyMem_Free(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001241 if (dirname == NULL) {
1242 PyErr_Clear();
1243 return;
1244 }
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001245
1246#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001247 wdirname = PyUnicode_AsUnicode(dirname);
1248 if (wdirname == NULL) {
1249 PyErr_Clear();
1250 return;
1251 }
1252 res = CreateDirectoryW(wdirname, NULL);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001253 ok = (res != 0);
1254 if (!ok && GetLastError() == ERROR_ALREADY_EXISTS)
1255 ok = 1;
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001256#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001257 dirbytes = PyUnicode_EncodeFSDefault(dirname);
1258 if (dirbytes == NULL) {
1259 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return;
1261 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001262 res = mkdir(PyBytes_AS_STRING(dirbytes), dirmode);
1263 Py_DECREF(dirbytes);
1264 if (0 <= res)
1265 ok = 1;
1266 else
1267 ok = (errno == EEXIST);
1268#endif
1269 if (!ok) {
1270 if (Py_VerboseFlag)
1271 PySys_FormatStderr("# cannot create cache dir %R\n", dirname);
1272 Py_DECREF(dirname);
1273 return;
1274 }
1275 Py_DECREF(dirname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001276
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001277 /* We first write to a tmp file and then take advantage
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001278 of atomic renaming (which *should* be true even under Windows).
1279 As in importlib, we use id(something) to generate a pseudo-random
1280 filename. mkstemp() can't be used since it doesn't allow specifying
1281 the file access permissions.
1282 */
1283 cpathname_tmp = PyUnicode_FromFormat("%U.%zd",
1284 cpathname, (Py_ssize_t) co);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001285 if (cpathname_tmp == NULL) {
1286 PyErr_Clear();
1287 return;
1288 }
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001289#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001290 wpathname = PyUnicode_AsUnicode(cpathname);
1291 if (wpathname == NULL) {
1292 PyErr_Clear();
1293 return;
1294 }
1295 wpathname_tmp = PyUnicode_AsUnicode(cpathname_tmp);
1296 if (wpathname_tmp == NULL) {
1297 PyErr_Clear();
1298 return;
1299 }
1300
1301 (void)DeleteFileW(wpathname_tmp);
1302 fd = _wopen(wpathname_tmp,
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001303 O_EXCL | O_CREAT | O_WRONLY | O_BINARY,
1304 mode);
Victor Stinner783c82c2011-04-20 03:27:51 +02001305 if (0 <= fd)
1306 fp = fdopen(fd, "wb");
1307 else
1308 fp = NULL;
1309#else
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001310 cpathbytes_tmp = PyUnicode_EncodeFSDefault(cpathname_tmp);
1311 Py_DECREF(cpathname_tmp);
1312 if (cpathbytes_tmp == NULL) {
1313 PyErr_Clear();
1314 return;
1315 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001316 cpathbytes = PyUnicode_EncodeFSDefault(cpathname);
1317 if (cpathbytes == NULL) {
1318 PyErr_Clear();
1319 return;
1320 }
Charles-François Natali0c929d92011-11-10 19:12:29 +01001321 fd = open(PyBytes_AS_STRING(cpathbytes_tmp),
1322 O_CREAT | O_EXCL | O_WRONLY, 0666);
Charles-François Natalie695eec2011-10-31 20:47:31 +01001323 if (0 <= fd)
1324 fp = fdopen(fd, "wb");
1325 else
1326 fp = NULL;
Victor Stinner783c82c2011-04-20 03:27:51 +02001327#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (fp == NULL) {
1329 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001330 PySys_FormatStderr(
1331 "# can't create %R\n", cpathname);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001332#ifdef MS_WINDOWS
1333 Py_DECREF(cpathname_tmp);
1334#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001335 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001336 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001337#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 return;
1339 }
1340 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001341 /* First write a 0 for mtime and size */
1342 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1344 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001345 fflush(fp);
Antoine Pitrou58161662012-01-25 18:06:07 +01001346 /* Now write the true mtime and size (as 32-bit fields) */
Antoine Pitrou707033a2011-10-17 19:28:44 +02001347 fseek(fp, 4L, 0);
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001348 assert(mtime <= 0xFFFFFFFF);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001349 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001350 PyMarshal_WriteLongToFile(size, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (fflush(fp) != 0 || ferror(fp)) {
1352 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001353 PySys_FormatStderr("# can't write %R\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 /* Don't keep partial file */
1355 fclose(fp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001356#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001357 (void)DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001358 Py_DECREF(cpathname_tmp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001359#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001360 (void) unlink(PyBytes_AS_STRING(cpathbytes_tmp));
Victor Stinner2f42ae52011-03-20 00:41:24 +01001361 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001362 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001363#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 return;
1365 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 fclose(fp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001367 /* Do a (hopefully) atomic rename */
1368#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001369 if (!MoveFileExW(wpathname_tmp, wpathname, MOVEFILE_REPLACE_EXISTING)) {
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001370 if (Py_VerboseFlag)
1371 PySys_FormatStderr("# can't write %R\n", cpathname);
1372 /* Don't keep tmp file */
Victor Stinner1f795172011-11-17 00:45:54 +01001373 (void) DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001374 Py_DECREF(cpathname_tmp);
1375 return;
1376 }
1377 Py_DECREF(cpathname_tmp);
1378#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001379 if (rename(PyBytes_AS_STRING(cpathbytes_tmp),
1380 PyBytes_AS_STRING(cpathbytes))) {
1381 if (Py_VerboseFlag)
1382 PySys_FormatStderr("# can't write %R\n", cpathname);
1383 /* Don't keep tmp file */
1384 unlink(PyBytes_AS_STRING(cpathbytes_tmp));
1385 Py_DECREF(cpathbytes);
1386 Py_DECREF(cpathbytes_tmp);
1387 return;
1388 }
1389 Py_DECREF(cpathbytes);
1390 Py_DECREF(cpathbytes_tmp);
1391#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001393 PySys_FormatStderr("# wrote %R\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001394}
1395
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001396static void
1397update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PyObject *constants, *tmp;
1400 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (PyUnicode_Compare(co->co_filename, oldname))
1403 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 tmp = co->co_filename;
1406 co->co_filename = newname;
1407 Py_INCREF(co->co_filename);
1408 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 constants = co->co_consts;
1411 n = PyTuple_GET_SIZE(constants);
1412 for (i = 0; i < n; i++) {
1413 tmp = PyTuple_GET_ITEM(constants, i);
1414 if (PyCode_Check(tmp))
1415 update_code_filenames((PyCodeObject *)tmp,
1416 oldname, newname);
1417 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001418}
1419
Victor Stinner2f42ae52011-03-20 00:41:24 +01001420static void
1421update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001422{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001423 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001424
Victor Stinner2f42ae52011-03-20 00:41:24 +01001425 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1426 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 oldname = co->co_filename;
1429 Py_INCREF(oldname);
1430 update_code_filenames(co, oldname, newname);
1431 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001432}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001433
Brett Cannon442c9b92011-03-23 16:14:42 -07001434static PyObject *
1435imp_fix_co_filename(PyObject *self, PyObject *args)
1436{
1437 PyObject *co;
1438 PyObject *file_path;
1439
1440 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1441 return NULL;
1442
1443 if (!PyCode_Check(co)) {
1444 PyErr_SetString(PyExc_TypeError,
1445 "first argument must be a code object");
1446 return NULL;
1447 }
1448
1449 if (!PyUnicode_Check(file_path)) {
1450 PyErr_SetString(PyExc_TypeError,
1451 "second argument must be a string");
1452 return NULL;
1453 }
1454
1455 update_compiled_module((PyCodeObject*)co, file_path);
1456
1457 Py_RETURN_NONE;
1458}
1459
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001460/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001461 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1462 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001463
Guido van Rossum79f25d91997-04-29 20:08:16 +00001464static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001465load_source_module(PyObject *name, PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 struct stat st;
1468 FILE *fpc;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001469 PyObject *cpathname = NULL, *cpathbytes = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyCodeObject *co;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001471 PyObject *m = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (fstat(fileno(fp), &st) != 0) {
1474 PyErr_Format(PyExc_RuntimeError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001475 "unable to get file status from %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001477 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 }
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001479 if (sizeof st.st_mtime > 4) {
1480 /* Python's .pyc timestamp handling presumes that the timestamp fits
1481 in 4 bytes. Since the code only does an equality comparison,
1482 ordering is not important and we can safely ignore the higher bits
1483 (collisions are extremely unlikely).
1484 */
1485 st.st_mtime &= 0xFFFFFFFF;
1486 }
Martin v. Löwis30260a72011-10-23 17:35:46 +02001487 if (PyUnicode_READY(pathname) < 0)
1488 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001489 cpathname = make_compiled_pathname(pathname, !Py_OptimizeFlag);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001490
1491 if (cpathname != NULL)
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001492 fpc = check_compiled_module(pathname, &st, cpathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001493 else
1494 fpc = NULL;
1495
1496 if (fpc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 co = read_compiled_module(cpathname, fpc);
1498 fclose(fpc);
1499 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001500 goto error;
1501 update_compiled_module(co, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001503 PySys_FormatStderr("import %U # precompiled from %R\n",
1504 name, cpathname);
1505 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1506 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 }
1508 else {
1509 co = parse_source_module(pathname, fp);
1510 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001511 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001513 PySys_FormatStderr("import %U # from %R\n",
Victor Stinner98dbba52011-03-14 15:15:47 -04001514 name, pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001515 if (cpathname != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1517 if (ro == NULL || !PyObject_IsTrue(ro))
1518 write_compiled_module(co, cpathname, &st);
1519 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001520 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1521 pathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001524
Victor Stinner2f42ae52011-03-20 00:41:24 +01001525error:
1526 Py_XDECREF(cpathbytes);
1527 Py_XDECREF(cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001529}
1530
Christian Heimes3b06e532008-01-07 20:12:44 +00001531/* Get source file -> unicode or None
1532 * Returns the path to the py file if available, else the given path
1533 */
1534static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001535get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001538 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001539 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001541 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001544 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001546
Victor Stinnerc9abda02011-03-14 13:33:46 -04001547 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001548 fileuni = PyUnicode_AsUCS4Copy(filename);
1549 if (!fileuni)
1550 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001551 if (len < 5
1552 || fileuni[len-4] != '.'
1553 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1554 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1555 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* Start by trying to turn PEP 3147 path into source path. If that
1558 * fails, just chop off the trailing character, i.e. legacy pyc path
1559 * to py.
1560 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001561 py = make_source_pathname(filename);
1562 if (py == NULL) {
1563 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001566 if (py == NULL)
1567 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001568
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001569 err = _Py_stat(py, &statbuf);
1570 if (err == -2)
1571 goto error;
1572 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001573 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001574 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001575 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001576 Py_DECREF(py);
1577 goto unchanged;
1578
1579error:
1580 PyErr_Clear();
1581unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001582 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001583 Py_INCREF(filename);
1584 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001585}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001586
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001587/* Forward */
Victor Stinner41c5fec2011-03-13 21:46:30 -04001588static PyObject *load_module(PyObject *, FILE *, PyObject *, int, PyObject *);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001589static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001590 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001591static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001592
1593/* Load a package and return its module object WITH INCREMENTED
1594 REFERENCE COUNT */
1595
1596static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001597load_package(PyObject *name, PyObject *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001598{
Victor Stinner41c5fec2011-03-13 21:46:30 -04001599 PyObject *m, *d, *bufobj;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001600 PyObject *file = NULL, *path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 int err;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001602 FILE *fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001604
Victor Stinnerc9abda02011-03-14 13:33:46 -04001605 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (m == NULL)
1607 return NULL;
1608 if (Py_VerboseFlag)
Victor Stinner98dbba52011-03-14 15:15:47 -04001609 PySys_FormatStderr("import %U # directory %R\n",
1610 name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 file = get_sourcefile(pathname);
1612 if (file == NULL)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001613 return NULL;
1614 path_list = Py_BuildValue("[O]", file);
1615 if (path_list == NULL) {
1616 Py_DECREF(file);
1617 return NULL;
1618 }
1619 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 err = PyDict_SetItemString(d, "__file__", file);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001621 Py_DECREF(file);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (err == 0)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001623 err = PyDict_SetItemString(d, "__path__", path_list);
1624 if (err != 0) {
1625 Py_DECREF(path_list);
1626 return NULL;
1627 }
Victor Stinner533d7832011-03-14 13:22:54 -04001628 fdp = find_module(name, initstr, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001629 &bufobj, &fp, NULL);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001630 Py_DECREF(path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (fdp == NULL) {
1632 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1633 PyErr_Clear();
1634 Py_INCREF(m);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001635 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 }
1637 else
Victor Stinnerc9abda02011-03-14 13:33:46 -04001638 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001640 m = load_module(name, fp, bufobj, fdp->type, NULL);
1641 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (fp != NULL)
1643 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001645}
1646
1647
1648/* Helper to test for built-in module */
1649
1650static int
Victor Stinner95872862011-03-07 18:20:56 +01001651is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001652{
Victor Stinner95872862011-03-07 18:20:56 +01001653 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001655 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1656 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (PyImport_Inittab[i].initfunc == NULL)
1658 return -1;
1659 else
1660 return 1;
1661 }
1662 }
1663 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001664}
1665
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001666
Just van Rossum52e14d62002-12-30 22:08:05 +00001667/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1668 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001669 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001670 that can handle the path item. Return None if no hook could;
1671 this tells our caller it should fall back to the builtin
1672 import mechanism. Cache the result in path_importer_cache.
1673 Returns a borrowed reference. */
1674
1675static PyObject *
1676get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyObject *importer;
1680 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* These conditions are the caller's responsibility: */
1683 assert(PyList_Check(path_hooks));
1684 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 nhooks = PyList_Size(path_hooks);
1687 if (nhooks < 0)
1688 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 importer = PyDict_GetItem(path_importer_cache, p);
1691 if (importer != NULL)
1692 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* set path_importer_cache[p] to None to avoid recursion */
1695 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1696 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 for (j = 0; j < nhooks; j++) {
1699 PyObject *hook = PyList_GetItem(path_hooks, j);
1700 if (hook == NULL)
1701 return NULL;
1702 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1703 if (importer != NULL)
1704 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1707 return NULL;
1708 }
1709 PyErr_Clear();
1710 }
1711 if (importer == NULL) {
1712 importer = PyObject_CallFunctionObjArgs(
1713 (PyObject *)&PyNullImporter_Type, p, NULL
1714 );
1715 if (importer == NULL) {
1716 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1717 PyErr_Clear();
1718 return Py_None;
1719 }
1720 }
1721 }
1722 if (importer != NULL) {
1723 int err = PyDict_SetItem(path_importer_cache, p, importer);
1724 Py_DECREF(importer);
1725 if (err != 0)
1726 return NULL;
1727 }
1728 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001729}
1730
Christian Heimes9cd17752007-11-18 19:35:23 +00001731PyAPI_FUNC(PyObject *)
1732PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1736 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1737 importer = get_path_importer(path_importer_cache,
1738 path_hooks, path);
1739 }
1740 }
1741 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1742 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001743}
1744
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001745/* Search the path (default sys.path) for a module. Return the
1746 corresponding filedescr struct, and (via return arguments) the
1747 pathname and an open file. Return NULL if the module is not found. */
1748
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001749#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001750extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1751 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001752#endif
1753
Victor Stinner547a2a62011-03-20 03:07:28 +01001754/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001755static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001756static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001757static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001758
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001759/* Get the path of a module: get its importer and call importer.find_module()
1760 hook, or check if the module if a package (if path/__init__.py exists).
1761
1762 -1: error: a Python error occurred
1763 0: ignore: an error occurred because of invalid data, but the error is not
1764 important enough to be reported.
1765 1: get path: module not found, but *buf contains its path
1766 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1767 and *buf is the path */
1768
1769static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001770find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001771 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001772 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001773{
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001774 PyObject *path_unicode, *filename = NULL;
1775 Py_ssize_t len, pos;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001776 struct stat statbuf;
1777 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001778 int err, result, addsep;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001779
1780 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001781 Py_INCREF(path);
1782 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001783 }
1784 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001785 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1786 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1787 if (path_unicode == NULL)
1788 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001789 }
1790 else
1791 return 0;
1792
Victor Stinner46084ba2011-10-06 02:39:42 +02001793 if (PyUnicode_READY(path_unicode))
1794 return -1;
1795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 len = PyUnicode_GET_LENGTH(path_unicode);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001797 if (PyUnicode_FindChar(path_unicode, 0, 0, len, 1) != -1) {
1798 result = 0;
1799 goto out; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001800 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001801
1802 /* sys.path_hooks import hook */
1803 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001804 _Py_IDENTIFIER(find_module);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001805 PyObject *importer;
1806
1807 importer = get_path_importer(path_importer_cache,
1808 path_hooks, path);
1809 if (importer == NULL) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001810 result = -1;
1811 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001812 }
1813 /* Note: importer is a borrowed reference */
1814 if (importer != Py_None) {
1815 PyObject *loader;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001816 loader = _PyObject_CallMethodId(importer,
1817 &PyId_find_module, "O", fullname);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001818 if (loader == NULL) {
1819 result = -1; /* error */
1820 goto out;
1821 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001822 if (loader != Py_None) {
1823 /* a loader was found */
1824 *p_loader = loader;
1825 *p_fd = &importhookdescr;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001826 result = 2;
1827 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001828 }
1829 Py_DECREF(loader);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001830 result = 0;
1831 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001832 }
1833 }
1834 /* no hook was found, use builtin import */
1835
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001836 addsep = 0;
1837 if (len > 0 && PyUnicode_READ_CHAR(path_unicode, len-1) != SEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001838#ifdef ALTSEP
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001839 && PyUnicode_READ_CHAR(path_unicode, len-1) != ALTSEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001840#endif
1841 )
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001842 addsep = 1;
1843 filename = PyUnicode_New(len + PyUnicode_GET_LENGTH(name) + addsep,
1844 Py_MAX(PyUnicode_MAX_CHAR_VALUE(path_unicode),
1845 PyUnicode_MAX_CHAR_VALUE(name)));
1846 if (filename == NULL) {
1847 result = -1;
1848 goto out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 }
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001850 PyUnicode_CopyCharacters(filename, 0, path_unicode, 0, len);
1851 pos = len;
1852 if (addsep)
Victor Stinner1f795172011-11-17 00:45:54 +01001853 PyUnicode_WRITE(PyUnicode_KIND(filename),
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001854 PyUnicode_DATA(filename),
1855 pos++, SEP);
Victor Stinner1f795172011-11-17 00:45:54 +01001856 PyUnicode_CopyCharacters(filename, pos, name, 0,
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001857 PyUnicode_GET_LENGTH(name));
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001858
1859 /* Check for package import (buf holds a directory name,
1860 and there's an __init__ module in that directory */
1861#ifdef HAVE_STAT
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001862 err = _Py_stat(filename, &statbuf);
1863 if (err == -2) {
1864 result = -1;
1865 goto out;
1866 }
1867 if (err == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001868 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1869 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001870 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001871
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001872 match = case_ok(filename, 0, name);
1873 if (match < 0) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001874 result = -1;
1875 goto out;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001876 }
1877 if (match) { /* case matches */
1878 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001879 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001880 filename = NULL;
Victor Stinnerd0296212011-03-14 14:04:10 -04001881 *p_fd = &fd_package;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001882 result = 2;
1883 goto out;
Victor Stinnerd0296212011-03-14 14:04:10 -04001884 }
1885 else {
1886 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001887 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001888 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001889 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001890 if (err) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001891 result = -1;
1892 goto out;
Victor Stinner547a2a62011-03-20 03:07:28 +01001893 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001894 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001895 }
1896 }
1897#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001898 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001899 filename = NULL;
1900 result = 1;
1901 out:
1902 Py_DECREF(path_unicode);
1903 Py_XDECREF(filename);
1904 return result;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001905}
1906
1907/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001908 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001909
1910 If the module is found, return a file descriptor, write the path in
1911 *p_filename, write the pointer to the file object into *p_fp, and (if
1912 p_loader is not NULL) the loader into *p_loader.
1913
1914 Otherwise, raise an exception and return NULL. */
1915
Victor Stinner37580282011-03-20 01:34:43 +01001916static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001917find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001918 PyObject *search_path_list, PyObject *path_hooks,
1919 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001920 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 struct filedescr *fdp = NULL;
1924 char *filemode;
1925 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001926 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001927 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001928 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001929
Victor Stinner37580282011-03-20 01:34:43 +01001930 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001932 PyObject *path;
1933 int ok;
1934
1935 path = PyList_GetItem(search_path_list, i);
1936 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001938
Victor Stinner2fd76e42011-03-14 15:19:39 -04001939 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001940 ok = find_module_path(fullname, name, path,
1941 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001942 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001943 if (ok < 0)
1944 return NULL;
1945 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001947 if (ok == 2) {
1948 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001949 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001950 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001953 struct stat statbuf;
1954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 filemode = fdp->mode;
1956 if (filemode[0] == 'U')
1957 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001958
Victor Stinner2fd76e42011-03-14 15:19:39 -04001959 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1960 if (filename == NULL) {
1961 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001962 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001963 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001964
1965 if (Py_VerboseFlag > 1)
1966 PySys_FormatStderr("# trying %R\n", filename);
1967
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001968 err = _Py_stat(filename, &statbuf);
1969 if (err == -2) {
1970 Py_DECREF(prefix);
1971 Py_DECREF(filename);
1972 return NULL;
1973 }
1974 if (err != 0 || S_ISDIR(statbuf.st_mode)) {
Charles-François Natali1659b832011-12-07 23:17:58 +01001975 /* it doesn't exist, or it's a directory */
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001976 Py_DECREF(filename);
1977 continue;
1978 }
1979
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001980 fp = _Py_fopen(filename, filemode);
1981 if (fp == NULL) {
1982 Py_DECREF(filename);
Victor Stinner925ef392011-06-20 15:01:10 +02001983 if (PyErr_Occurred()) {
1984 Py_DECREF(prefix);
1985 return NULL;
1986 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001987 continue;
1988 }
1989 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
1990 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001991 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001992 Py_DECREF(filename);
1993 return NULL;
1994 }
1995 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001996 Py_DECREF(prefix);
1997 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04001998 *p_fp = fp;
1999 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002001 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04002002
2003 fclose(fp);
2004 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002006 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 }
Victor Stinnerd0296212011-03-14 14:04:10 -04002008 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002009 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04002010 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002011}
2012
Victor Stinner37580282011-03-20 01:34:43 +01002013/* Find a module:
2014
2015 - try find_module() of each sys.meta_path hook
2016 - try find_frozen()
2017 - try is_builtin()
2018 - try _PyWin_FindRegisteredModule() (Windows only)
2019 - otherwise, call find_module_path_list() with search_path_list (if not
2020 NULL) or sys.path
2021
Victor Stinner2fd76e42011-03-14 15:19:39 -04002022 fullname can be NULL, but only if p_loader is NULL.
2023
Victor Stinner37580282011-03-20 01:34:43 +01002024 Return:
2025
2026 - &fd_builtin (C_BUILTIN) if it is a builtin
2027 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04002028 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01002029 if it is a package
2030 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
2031 importer loader was found
2032 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
2033 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04002034 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01002035 - NULL on error
2036
Victor Stinner2fd76e42011-03-14 15:19:39 -04002037 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
2038 Eg. *p_path is set to NULL for a builtin package.
2039*/
Victor Stinner37580282011-03-20 01:34:43 +01002040
2041static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002042find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002043 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01002044{
2045 Py_ssize_t i, npath;
2046 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
2047 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
2048 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01002049
Victor Stinner2fd76e42011-03-14 15:19:39 -04002050 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01002051 *p_fp = NULL;
2052 if (p_loader != NULL)
2053 *p_loader = NULL;
2054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002055 if (PyUnicode_GET_LENGTH(name) > MAXPATHLEN) {
2056 PyErr_SetString(PyExc_OverflowError,
2057 "module name is too long");
2058 return NULL;
2059 }
2060
Victor Stinner37580282011-03-20 01:34:43 +01002061 /* sys.meta_path import hook */
2062 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002063 _Py_IDENTIFIER(find_module);
Victor Stinner37580282011-03-20 01:34:43 +01002064 PyObject *meta_path;
2065
2066 meta_path = PySys_GetObject("meta_path");
2067 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02002068 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002069 "sys.meta_path must be a list of "
2070 "import hooks");
2071 return NULL;
2072 }
2073 Py_INCREF(meta_path); /* zap guard */
2074 npath = PyList_Size(meta_path);
2075 for (i = 0; i < npath; i++) {
2076 PyObject *loader;
2077 PyObject *hook = PyList_GetItem(meta_path, i);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002078 loader = _PyObject_CallMethodId(hook, &PyId_find_module,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002079 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01002080 search_path_list != NULL ?
2081 search_path_list : Py_None);
2082 if (loader == NULL) {
2083 Py_DECREF(meta_path);
2084 return NULL; /* true error */
2085 }
2086 if (loader != Py_None) {
2087 /* a loader was found */
2088 *p_loader = loader;
2089 Py_DECREF(meta_path);
2090 return &importhookdescr;
2091 }
2092 Py_DECREF(loader);
2093 }
2094 Py_DECREF(meta_path);
2095 }
2096
Victor Stinnerdf75a022011-03-14 13:40:04 -04002097 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002098 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01002099
2100 if (search_path_list == NULL) {
2101#ifdef MS_COREDLL
2102 FILE *fp;
2103 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01002104#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04002105 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01002106 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01002107#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04002108 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01002109 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01002110 *p_fp = fp;
2111 return fdp;
2112 }
2113 else if (PyErr_Occurred())
2114 return NULL;
2115#endif
Victor Stinner37580282011-03-20 01:34:43 +01002116 search_path_list = PySys_GetObject("path");
2117 }
2118
2119 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
Victor Stinner16191322011-09-15 19:28:05 +02002120 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002121 "sys.path must be a list of directory names");
2122 return NULL;
2123 }
2124
2125 path_hooks = PySys_GetObject("path_hooks");
2126 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02002127 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002128 "sys.path_hooks must be a list of "
2129 "import hooks");
2130 return NULL;
2131 }
2132 path_importer_cache = PySys_GetObject("path_importer_cache");
2133 if (path_importer_cache == NULL ||
2134 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02002135 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002136 "sys.path_importer_cache must be a dict");
2137 return NULL;
2138 }
2139
2140 return find_module_path_list(fullname, name,
2141 search_path_list, path_hooks,
2142 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002143 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01002144}
2145
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002146/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00002147 * The arguments here are tricky, best shown by example:
2148 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2149 * ^ ^ ^ ^
2150 * |--------------------- buf ---------------------|
2151 * |------------------- len ------------------|
2152 * |------ name -------|
2153 * |----- namelen -----|
2154 * buf is the full path, but len only counts up to (& exclusive of) the
2155 * extension. name is the module name, also exclusive of extension.
2156 *
2157 * We've already done a successful stat() or fopen() on buf, so know that
2158 * there's some match, possibly case-insensitive.
2159 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002160 * case_bytes() is to return 1 if there's a case-sensitive match for
2161 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00002162 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00002163 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002164 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00002165 * on platforms with case-insensitive filesystems. It's trivial to implement
2166 * for case-sensitive filesystems. It's pretty much a cross-platform
2167 * nightmare for systems with case-insensitive filesystems.
2168 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00002169
Tim Peters50d8d372001-02-28 05:34:27 +00002170/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002171 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00002172 */
Jason Tishler7961aa62005-05-20 00:56:54 +00002173#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002174#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00002175
Tim Peters50d8d372001-02-28 05:34:27 +00002176#elif defined(DJGPP)
2177#include <dir.h>
2178
Jason Tishler7961aa62005-05-20 00:56:54 +00002179#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00002180#include <sys/types.h>
2181#include <dirent.h>
2182
Andrew MacIntyred9400542002-02-26 11:41:34 +00002183#elif defined(PYOS_OS2)
2184#define INCL_DOS
2185#define INCL_DOSERRORS
2186#define INCL_NOPMAPI
2187#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00002188#endif
2189
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002190#if defined(DJGPP) \
2191 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
2192 && defined(HAVE_DIRENT_H)) \
2193 || defined(PYOS_OS2)
2194# define USE_CASE_OK_BYTES
2195#endif
2196
2197
2198#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00002199static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002200case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002201{
Tim Peters50d8d372001-02-28 05:34:27 +00002202/* Pick a platform-specific implementation; the sequence of #if's here should
2203 * match the sequence just above.
2204 */
2205
Tim Peters50d8d372001-02-28 05:34:27 +00002206/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002207#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 struct ffblk ffblk;
2209 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (Py_GETENV("PYTHONCASEOK") != NULL)
2212 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2215 if (done) {
2216 PyErr_Format(PyExc_NameError,
2217 "Can't find file for module %.100s\n(filename %.300s)",
2218 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01002219 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 }
2221 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002222
Jason Tishler7961aa62005-05-20 00:56:54 +00002223/* new-fangled macintosh (macosx) or Cygwin */
2224#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 DIR *dirp;
2226 struct dirent *dp;
2227 char dirname[MAXPATHLEN + 1];
2228 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (Py_GETENV("PYTHONCASEOK") != NULL)
2231 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /* Copy the dir component into dirname; substitute "." if empty */
2234 if (dirlen <= 0) {
2235 dirname[0] = '.';
2236 dirname[1] = '\0';
2237 }
2238 else {
2239 assert(dirlen <= MAXPATHLEN);
2240 memcpy(dirname, buf, dirlen);
2241 dirname[dirlen] = '\0';
2242 }
2243 /* Open the directory and search the entries for an exact match. */
2244 dirp = opendir(dirname);
2245 if (dirp) {
2246 char *nameWithExt = buf + len - namelen;
2247 while ((dp = readdir(dirp)) != NULL) {
2248 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002249#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002251#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002253#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (thislen >= namelen &&
2255 strcmp(dp->d_name, nameWithExt) == 0) {
2256 (void)closedir(dirp);
2257 return 1; /* Found */
2258 }
2259 }
2260 (void)closedir(dirp);
2261 }
2262 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002263
Andrew MacIntyred9400542002-02-26 11:41:34 +00002264/* OS/2 */
2265#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 HDIR hdir = 1;
2267 ULONG srchcnt = 1;
2268 FILEFINDBUF3 ffbuf;
2269 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (Py_GETENV("PYTHONCASEOK") != NULL)
2272 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 rc = DosFindFirst(buf,
2275 &hdir,
2276 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2277 &ffbuf, sizeof(ffbuf),
2278 &srchcnt,
2279 FIL_STANDARD);
2280 if (rc != NO_ERROR)
2281 return 0;
2282 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002283
Tim Peters50d8d372001-02-28 05:34:27 +00002284/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2285#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002286# error "USE_CASE_OK_BYTES is not correctly defined"
2287#endif
2288}
2289#endif
2290
2291/*
2292 * Check if a filename case matchs the name case. We've already done a
2293 * successful stat() or fopen() on buf, so know that there's some match,
2294 * possibly case-insensitive.
2295 *
2296 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
2297 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
2298 * if envar PYTHONCASEOK exists.
2299 *
2300 * case_ok() is used to implement case-sensitive import semantics even
2301 * on platforms with case-insensitive filesystems. It's trivial to implement
2302 * for case-sensitive filesystems. It's pretty much a cross-platform
2303 * nightmare for systems with case-insensitive filesystems.
2304 */
2305
2306static int
2307case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
2308{
2309#ifdef MS_WINDOWS
2310 WIN32_FIND_DATAW data;
2311 HANDLE h;
2312 int cmp;
Victor Stinner1f795172011-11-17 00:45:54 +01002313 wchar_t *wfilename, *wname;
Victor Stinner8c981892011-10-11 22:27:13 +02002314 Py_ssize_t wname_len;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002315
2316 if (Py_GETENV("PYTHONCASEOK") != NULL)
2317 return 1;
2318
Victor Stinner1f795172011-11-17 00:45:54 +01002319 wfilename = PyUnicode_AsUnicode(filename);
2320 if (wfilename == NULL)
2321 return -1;
2322
2323 h = FindFirstFileW(wfilename, &data);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002324 if (h == INVALID_HANDLE_VALUE) {
2325 PyErr_Format(PyExc_NameError,
2326 "Can't find file for module %R\n(filename %R)",
2327 name, filename);
Victor Stinner1f795172011-11-17 00:45:54 +01002328 return -1;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002329 }
2330 FindClose(h);
Victor Stinnerbeac78b2011-10-11 21:55:01 +02002331
2332 wname = PyUnicode_AsUnicodeAndSize(name, &wname_len);
2333 if (wname == NULL)
2334 return -1;
2335
2336 cmp = wcsncmp(data.cFileName, wname, wname_len);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002337 return cmp == 0;
2338#elif defined(USE_CASE_OK_BYTES)
2339 int match;
2340 PyObject *filebytes, *namebytes;
2341 filebytes = PyUnicode_EncodeFSDefault(filename);
2342 if (filebytes == NULL)
2343 return -1;
2344 namebytes = PyUnicode_EncodeFSDefault(name);
2345 if (namebytes == NULL) {
2346 Py_DECREF(filebytes);
2347 return -1;
2348 }
2349 match = case_bytes(
2350 PyBytes_AS_STRING(filebytes),
2351 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01002352 PyBytes_GET_SIZE(namebytes),
2353 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002354 Py_DECREF(filebytes);
2355 Py_DECREF(namebytes);
2356 return match;
2357#else
2358 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002360
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002361#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002362}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002363
Guido van Rossum197346f1997-10-31 18:38:52 +00002364#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002365
Victor Stinner547a2a62011-03-20 03:07:28 +01002366/* Helper to look for __init__.py or __init__.py[co] in potential package.
2367 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00002368static int
Victor Stinner547a2a62011-03-20 03:07:28 +01002369find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00002370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01002372 PyObject *filename;
2373 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002374 int err;
Guido van Rossum197346f1997-10-31 18:38:52 +00002375
Victor Stinner547a2a62011-03-20 03:07:28 +01002376 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
2377 if (filename == NULL)
2378 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002379 err = _Py_stat(filename, &statbuf);
2380 if (err == -2)
2381 return -1;
2382 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002383 /* 3=len(".py") */
2384 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002385 if (match < 0) {
2386 Py_DECREF(filename);
2387 return -1;
2388 }
2389 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002390 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 return 1;
2392 }
2393 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002394 Py_DECREF(filename);
2395
2396 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
2397 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
2398 if (filename == NULL)
2399 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002400 err = _Py_stat(filename, &statbuf);
2401 if (err == -2) {
2402 Py_DECREF(filename);
2403 return -1;
2404 }
2405 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002406 /* 4=len(".pyc") */
2407 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002408 if (match < 0) {
2409 Py_DECREF(filename);
2410 return -1;
2411 }
2412 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002413 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return 1;
2415 }
2416 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002417 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002419}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002420
Guido van Rossum197346f1997-10-31 18:38:52 +00002421#endif /* HAVE_STAT */
2422
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002423
Victor Stinner95872862011-03-07 18:20:56 +01002424static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002425
Victor Stinner44c6c152010-08-09 00:59:10 +00002426static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002427load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002428{
2429 PyObject *m, *modules;
2430 int err;
2431
Victor Stinner44c6c152010-08-09 00:59:10 +00002432 if (type == C_BUILTIN)
2433 err = init_builtin(name);
2434 else
Victor Stinner95872862011-03-07 18:20:56 +01002435 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002436 if (err < 0)
2437 return NULL;
2438 if (err == 0) {
2439 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002440 "Purported %s module %R not found",
2441 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002442 name);
2443 return NULL;
2444 }
2445
2446 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002447 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002448 if (m == NULL) {
2449 PyErr_Format(
2450 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002451 "%s module %R not properly initialized",
2452 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002453 name);
2454 return NULL;
2455 }
2456 Py_INCREF(m);
2457 return m;
2458}
2459
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002460/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002461 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002462
Guido van Rossum79f25d91997-04-29 20:08:16 +00002463static PyObject *
Victor Stinner41c5fec2011-03-13 21:46:30 -04002464load_module(PyObject *name, FILE *fp, PyObject *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* First check that there's an open file (if we need one) */
2469 switch (type) {
2470 case PY_SOURCE:
2471 case PY_COMPILED:
2472 if (fp == NULL) {
2473 PyErr_Format(PyExc_ValueError,
Victor Stinner41c5fec2011-03-13 21:46:30 -04002474 "file object required for import (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 type);
2476 return NULL;
2477 }
2478 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002481
Victor Stinner41c5fec2011-03-13 21:46:30 -04002482 case PY_SOURCE:
2483 m = load_source_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002485
Victor Stinner41c5fec2011-03-13 21:46:30 -04002486 case PY_COMPILED:
2487 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002489
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002490#ifdef HAVE_DYNAMIC_LOADING
Victor Stinner41c5fec2011-03-13 21:46:30 -04002491 case C_EXTENSION:
2492 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002494#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002495
Victor Stinner41c5fec2011-03-13 21:46:30 -04002496 case PKG_DIRECTORY:
2497 m = load_package(name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 case C_BUILTIN:
Victor Stinner41c5fec2011-03-13 21:46:30 -04002501 case PY_FROZEN:
2502 m = load_builtin(name, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 case IMP_HOOK: {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002506 _Py_IDENTIFIER(load_module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if (loader == NULL) {
2508 PyErr_SetString(PyExc_ImportError,
2509 "import hook without loader");
2510 return NULL;
2511 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002512 m = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 break;
2514 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 default:
2517 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002518 "Don't know how to import %R (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 name, type);
2520 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002525}
2526
2527
2528/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002529 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002530 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002531
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002532static int
Victor Stinner95872862011-03-07 18:20:56 +01002533init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002536
Victor Stinner95872862011-03-07 18:20:56 +01002537 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 for (p = PyImport_Inittab; p->name != NULL; p++) {
2541 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002542 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01002543 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 if (p->initfunc == NULL) {
2545 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002546 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 name);
2548 return -1;
2549 }
2550 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002551 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 mod = (*p->initfunc)();
2553 if (mod == 0)
2554 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002555 /* Remember pointer to module init function. */
2556 def = PyModule_GetDef(mod);
2557 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01002558 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 return -1;
2560 /* FixupExtension has put the module into sys.modules,
2561 so we can release our own reference. */
2562 Py_DECREF(mod);
2563 return 1;
2564 }
2565 }
2566 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002567}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002568
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002569
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002570/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002571
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002572static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002573find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002576
Victor Stinner53dc7352011-03-20 01:50:21 +01002577 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 for (p = PyImport_FrozenModules; ; p++) {
2581 if (p->name == NULL)
2582 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002583 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 break;
2585 }
2586 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002587}
2588
Guido van Rossum79f25d91997-04-29 20:08:16 +00002589static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002590get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 struct _frozen *p = find_frozen(name);
2593 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 if (p == NULL) {
2596 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002597 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 name);
2599 return NULL;
2600 }
2601 if (p->code == NULL) {
2602 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002603 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 name);
2605 return NULL;
2606 }
2607 size = p->size;
2608 if (size < 0)
2609 size = -size;
2610 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002611}
2612
Brett Cannon8d110132009-03-15 02:20:16 +00002613static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002614is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 struct _frozen *p = find_frozen(name);
2617 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (p == NULL) {
2620 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002621 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 name);
2623 return NULL;
2624 }
Brett Cannon8d110132009-03-15 02:20:16 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (size < 0)
2629 Py_RETURN_TRUE;
2630 else
2631 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002632}
2633
2634
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002635/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002636 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002637 an exception set if the initialization failed.
2638 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002639
2640int
Victor Stinner53dc7352011-03-20 01:50:21 +01002641PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002642{
Victor Stinner53dc7352011-03-20 01:50:21 +01002643 struct _frozen *p;
2644 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 int ispackage;
2646 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002647
Victor Stinner53dc7352011-03-20 01:50:21 +01002648 p = find_frozen(name);
2649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 if (p == NULL)
2651 return 0;
2652 if (p->code == NULL) {
2653 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002654 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 name);
2656 return -1;
2657 }
2658 size = p->size;
2659 ispackage = (size < 0);
2660 if (ispackage)
2661 size = -size;
2662 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002663 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 name, ispackage ? " package" : "");
2665 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2666 if (co == NULL)
2667 return -1;
2668 if (!PyCode_Check(co)) {
2669 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002670 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 name);
2672 goto err_return;
2673 }
2674 if (ispackage) {
2675 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002676 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002678 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 if (m == NULL)
2680 goto err_return;
2681 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 l = PyList_New(1);
2683 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 goto err_return;
2685 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002686 Py_INCREF(name);
2687 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 err = PyDict_SetItemString(d, "__path__", l);
2689 Py_DECREF(l);
2690 if (err != 0)
2691 goto err_return;
2692 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002693 path = PyUnicode_FromString("<frozen>");
2694 if (path == NULL)
2695 goto err_return;
2696 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2697 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 if (m == NULL)
2699 goto err_return;
2700 Py_DECREF(co);
2701 Py_DECREF(m);
2702 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002703err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 Py_DECREF(co);
2705 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002706}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002707
Victor Stinner53dc7352011-03-20 01:50:21 +01002708int
2709PyImport_ImportFrozenModule(char *name)
2710{
2711 PyObject *nameobj;
2712 int ret;
2713 nameobj = PyUnicode_InternFromString(name);
2714 if (nameobj == NULL)
2715 return -1;
2716 ret = PyImport_ImportFrozenModuleObject(nameobj);
2717 Py_DECREF(nameobj);
2718 return ret;
2719}
2720
Guido van Rossum74e6a111994-08-29 12:54:38 +00002721
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002722/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002723 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002724
Guido van Rossum79f25d91997-04-29 20:08:16 +00002725PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002726PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 PyObject *pname;
2729 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 pname = PyUnicode_FromString(name);
2732 if (pname == NULL)
2733 return NULL;
2734 result = PyImport_Import(pname);
2735 Py_DECREF(pname);
2736 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002737}
2738
Christian Heimes072c0f12008-01-03 23:01:04 +00002739/* Import a module without blocking
2740 *
2741 * At first it tries to fetch the module from sys.modules. If the module was
2742 * never loaded before it loads it with PyImport_ImportModule() unless another
2743 * thread holds the import lock. In the latter case the function raises an
2744 * ImportError instead of blocking.
2745 *
2746 * Returns the module object with incremented ref count.
2747 */
2748PyObject *
2749PyImport_ImportModuleNoBlock(const char *name)
2750{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002751 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002752#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002754#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 /* Try to get the module from sys.modules[name] */
2757 modules = PyImport_GetModuleDict();
2758 if (modules == NULL)
2759 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002760
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002761 nameobj = PyUnicode_FromString(name);
2762 if (nameobj == NULL)
2763 return NULL;
2764 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002766 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 Py_INCREF(result);
2768 return result;
2769 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002770 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002771#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 /* check the import lock
2773 * me might be -1 but I ignore the error here, the lock function
2774 * takes care of the problem */
2775 me = PyThread_get_thread_ident();
2776 if (import_lock_thread == -1 || import_lock_thread == me) {
2777 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002778 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 }
2780 else {
2781 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002782 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002784 nameobj);
2785 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002787#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002788 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002789#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002790 Py_DECREF(nameobj);
2791 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002792}
2793
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002794/* Forward declarations for helper routines */
Victor Stinner974389d2011-03-15 09:33:57 +01002795static PyObject *get_parent(PyObject *globals,
2796 PyObject **p_name,
2797 int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002798static PyObject *load_next(PyObject *mod, PyObject *altmod,
Victor Stinner974389d2011-03-15 09:33:57 +01002799 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002800 PyObject **p_prefix);
Victor Stinner974389d2011-03-15 09:33:57 +01002801static int mark_miss(PyObject *name);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002802static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Victor Stinner974389d2011-03-15 09:33:57 +01002803 PyObject *buf, int recursive);
2804static PyObject * import_submodule(PyObject *mod, PyObject *name,
2805 PyObject *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002806
2807/* The Magnum Opus of dotted-name import :-) */
2808
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002809static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01002810import_module_level(PyObject *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002812{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002813 PyObject *parent, *next, *inputname, *outputname;
2814 PyObject *head = NULL;
2815 PyObject *tail = NULL;
2816 PyObject *prefix = NULL;
2817 PyObject *result = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002818 Py_ssize_t sep, altsep;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 if (PyUnicode_READY(name))
2821 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002823 sep = PyUnicode_FindChar(name, SEP, 0, PyUnicode_GET_LENGTH(name), 1);
2824 if (sep == -2)
2825 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002826#ifdef ALTSEP
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002827 altsep = PyUnicode_FindChar(name, ALTSEP, 0, PyUnicode_GET_LENGTH(name), 1);
2828 if (altsep == -2)
2829 return NULL;
2830#else
2831 altsep = -1;
Christian Heimes454f37b2008-01-10 00:10:02 +00002832#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002833 if (sep != -1 || altsep != -1)
2834 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 PyErr_SetString(PyExc_ImportError,
2836 "Import by filename is not supported.");
2837 return NULL;
2838 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002839
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002840 parent = get_parent(globals, &prefix, level);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 if (parent == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002843 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002844
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002845 if (PyUnicode_READY(prefix))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002846 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002847
2848 head = load_next(parent, level < 0 ? Py_None : parent, name, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002849 &prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 if (head == NULL)
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002851 goto out;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 tail = head;
2854 Py_INCREF(tail);
Victor Stinner974389d2011-03-15 09:33:57 +01002855
2856 if (outputname != NULL) {
2857 while (1) {
2858 inputname = outputname;
2859 next = load_next(tail, tail, inputname, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002860 &prefix);
2861 Py_CLEAR(tail);
2862 Py_CLEAR(inputname);
2863 if (next == NULL)
2864 goto out;
Victor Stinner974389d2011-03-15 09:33:57 +01002865 tail = next;
2866
2867 if (outputname == NULL) {
2868 break;
2869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 }
2872 if (tail == Py_None) {
2873 /* If tail is Py_None, both get_parent and load_next found
2874 an empty module name: someone called __import__("") or
2875 doctored faulty bytecode */
Victor Stinner974389d2011-03-15 09:33:57 +01002876 PyErr_SetString(PyExc_ValueError, "Empty module name");
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002877 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 if (fromlist != NULL) {
2881 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2882 fromlist = NULL;
2883 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (fromlist == NULL) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002886 result = head;
2887 Py_INCREF(result);
2888 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002890
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002891 if (!ensure_fromlist(tail, fromlist, prefix, 0))
2892 goto out;
Victor Stinner1f795172011-11-17 00:45:54 +01002893
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002894 result = tail;
2895 Py_INCREF(result);
2896 out:
2897 Py_XDECREF(head);
2898 Py_XDECREF(tail);
2899 Py_XDECREF(prefix);
2900 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002901}
2902
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002903PyObject *
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002904PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2905 PyObject *locals, PyObject *fromlist,
2906 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002907{
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002908 PyObject *mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 _PyImport_AcquireLock();
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002910 mod = import_module_level(name, globals, locals, fromlist, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 if (_PyImport_ReleaseLock() < 0) {
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002912 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyErr_SetString(PyExc_RuntimeError,
2914 "not holding the import lock");
2915 return NULL;
2916 }
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002917 return mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002918}
2919
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002920PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002921PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002922 PyObject *fromlist, int level)
2923{
2924 PyObject *nameobj, *mod;
2925 nameobj = PyUnicode_FromString(name);
2926 if (nameobj == NULL)
2927 return NULL;
2928 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2929 fromlist, level);
2930 Py_DECREF(nameobj);
2931 return mod;
2932}
2933
2934
Fred Drake87590902004-05-28 20:21:36 +00002935/* Return the package that an import is being performed in. If globals comes
2936 from the module foo.bar.bat (not itself a package), this returns the
2937 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002938 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002939
Victor Stinner974389d2011-03-15 09:33:57 +01002940 The name of the returned package is returned in *p_name.
Fred Drake87590902004-05-28 20:21:36 +00002941
2942 If globals doesn't come from a package or a module in a package, or a
2943 corresponding entry is not found in sys.modules, Py_None is returned.
2944*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002945static PyObject *
Victor Stinner9599de52011-03-13 22:38:38 -04002946get_parent(PyObject *globals, PyObject **p_name, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002947{
Victor Stinner974389d2011-03-15 09:33:57 +01002948 PyObject *nameobj;
2949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 static PyObject *namestr = NULL;
2951 static PyObject *pathstr = NULL;
2952 static PyObject *pkgstr = NULL;
2953 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2954 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 if (globals == NULL || !PyDict_Check(globals) || !level)
Victor Stinner974389d2011-03-15 09:33:57 +01002957 goto return_none;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 if (namestr == NULL) {
2960 namestr = PyUnicode_InternFromString("__name__");
2961 if (namestr == NULL)
2962 return NULL;
2963 }
2964 if (pathstr == NULL) {
2965 pathstr = PyUnicode_InternFromString("__path__");
2966 if (pathstr == NULL)
2967 return NULL;
2968 }
2969 if (pkgstr == NULL) {
2970 pkgstr = PyUnicode_InternFromString("__package__");
2971 if (pkgstr == NULL)
2972 return NULL;
2973 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 if ((pkgname != NULL) && (pkgname != Py_None)) {
2978 /* __package__ is set, so use it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 if (!PyUnicode_Check(pkgname)) {
2980 PyErr_SetString(PyExc_ValueError,
2981 "__package__ set to non-string");
2982 return NULL;
2983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002984 if (PyUnicode_GET_LENGTH(pkgname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 if (level > 0) {
2986 PyErr_SetString(PyExc_ValueError,
2987 "Attempted relative import in non-package");
2988 return NULL;
2989 }
Victor Stinner974389d2011-03-15 09:33:57 +01002990 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002992 Py_INCREF(pkgname);
2993 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 } else {
2995 /* __package__ not set, so figure it out and set it */
2996 modname = PyDict_GetItem(globals, namestr);
2997 if (modname == NULL || !PyUnicode_Check(modname))
Victor Stinner974389d2011-03-15 09:33:57 +01002998 goto return_none;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 modpath = PyDict_GetItem(globals, pathstr);
3001 if (modpath != NULL) {
3002 /* __path__ is set, so modname is already the package name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 error = PyDict_SetItem(globals, pkgstr, modname);
3006 if (error) {
3007 PyErr_SetString(PyExc_ValueError,
3008 "Could not set __package__");
3009 return NULL;
3010 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003011 Py_INCREF(modname);
3012 nameobj = modname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 } else {
3014 /* Normal module, so work out the package name if any */
Victor Stinner974389d2011-03-15 09:33:57 +01003015 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003016 len = PyUnicode_FindChar(modname, '.',
3017 0, PyUnicode_GET_LENGTH(modname), -1);
3018 if (len == -2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003020 if (len < 0) {
3021 if (level > 0) {
3022 PyErr_SetString(PyExc_ValueError,
3023 "Attempted relative import in non-package");
3024 return NULL;
3025 }
3026 if (PyDict_SetItem(globals, pkgstr, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 PyErr_SetString(PyExc_ValueError,
3028 "Could not set __package__");
3029 return NULL;
3030 }
Victor Stinner974389d2011-03-15 09:33:57 +01003031 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003033 pkgname = PyUnicode_Substring(modname, 0, len);
3034 if (pkgname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003036 if (PyDict_SetItem(globals, pkgstr, pkgname)) {
3037 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 PyErr_SetString(PyExc_ValueError,
3039 "Could not set __package__");
3040 return NULL;
3041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003042 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 }
3044 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003045 if (level > 1) {
3046 Py_ssize_t dot, end = PyUnicode_GET_LENGTH(nameobj);
3047 PyObject *newname;
3048 while (--level > 0) {
3049 dot = PyUnicode_FindChar(nameobj, '.', 0, end, -1);
3050 if (dot == -2) {
3051 Py_DECREF(nameobj);
3052 return NULL;
3053 }
3054 if (dot < 0) {
3055 Py_DECREF(nameobj);
3056 PyErr_SetString(PyExc_ValueError,
3057 "Attempted relative import beyond "
3058 "toplevel package");
3059 return NULL;
3060 }
3061 end = dot;
3062 }
3063 newname = PyUnicode_Substring(nameobj, 0, end);
3064 Py_DECREF(nameobj);
3065 if (newname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003067 nameobj = newname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 }
Victor Stinner974389d2011-03-15 09:33:57 +01003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003071 parent = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 if (parent == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003073 int err;
3074
3075 if (orig_level >= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 PyErr_Format(PyExc_SystemError,
Victor Stinner974389d2011-03-15 09:33:57 +01003077 "Parent module %R not loaded, "
3078 "cannot perform relative import", nameobj);
3079 Py_DECREF(nameobj);
3080 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 }
Victor Stinner974389d2011-03-15 09:33:57 +01003082
3083 err = PyErr_WarnFormat(
3084 PyExc_RuntimeWarning, 1,
3085 "Parent module %R not found while handling absolute import",
3086 nameobj);
3087 Py_DECREF(nameobj);
3088 if (err)
3089 return NULL;
3090
3091 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 }
Victor Stinner974389d2011-03-15 09:33:57 +01003093 *p_name = nameobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 return parent;
3095 /* We expect, but can't guarantee, if parent != None, that:
Victor Stinner974389d2011-03-15 09:33:57 +01003096 - parent.__name__ == name
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 - parent.__dict__ is globals
3098 If this is violated... Who cares? */
Victor Stinner974389d2011-03-15 09:33:57 +01003099
3100return_none:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003101 nameobj = PyUnicode_New(0, 0);
Victor Stinner974389d2011-03-15 09:33:57 +01003102 if (nameobj == NULL)
3103 return NULL;
3104 *p_name = nameobj;
3105 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003106}
3107
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003108/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003109static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003110load_next(PyObject *mod, PyObject *altmod,
3111 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003112 PyObject **p_prefix)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003113{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003114 Py_ssize_t dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003115 Py_ssize_t len;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003116 PyObject *fullname, *name = NULL, *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003117
Victor Stinner974389d2011-03-15 09:33:57 +01003118 *p_outputname = NULL;
3119
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003120 len = PyUnicode_GET_LENGTH(inputname);
3121 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 /* completely empty module name should only happen in
3123 'from . import' (or '__import__("")')*/
3124 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 return mod;
3126 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003127
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003128
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003129 dot = PyUnicode_FindChar(inputname, '.', 0, len, 1);
3130 if (dot >= 0) {
3131 len = dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003132 if (len == 0) {
3133 PyErr_SetString(PyExc_ValueError,
3134 "Empty module name");
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003135 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003136 }
3137 }
Victor Stinner974389d2011-03-15 09:33:57 +01003138
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003139 /* name = inputname[:len] */
3140 name = PyUnicode_Substring(inputname, 0, len);
3141 if (name == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003142 goto error;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003143
3144 if (PyUnicode_GET_LENGTH(*p_prefix)) {
3145 /* fullname = prefix + "." + name */
3146 fullname = PyUnicode_FromFormat("%U.%U", *p_prefix, name);
3147 if (fullname == NULL)
3148 goto error;
3149 }
3150 else {
3151 fullname = name;
3152 Py_INCREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003154
Victor Stinner974389d2011-03-15 09:33:57 +01003155 result = import_submodule(mod, name, fullname);
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003156 Py_DECREF(*p_prefix);
3157 /* Transfer reference. */
3158 *p_prefix = fullname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 if (result == Py_None && altmod != mod) {
3160 Py_DECREF(result);
3161 /* Here, altmod must be None and mod must not be None */
Victor Stinner974389d2011-03-15 09:33:57 +01003162 result = import_submodule(altmod, name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 if (result != NULL && result != Py_None) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003164 if (mark_miss(*p_prefix) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003166 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 }
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003168 Py_DECREF(*p_prefix);
3169 *p_prefix = name;
3170 Py_INCREF(*p_prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 }
3172 }
3173 if (result == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003174 goto error;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 if (result == Py_None) {
3177 Py_DECREF(result);
3178 PyErr_Format(PyExc_ImportError,
Victor Stinner974389d2011-03-15 09:33:57 +01003179 "No module named %R", inputname);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003180 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003182
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003183 if (dot >= 0) {
3184 *p_outputname = PyUnicode_Substring(inputname, dot+1,
3185 PyUnicode_GET_LENGTH(inputname));
Victor Stinner974389d2011-03-15 09:33:57 +01003186 if (*p_outputname == NULL) {
3187 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003188 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003189 }
3190 }
3191
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003192 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 return result;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003194
3195error:
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003196 Py_XDECREF(name);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003197 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003198}
3199
3200static int
Victor Stinner974389d2011-03-15 09:33:57 +01003201mark_miss(PyObject *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003204 return PyDict_SetItem(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003205}
3206
3207static int
Victor Stinner974389d2011-03-15 09:33:57 +01003208ensure_fromlist(PyObject *mod, PyObject *fromlist, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 int i;
Victor Stinner974389d2011-03-15 09:33:57 +01003212 PyObject *fullname;
3213 Py_ssize_t fromlist_len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003214
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003215 if (!_PyObject_HasAttrId(mod, &PyId___path__))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003217
Victor Stinner974389d2011-03-15 09:33:57 +01003218 fromlist_len = PySequence_Size(fromlist);
3219
3220 for (i = 0; i < fromlist_len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 PyObject *item = PySequence_GetItem(fromlist, i);
3222 int hasit;
Victor Stinner974389d2011-03-15 09:33:57 +01003223 if (item == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 if (!PyUnicode_Check(item)) {
3226 PyErr_SetString(PyExc_TypeError,
3227 "Item in ``from list'' not a string");
3228 Py_DECREF(item);
3229 return 0;
3230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003231 if (PyUnicode_READ_CHAR(item, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 PyObject *all;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003233 _Py_IDENTIFIER(__all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 Py_DECREF(item);
3235 /* See if the package defines __all__ */
3236 if (recursive)
3237 continue; /* Avoid endless recursion */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003238 all = _PyObject_GetAttrId(mod, &PyId___all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 if (all == NULL)
3240 PyErr_Clear();
3241 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003242 int ret = ensure_fromlist(mod, all, name, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 Py_DECREF(all);
3244 if (!ret)
3245 return 0;
3246 }
3247 continue;
3248 }
3249 hasit = PyObject_HasAttr(mod, item);
3250 if (!hasit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 PyObject *submod;
Victor Stinner974389d2011-03-15 09:33:57 +01003252 fullname = PyUnicode_FromFormat("%U.%U", name, item);
3253 if (fullname != NULL) {
3254 submod = import_submodule(mod, item, fullname);
3255 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 }
Victor Stinner974389d2011-03-15 09:33:57 +01003257 else
3258 submod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 Py_XDECREF(submod);
3260 if (submod == NULL) {
3261 Py_DECREF(item);
3262 return 0;
3263 }
3264 }
3265 Py_DECREF(item);
3266 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003267
Victor Stinner974389d2011-03-15 09:33:57 +01003268 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003269}
3270
Neil Schemenauer00b09662003-06-16 21:03:07 +00003271static int
Victor Stinner974389d2011-03-15 09:33:57 +01003272add_submodule(PyObject *mod, PyObject *submod, PyObject *fullname,
3273 PyObject *subname, PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00003274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 if (mod == Py_None)
3276 return 1;
3277 /* Irrespective of the success of this load, make a
3278 reference to it in the parent package module. A copy gets
3279 saved in the modules dictionary under the full name, so get a
3280 reference from there, if need be. (The exception is when the
3281 load failed with a SyntaxError -- then there's no trace in
3282 sys.modules. In that case, of course, do nothing extra.) */
3283 if (submod == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003284 submod = PyDict_GetItem(modules, fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 if (submod == NULL)
3286 return 1;
3287 }
3288 if (PyModule_Check(mod)) {
3289 /* We can't use setattr here since it can give a
3290 * spurious warning if the submodule name shadows a
3291 * builtin name */
3292 PyObject *dict = PyModule_GetDict(mod);
3293 if (!dict)
3294 return 0;
Victor Stinner974389d2011-03-15 09:33:57 +01003295 if (PyDict_SetItem(dict, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return 0;
3297 }
3298 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003299 if (PyObject_SetAttr(mod, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 return 0;
3301 }
3302 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00003303}
3304
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003305static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003306import_submodule(PyObject *mod, PyObject *subname, PyObject *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003309 PyObject *m = NULL, *bufobj, *path_list, *loader;
Victor Stinner9599de52011-03-13 22:38:38 -04003310 struct filedescr *fdp;
3311 FILE *fp;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 /* Require:
3314 if mod == None: subname == fullname
3315 else: mod.__name__ + "." + subname == fullname
3316 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003317
Victor Stinner974389d2011-03-15 09:33:57 +01003318 if ((m = PyDict_GetItem(modules, fullname)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 Py_INCREF(m);
Victor Stinner9599de52011-03-13 22:38:38 -04003320 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 }
Victor Stinner9599de52011-03-13 22:38:38 -04003322
3323 if (mod == Py_None)
Victor Stinner533d7832011-03-14 13:22:54 -04003324 path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003326 path_list = _PyObject_GetAttrId(mod, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003327 if (path_list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 PyErr_Clear();
3329 Py_INCREF(Py_None);
3330 return Py_None;
3331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003333
Victor Stinner533d7832011-03-14 13:22:54 -04003334 fdp = find_module(fullname, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003335 &bufobj, &fp, &loader);
Victor Stinner533d7832011-03-14 13:22:54 -04003336 Py_XDECREF(path_list);
Victor Stinner9599de52011-03-13 22:38:38 -04003337 if (fdp == NULL) {
3338 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3339 return NULL;
3340 PyErr_Clear();
3341 Py_INCREF(Py_None);
3342 return Py_None;
3343 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003344 m = load_module(fullname, fp, bufobj, fdp->type, loader);
3345 Py_XDECREF(bufobj);
Victor Stinner9599de52011-03-13 22:38:38 -04003346 Py_XDECREF(loader);
3347 if (fp)
3348 fclose(fp);
3349 if (m == NULL)
3350 return NULL;
3351 if (!add_submodule(mod, m, fullname, subname, modules)) {
3352 Py_XDECREF(m);
3353 return NULL;
3354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003356}
3357
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003358
3359/* Re-import a module of any kind and return its module object, WITH
3360 INCREMENTED REFERENCE COUNT */
3361
Guido van Rossum79f25d91997-04-29 20:08:16 +00003362PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003363PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 PyInterpreterState *interp = PyThreadState_Get()->interp;
3366 PyObject *modules_reloading = interp->modules_reloading;
3367 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003368 PyObject *path_list = NULL, *loader = NULL, *existing_m = NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003369 PyObject *name, *bufobj, *subname;
3370 Py_ssize_t subname_start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 struct filedescr *fdp;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003372 FILE *fp = NULL;
3373 PyObject *newm = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 if (modules_reloading == NULL) {
3376 Py_FatalError("PyImport_ReloadModule: "
3377 "no modules_reloading dictionary!");
3378 return NULL;
3379 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 if (m == NULL || !PyModule_Check(m)) {
3382 PyErr_SetString(PyExc_TypeError,
3383 "reload() argument must be module");
3384 return NULL;
3385 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003386 name = PyModule_GetNameObject(m);
3387 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003389 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003391 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01003392 name);
3393 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 return NULL;
3395 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003396 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 if (existing_m != NULL) {
3398 /* Due to a recursive reload, this module is already
3399 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003400 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 Py_INCREF(existing_m);
3402 return existing_m;
3403 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003404 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
3405 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003407 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003408
Martin v. Löwis796ea532011-10-30 09:07:07 +01003409 subname_start = PyUnicode_FindChar(name, '.', 0,
3410 PyUnicode_GET_LENGTH(name), -1);
3411 if (subname_start == -1) {
3412 Py_INCREF(name);
3413 subname = name;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 else {
3416 PyObject *parentname, *parent;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003417 Py_ssize_t len;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003418 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003420 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 }
3422 parent = PyDict_GetItem(modules, parentname);
3423 if (parent == NULL) {
3424 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003425 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 parentname);
3427 Py_DECREF(parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003428 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 }
3430 Py_DECREF(parentname);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003431 path_list = _PyObject_GetAttrId(parent, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003432 if (path_list == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 PyErr_Clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003434 subname_start++;
3435 len = PyUnicode_GET_LENGTH(name) - (subname_start + 1);
3436 subname = PyUnicode_Substring(name, subname_start, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003438 if (subname == NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003439 goto error;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003440 fdp = find_module(name, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003441 &bufobj, &fp, &loader);
Martin v. Löwis796ea532011-10-30 09:07:07 +01003442 Py_DECREF(subname);
Victor Stinner533d7832011-03-14 13:22:54 -04003443 Py_XDECREF(path_list);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 if (fdp == NULL) {
3446 Py_XDECREF(loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003447 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003449
Martin v. Löwis796ea532011-10-30 09:07:07 +01003450 newm = load_module(name, fp, bufobj, fdp->type, loader);
Victor Stinner2fd76e42011-03-14 15:19:39 -04003451 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 if (fp)
3455 fclose(fp);
3456 if (newm == NULL) {
3457 /* load_module probably removed name from modules because of
3458 * the error. Put back the original module object. We're
3459 * going to return NULL in this case regardless of whether
3460 * replacing name succeeds, so the return value is ignored.
3461 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003462 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003464
3465error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003467 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003469}
3470
3471
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003472/* Higher-level import emulator which emulates the "import" statement
3473 more accurately -- it invokes the __import__() function from the
3474 builtins of the current globals. This means that the import is
3475 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003476 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003477 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003478 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003479 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003480
3481PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003482PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 static PyObject *silly_list = NULL;
3485 static PyObject *builtins_str = NULL;
3486 static PyObject *import_str = NULL;
3487 PyObject *globals = NULL;
3488 PyObject *import = NULL;
3489 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003490 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 /* Initialize constant string objects */
3494 if (silly_list == NULL) {
3495 import_str = PyUnicode_InternFromString("__import__");
3496 if (import_str == NULL)
3497 return NULL;
3498 builtins_str = PyUnicode_InternFromString("__builtins__");
3499 if (builtins_str == NULL)
3500 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003501 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 if (silly_list == NULL)
3503 return NULL;
3504 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 /* Get the builtins from current globals */
3507 globals = PyEval_GetGlobals();
3508 if (globals != NULL) {
3509 Py_INCREF(globals);
3510 builtins = PyObject_GetItem(globals, builtins_str);
3511 if (builtins == NULL)
3512 goto err;
3513 }
3514 else {
3515 /* No globals -- use standard builtins, and fake globals */
3516 builtins = PyImport_ImportModuleLevel("builtins",
3517 NULL, NULL, NULL, 0);
3518 if (builtins == NULL)
3519 return NULL;
3520 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3521 if (globals == NULL)
3522 goto err;
3523 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 /* Get the __import__ function from the builtins */
3526 if (PyDict_Check(builtins)) {
3527 import = PyObject_GetItem(builtins, import_str);
3528 if (import == NULL)
3529 PyErr_SetObject(PyExc_KeyError, import_str);
3530 }
3531 else
3532 import = PyObject_GetAttr(builtins, import_str);
3533 if (import == NULL)
3534 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003537 Always use absolute import here.
3538 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3540 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003541 if (r == NULL)
3542 goto err;
3543 Py_DECREF(r);
3544
3545 modules = PyImport_GetModuleDict();
3546 r = PyDict_GetItem(modules, module_name);
3547 if (r != NULL)
3548 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003549
3550 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 Py_XDECREF(globals);
3552 Py_XDECREF(builtins);
3553 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003556}
3557
3558
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003559/* Module 'imp' provides Python access to the primitives used for
3560 importing modules.
3561*/
3562
Guido van Rossum79f25d91997-04-29 20:08:16 +00003563static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003564imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 buf[0] = (char) ((magic >> 0) & 0xff);
3569 buf[1] = (char) ((magic >> 8) & 0xff);
3570 buf[2] = (char) ((magic >> 16) & 0xff);
3571 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003574}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003575
3576static PyObject *
3577imp_get_magic(PyObject *self, PyObject *noargs)
3578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003580}
3581
3582static PyObject *
3583imp_get_tag(PyObject *self, PyObject *noargs)
3584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003586}
3587
Guido van Rossum79f25d91997-04-29 20:08:16 +00003588static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003589imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 PyObject *list;
3592 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 list = PyList_New(0);
3595 if (list == NULL)
3596 return NULL;
3597 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3598 PyObject *item = Py_BuildValue("ssi",
3599 fdp->suffix, fdp->mode, fdp->type);
3600 if (item == NULL) {
3601 Py_DECREF(list);
3602 return NULL;
3603 }
3604 if (PyList_Append(list, item) < 0) {
3605 Py_DECREF(list);
3606 Py_DECREF(item);
3607 return NULL;
3608 }
3609 Py_DECREF(item);
3610 }
3611 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003612}
3613
Guido van Rossum79f25d91997-04-29 20:08:16 +00003614static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003615call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 extern int fclose(FILE *);
3618 PyObject *fob, *ret;
3619 PyObject *pathobj;
3620 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003621 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 int fd = -1;
3623 char *found_encoding = NULL;
3624 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003625
Victor Stinner533d7832011-03-14 13:22:54 -04003626 if (path_list == Py_None)
3627 path_list = NULL;
3628 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003629 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 if (fdp == NULL)
3631 return NULL;
3632 if (fp != NULL) {
3633 fd = fileno(fp);
3634 if (fd != -1)
3635 fd = dup(fd);
3636 fclose(fp);
Victor Stinnerd417d012011-06-20 15:16:55 +02003637 if (fd == -1) {
3638 PyErr_SetFromErrno(PyExc_OSError);
3639 return NULL;
3640 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 fp = NULL;
3642 }
3643 if (fd != -1) {
3644 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003645 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003647 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003649 if (found_encoding == NULL && PyErr_Occurred()) {
3650 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 encoding = (found_encoding != NULL) ? found_encoding :
3654 (char*)PyUnicode_GetDefaultEncoding();
3655 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003656 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 (char*)encoding, NULL, NULL, 1);
3658 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003659 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 close(fd);
3661 PyMem_FREE(found_encoding);
3662 return NULL;
3663 }
3664 }
3665 else {
3666 fob = Py_None;
3667 Py_INCREF(fob);
3668 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003669 if (pathobj == NULL) {
3670 Py_INCREF(Py_None);
3671 pathobj = Py_None;
3672 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 ret = Py_BuildValue("NN(ssi)",
3674 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3675 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003678}
3679
Guido van Rossum79f25d91997-04-29 20:08:16 +00003680static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003681imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003682{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003683 PyObject *name, *path_list = NULL;
3684 if (!PyArg_ParseTuple(args, "U|O:find_module",
3685 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003687 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003688}
3689
3690static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003691imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003692{
Victor Stinner95872862011-03-07 18:20:56 +01003693 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 int ret;
3695 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003696 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 return NULL;
3698 ret = init_builtin(name);
3699 if (ret < 0)
3700 return NULL;
3701 if (ret == 0) {
3702 Py_INCREF(Py_None);
3703 return Py_None;
3704 }
Victor Stinner95872862011-03-07 18:20:56 +01003705 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 Py_XINCREF(m);
3707 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003708}
3709
Guido van Rossum79f25d91997-04-29 20:08:16 +00003710static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003711imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003712{
Victor Stinner53dc7352011-03-20 01:50:21 +01003713 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 int ret;
3715 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003716 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003718 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (ret < 0)
3720 return NULL;
3721 if (ret == 0) {
3722 Py_INCREF(Py_None);
3723 return Py_None;
3724 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003725 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 Py_XINCREF(m);
3727 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003728}
3729
Guido van Rossum79f25d91997-04-29 20:08:16 +00003730static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003731imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003732{
Victor Stinner53dc7352011-03-20 01:50:21 +01003733 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003734
Victor Stinner53dc7352011-03-20 01:50:21 +01003735 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 return NULL;
3737 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003738}
3739
Guido van Rossum79f25d91997-04-29 20:08:16 +00003740static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003741imp_is_frozen_package(PyObject *self, PyObject *args)
3742{
Victor Stinner53dc7352011-03-20 01:50:21 +01003743 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003744
Victor Stinner53dc7352011-03-20 01:50:21 +01003745 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 return NULL;
3747 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003748}
3749
3750static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003751imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003752{
Victor Stinner95872862011-03-07 18:20:56 +01003753 PyObject *name;
3754 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 return NULL;
3756 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003757}
3758
Guido van Rossum79f25d91997-04-29 20:08:16 +00003759static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003760imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003761{
Victor Stinner53dc7352011-03-20 01:50:21 +01003762 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003764 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 return NULL;
3766 p = find_frozen(name);
3767 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003768}
3769
3770static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003771get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 FILE *fp;
3774 if (mode[0] == 'U')
3775 mode = "r" PY_STDIOTEXTMODE;
3776 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003777 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003778 if (!fp) {
3779 if (!PyErr_Occurred())
3780 PyErr_SetFromErrno(PyExc_IOError);
3781 return NULL;
3782 }
3783 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 }
3785 else {
3786 int fd = PyObject_AsFileDescriptor(fob);
3787 if (fd == -1)
3788 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01003789 if (!_PyVerify_fd(fd)) {
3790 PyErr_SetFromErrno(PyExc_IOError);
3791 return NULL;
3792 }
3793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 /* the FILE struct gets a new fd, so that it can be closed
3795 * independently of the file descriptor given
3796 */
3797 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01003798 if (fd == -1) {
3799 PyErr_SetFromErrno(PyExc_IOError);
3800 return NULL;
3801 }
3802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003804 if (!fp) {
3805 PyErr_SetFromErrno(PyExc_IOError);
3806 return NULL;
3807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003809 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003810}
3811
Guido van Rossum79f25d91997-04-29 20:08:16 +00003812static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003813imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003814{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003815 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 PyObject *fob = NULL;
3817 PyObject *m;
3818 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003819 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003821 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 &fob))
3823 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003824 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003826 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 return NULL;
3828 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003829 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003831 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003833}
3834
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003835#ifdef HAVE_DYNAMIC_LOADING
3836
Guido van Rossum79f25d91997-04-29 20:08:16 +00003837static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003838imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003839{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003840 PyObject *name, *pathname, *fob = NULL, *mod;
3841 FILE *fp;
3842
3843 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3844 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003846 if (fob != NULL) {
3847 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003848 if (fp == NULL) {
3849 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003853 else
3854 fp = NULL;
3855 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003856 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 if (fp)
3858 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003859 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003860}
3861
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003862#endif /* HAVE_DYNAMIC_LOADING */
3863
Guido van Rossum79f25d91997-04-29 20:08:16 +00003864static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003865imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003866{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003867 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 PyObject *fob = NULL;
3869 PyObject *m;
3870 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003871 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003873 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 &fob))
3875 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003876 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003878 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 return NULL;
3880 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003881 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003882 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 fclose(fp);
3884 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003885}
3886
Guido van Rossum79f25d91997-04-29 20:08:16 +00003887static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003888imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003889{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003890 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 char *suffix; /* Unused */
3892 char *mode;
3893 int type;
3894 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003895
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003896 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3897 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003899 if (pathname_obj != Py_None) {
3900 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3901 return NULL;
3902 }
3903 else
3904 pathname = NULL;
3905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 if (*mode) {
3907 /* Mode must start with 'r' or 'U' and must not contain '+'.
3908 Implicit in this test is the assumption that the mode
3909 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3912 PyErr_Format(PyExc_ValueError,
3913 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003914 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 return NULL;
3916 }
3917 }
3918 if (fob == Py_None)
3919 fp = NULL;
3920 else {
3921 fp = get_file(NULL, fob, mode);
3922 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003923 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 return NULL;
3925 }
3926 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003927 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003928 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 if (fp)
3930 fclose(fp);
3931 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003932}
3933
3934static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003935imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003936{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003937 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003939 if (!PyArg_ParseTuple(args, "UO&:load_package",
3940 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003942 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003943 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003945}
3946
3947static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003948imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003949{
Victor Stinnerfe19d212011-03-14 14:53:28 -04003950 PyObject *name;
3951 if (!PyArg_ParseTuple(args, "U:new_module", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 return NULL;
Victor Stinnerfe19d212011-03-14 14:53:28 -04003953 return PyModule_NewObject(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003954}
3955
Christian Heimes13a7a212008-01-07 17:13:09 +00003956static PyObject *
3957imp_reload(PyObject *self, PyObject *v)
3958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003960}
3961
3962PyDoc_STRVAR(doc_reload,
3963"reload(module) -> module\n\
3964\n\
3965Reload the module. The module must have been successfully imported before.");
3966
Barry Warsaw28a691b2010-04-17 00:19:56 +00003967static PyObject *
3968imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003971
Victor Stinner2f42ae52011-03-20 00:41:24 +01003972 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003973 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003977 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003978 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003980
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003981 if (debug_override != NULL &&
3982 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003983 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003984 return NULL;
3985 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003986
Martin v. Löwis30260a72011-10-23 17:35:46 +02003987 if (PyUnicode_READY(pathname) < 0)
3988 return NULL;
3989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003990 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003991 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 if (cpathname == NULL) {
3994 PyErr_Format(PyExc_SystemError, "path buffer too short");
3995 return NULL;
3996 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003997 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003998}
3999
4000PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01004001"cache_from_source(path, [debug_override]) -> path\n\
4002Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004003\n\
4004The .py file does not need to exist; this simply returns the path to the\n\
4005.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
4006will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
4007\n\
4008If debug_override is not None, then it must be a boolean and is taken as\n\
4009the value of __debug__ instead.");
4010
4011static PyObject *
4012imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
4013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04004015 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00004018 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04004019 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004021
Victor Stinnerc9abda02011-03-14 13:33:46 -04004022 source = make_source_pathname(pathname);
4023 if (source == NULL) {
4024 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04004026 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 return NULL;
4028 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04004029 Py_DECREF(pathname);
4030 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004031}
4032
4033PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01004034"source_from_cache(path) -> path\n\
4035Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004036\n\
4037The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
4038the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
4039does not conform to PEP 3147 format, ValueError will be raised.");
4040
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004041/* Doc strings */
4042
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004043PyDoc_STRVAR(doc_imp,
4044"This module provides the components needed to build your own\n\
4045__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004047PyDoc_STRVAR(doc_find_module,
4048"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004049Search for a module. If path is omitted or None, search for a\n\
4050built-in, frozen or special module and continue search in sys.path.\n\
4051The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004052package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004054PyDoc_STRVAR(doc_load_module,
4055"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004056Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004057The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004059PyDoc_STRVAR(doc_get_magic,
4060"get_magic() -> string\n\
4061Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004062
Barry Warsaw28a691b2010-04-17 00:19:56 +00004063PyDoc_STRVAR(doc_get_tag,
4064"get_tag() -> string\n\
4065Return the magic tag for .pyc or .pyo files.");
4066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004067PyDoc_STRVAR(doc_get_suffixes,
4068"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004069Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004070that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004072PyDoc_STRVAR(doc_new_module,
4073"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004074Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004075The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004077PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00004078"lock_held() -> boolean\n\
4079Return True if the import lock is currently held, else False.\n\
4080On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00004081
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004082PyDoc_STRVAR(doc_acquire_lock,
4083"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00004084Acquires the interpreter's import lock for the current thread.\n\
4085This lock should be used by import hooks to ensure thread-safety\n\
4086when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004087On platforms without threads, this function does nothing.");
4088
4089PyDoc_STRVAR(doc_release_lock,
4090"release_lock() -> None\n\
4091Release the interpreter's import lock.\n\
4092On platforms without threads, this function does nothing.");
4093
Guido van Rossum79f25d91997-04-29 20:08:16 +00004094static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
4096 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
4097 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
4098 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
4099 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
4100 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
4101 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
4102 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
4103 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
4104 {"reload", imp_reload, METH_O, doc_reload},
4105 {"cache_from_source", (PyCFunction)imp_cache_from_source,
4106 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
4107 {"source_from_cache", (PyCFunction)imp_source_from_cache,
4108 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
4109 /* The rest are obsolete */
4110 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
4111 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
4112 {"init_builtin", imp_init_builtin, METH_VARARGS},
4113 {"init_frozen", imp_init_frozen, METH_VARARGS},
4114 {"is_builtin", imp_is_builtin, METH_VARARGS},
4115 {"is_frozen", imp_is_frozen, METH_VARARGS},
4116 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004117#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004119#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 {"load_package", imp_load_package, METH_VARARGS},
4121 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07004122 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004124};
4125
Guido van Rossum1a8791e1998-08-04 22:46:29 +00004126static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004127setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 PyObject *v;
4130 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 v = PyLong_FromLong((long)value);
4133 err = PyDict_SetItemString(d, name, v);
4134 Py_XDECREF(v);
4135 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004136}
4137
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004138typedef struct {
4139 PyObject_HEAD
4140} NullImporter;
4141
4142static int
4143NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
4144{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004145#ifndef MS_WINDOWS
4146 PyObject *path;
4147 struct stat statbuf;
4148 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4151 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004152
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004153 if (!PyArg_ParseTuple(args, "O&:NullImporter",
4154 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004156
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004157 if (PyBytes_GET_SIZE(path) == 0) {
4158 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 PyErr_SetString(PyExc_ImportError, "empty pathname");
4160 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004162
4163 rv = stat(PyBytes_AS_STRING(path), &statbuf);
4164 Py_DECREF(path);
4165 if (rv == 0) {
4166 /* it exists */
4167 if (S_ISDIR(statbuf.st_mode)) {
4168 /* it's a directory */
4169 PyErr_SetString(PyExc_ImportError, "existing directory");
4170 return -1;
4171 }
4172 }
4173#else /* MS_WINDOWS */
4174 PyObject *pathobj;
4175 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00004176 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004177
4178 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4179 return -1;
4180
4181 if (!PyArg_ParseTuple(args, "U:NullImporter",
4182 &pathobj))
4183 return -1;
4184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004185 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004186 PyErr_SetString(PyExc_ImportError, "empty pathname");
4187 return -1;
4188 }
4189
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00004190 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004191 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004192 return -1;
4193 /* see issue1293 and issue3677:
4194 * stat() on Windows doesn't recognise paths like
4195 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
4196 */
4197 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004198 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004199 if (rv != INVALID_FILE_ATTRIBUTES) {
4200 /* it exists */
4201 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
4202 /* it's a directory */
4203 PyErr_SetString(PyExc_ImportError, "existing directory");
4204 return -1;
4205 }
4206 }
4207#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004209}
4210
4211static PyObject *
4212NullImporter_find_module(NullImporter *self, PyObject *args)
4213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004215}
4216
4217static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
4219 "Always return None"
4220 },
4221 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004222};
4223
4224
Christian Heimes9cd17752007-11-18 19:35:23 +00004225PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 PyVarObject_HEAD_INIT(NULL, 0)
4227 "imp.NullImporter", /*tp_name*/
4228 sizeof(NullImporter), /*tp_basicsize*/
4229 0, /*tp_itemsize*/
4230 0, /*tp_dealloc*/
4231 0, /*tp_print*/
4232 0, /*tp_getattr*/
4233 0, /*tp_setattr*/
4234 0, /*tp_reserved*/
4235 0, /*tp_repr*/
4236 0, /*tp_as_number*/
4237 0, /*tp_as_sequence*/
4238 0, /*tp_as_mapping*/
4239 0, /*tp_hash */
4240 0, /*tp_call*/
4241 0, /*tp_str*/
4242 0, /*tp_getattro*/
4243 0, /*tp_setattro*/
4244 0, /*tp_as_buffer*/
4245 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4246 "Null importer object", /* tp_doc */
4247 0, /* tp_traverse */
4248 0, /* tp_clear */
4249 0, /* tp_richcompare */
4250 0, /* tp_weaklistoffset */
4251 0, /* tp_iter */
4252 0, /* tp_iternext */
4253 NullImporter_methods, /* tp_methods */
4254 0, /* tp_members */
4255 0, /* tp_getset */
4256 0, /* tp_base */
4257 0, /* tp_dict */
4258 0, /* tp_descr_get */
4259 0, /* tp_descr_set */
4260 0, /* tp_dictoffset */
4261 (initproc)NullImporter_init, /* tp_init */
4262 0, /* tp_alloc */
4263 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004264};
4265
Martin v. Löwis1a214512008-06-11 05:26:20 +00004266static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 PyModuleDef_HEAD_INIT,
4268 "imp",
4269 doc_imp,
4270 0,
4271 imp_methods,
4272 NULL,
4273 NULL,
4274 NULL,
4275 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004276};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004277
Jason Tishler6bc06ec2003-09-04 11:59:50 +00004278PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004279PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 if (PyType_Ready(&PyNullImporter_Type) < 0)
4284 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 m = PyModule_Create(&impmodule);
4287 if (m == NULL)
4288 goto failure;
4289 d = PyModule_GetDict(m);
4290 if (d == NULL)
4291 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
4294 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
4295 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
4296 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
4297 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
4298 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
4299 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4300 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4301 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4302 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 Py_INCREF(&PyNullImporter_Type);
4305 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4306 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004307 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 Py_XDECREF(m);
4309 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004310}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004311
4312
Guido van Rossumb18618d2000-05-03 23:44:39 +00004313/* API for embedding applications that want to add their own entries
4314 to the table of built-in modules. This should normally be called
4315 *before* Py_Initialize(). When the table resize fails, -1 is
4316 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004317
4318 After a similar function by Just van Rossum. */
4319
4320int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004321PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 static struct _inittab *our_copy = NULL;
4324 struct _inittab *p;
4325 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 /* Count the number of entries in both tables */
4328 for (n = 0; newtab[n].name != NULL; n++)
4329 ;
4330 if (n == 0)
4331 return 0; /* Nothing to do */
4332 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4333 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 /* Allocate new memory for the combined table */
4336 p = our_copy;
4337 PyMem_RESIZE(p, struct _inittab, i+n+1);
4338 if (p == NULL)
4339 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 /* Copy the tables into the new memory */
4342 if (our_copy != PyImport_Inittab)
4343 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4344 PyImport_Inittab = our_copy = p;
4345 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004348}
4349
4350/* Shorthand to add a single entry given a name and a function */
4351
4352int
Brett Cannona826f322009-04-02 03:41:46 +00004353PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 newtab[0].name = (char *)name;
4360 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004363}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004364
4365#ifdef __cplusplus
4366}
4367#endif