blob: 4efc36923a30c968f052573f2344406f53aa6ebf [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 Pitrou5136ac02012-01-13 18:52:16 +01001346 /* Now write the true mtime and size */
Antoine Pitrou707033a2011-10-17 19:28:44 +02001347 fseek(fp, 4L, 0);
1348 assert(mtime < LONG_MAX);
1349 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 }
Fred Drake4c82b232000-06-30 16:18:57 +00001479#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 /* Python's .pyc timestamp handling presumes that the timestamp fits
1481 in 4 bytes. This will be fine until sometime in the year 2038,
1482 when a 4-byte signed time_t will overflow.
1483 */
1484 if (st.st_mtime >> 32) {
1485 PyErr_SetString(PyExc_OverflowError,
1486 "modification time overflows a 4 byte field");
Victor Stinner2f42ae52011-03-20 00:41:24 +01001487 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 }
Fred Drake4c82b232000-06-30 16:18:57 +00001489#endif
Martin v. Löwis30260a72011-10-23 17:35:46 +02001490 if (PyUnicode_READY(pathname) < 0)
1491 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001492 cpathname = make_compiled_pathname(pathname, !Py_OptimizeFlag);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001493
1494 if (cpathname != NULL)
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001495 fpc = check_compiled_module(pathname, &st, cpathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001496 else
1497 fpc = NULL;
1498
1499 if (fpc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 co = read_compiled_module(cpathname, fpc);
1501 fclose(fpc);
1502 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001503 goto error;
1504 update_compiled_module(co, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001506 PySys_FormatStderr("import %U # precompiled from %R\n",
1507 name, cpathname);
1508 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1509 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 }
1511 else {
1512 co = parse_source_module(pathname, fp);
1513 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001514 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001516 PySys_FormatStderr("import %U # from %R\n",
Victor Stinner98dbba52011-03-14 15:15:47 -04001517 name, pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001518 if (cpathname != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1520 if (ro == NULL || !PyObject_IsTrue(ro))
1521 write_compiled_module(co, cpathname, &st);
1522 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001523 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1524 pathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001527
Victor Stinner2f42ae52011-03-20 00:41:24 +01001528error:
1529 Py_XDECREF(cpathbytes);
1530 Py_XDECREF(cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001532}
1533
Christian Heimes3b06e532008-01-07 20:12:44 +00001534/* Get source file -> unicode or None
1535 * Returns the path to the py file if available, else the given path
1536 */
1537static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001538get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001541 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001542 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001544 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001546 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001547 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001549
Victor Stinnerc9abda02011-03-14 13:33:46 -04001550 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001551 fileuni = PyUnicode_AsUCS4Copy(filename);
1552 if (!fileuni)
1553 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001554 if (len < 5
1555 || fileuni[len-4] != '.'
1556 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1557 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1558 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* Start by trying to turn PEP 3147 path into source path. If that
1561 * fails, just chop off the trailing character, i.e. legacy pyc path
1562 * to py.
1563 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001564 py = make_source_pathname(filename);
1565 if (py == NULL) {
1566 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001567 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001569 if (py == NULL)
1570 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001571
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001572 err = _Py_stat(py, &statbuf);
1573 if (err == -2)
1574 goto error;
1575 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001576 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001577 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001578 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001579 Py_DECREF(py);
1580 goto unchanged;
1581
1582error:
1583 PyErr_Clear();
1584unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001586 Py_INCREF(filename);
1587 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001588}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001589
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001590/* Forward */
Victor Stinner41c5fec2011-03-13 21:46:30 -04001591static PyObject *load_module(PyObject *, FILE *, PyObject *, int, PyObject *);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001592static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001593 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001594static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001595
1596/* Load a package and return its module object WITH INCREMENTED
1597 REFERENCE COUNT */
1598
1599static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001600load_package(PyObject *name, PyObject *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001601{
Victor Stinner41c5fec2011-03-13 21:46:30 -04001602 PyObject *m, *d, *bufobj;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001603 PyObject *file = NULL, *path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 int err;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001605 FILE *fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001607
Victor Stinnerc9abda02011-03-14 13:33:46 -04001608 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (m == NULL)
1610 return NULL;
1611 if (Py_VerboseFlag)
Victor Stinner98dbba52011-03-14 15:15:47 -04001612 PySys_FormatStderr("import %U # directory %R\n",
1613 name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 file = get_sourcefile(pathname);
1615 if (file == NULL)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001616 return NULL;
1617 path_list = Py_BuildValue("[O]", file);
1618 if (path_list == NULL) {
1619 Py_DECREF(file);
1620 return NULL;
1621 }
1622 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 err = PyDict_SetItemString(d, "__file__", file);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001624 Py_DECREF(file);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (err == 0)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001626 err = PyDict_SetItemString(d, "__path__", path_list);
1627 if (err != 0) {
1628 Py_DECREF(path_list);
1629 return NULL;
1630 }
Victor Stinner533d7832011-03-14 13:22:54 -04001631 fdp = find_module(name, initstr, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001632 &bufobj, &fp, NULL);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001633 Py_DECREF(path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (fdp == NULL) {
1635 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1636 PyErr_Clear();
1637 Py_INCREF(m);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001638 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 }
1640 else
Victor Stinnerc9abda02011-03-14 13:33:46 -04001641 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001643 m = load_module(name, fp, bufobj, fdp->type, NULL);
1644 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (fp != NULL)
1646 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001648}
1649
1650
1651/* Helper to test for built-in module */
1652
1653static int
Victor Stinner95872862011-03-07 18:20:56 +01001654is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001655{
Victor Stinner95872862011-03-07 18:20:56 +01001656 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001658 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1659 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (PyImport_Inittab[i].initfunc == NULL)
1661 return -1;
1662 else
1663 return 1;
1664 }
1665 }
1666 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001667}
1668
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001669
Just van Rossum52e14d62002-12-30 22:08:05 +00001670/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1671 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001672 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001673 that can handle the path item. Return None if no hook could;
1674 this tells our caller it should fall back to the builtin
1675 import mechanism. Cache the result in path_importer_cache.
1676 Returns a borrowed reference. */
1677
1678static PyObject *
1679get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PyObject *importer;
1683 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 /* These conditions are the caller's responsibility: */
1686 assert(PyList_Check(path_hooks));
1687 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 nhooks = PyList_Size(path_hooks);
1690 if (nhooks < 0)
1691 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 importer = PyDict_GetItem(path_importer_cache, p);
1694 if (importer != NULL)
1695 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 /* set path_importer_cache[p] to None to avoid recursion */
1698 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1699 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 for (j = 0; j < nhooks; j++) {
1702 PyObject *hook = PyList_GetItem(path_hooks, j);
1703 if (hook == NULL)
1704 return NULL;
1705 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1706 if (importer != NULL)
1707 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1710 return NULL;
1711 }
1712 PyErr_Clear();
1713 }
1714 if (importer == NULL) {
1715 importer = PyObject_CallFunctionObjArgs(
1716 (PyObject *)&PyNullImporter_Type, p, NULL
1717 );
1718 if (importer == NULL) {
1719 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1720 PyErr_Clear();
1721 return Py_None;
1722 }
1723 }
1724 }
1725 if (importer != NULL) {
1726 int err = PyDict_SetItem(path_importer_cache, p, importer);
1727 Py_DECREF(importer);
1728 if (err != 0)
1729 return NULL;
1730 }
1731 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001732}
1733
Christian Heimes9cd17752007-11-18 19:35:23 +00001734PyAPI_FUNC(PyObject *)
1735PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1739 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1740 importer = get_path_importer(path_importer_cache,
1741 path_hooks, path);
1742 }
1743 }
1744 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1745 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001746}
1747
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001748/* Search the path (default sys.path) for a module. Return the
1749 corresponding filedescr struct, and (via return arguments) the
1750 pathname and an open file. Return NULL if the module is not found. */
1751
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001752#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001753extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1754 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001755#endif
1756
Victor Stinner547a2a62011-03-20 03:07:28 +01001757/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001758static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001759static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001760static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001761
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001762/* Get the path of a module: get its importer and call importer.find_module()
1763 hook, or check if the module if a package (if path/__init__.py exists).
1764
1765 -1: error: a Python error occurred
1766 0: ignore: an error occurred because of invalid data, but the error is not
1767 important enough to be reported.
1768 1: get path: module not found, but *buf contains its path
1769 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1770 and *buf is the path */
1771
1772static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001773find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001774 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001775 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001776{
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001777 PyObject *path_unicode, *filename = NULL;
1778 Py_ssize_t len, pos;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001779 struct stat statbuf;
1780 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001781 int err, result, addsep;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001782
1783 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001784 Py_INCREF(path);
1785 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001786 }
1787 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001788 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1789 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1790 if (path_unicode == NULL)
1791 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001792 }
1793 else
1794 return 0;
1795
Victor Stinner46084ba2011-10-06 02:39:42 +02001796 if (PyUnicode_READY(path_unicode))
1797 return -1;
1798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001799 len = PyUnicode_GET_LENGTH(path_unicode);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001800 if (PyUnicode_FindChar(path_unicode, 0, 0, len, 1) != -1) {
1801 result = 0;
1802 goto out; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001803 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001804
1805 /* sys.path_hooks import hook */
1806 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001807 _Py_IDENTIFIER(find_module);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001808 PyObject *importer;
1809
1810 importer = get_path_importer(path_importer_cache,
1811 path_hooks, path);
1812 if (importer == NULL) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001813 result = -1;
1814 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001815 }
1816 /* Note: importer is a borrowed reference */
1817 if (importer != Py_None) {
1818 PyObject *loader;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001819 loader = _PyObject_CallMethodId(importer,
1820 &PyId_find_module, "O", fullname);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001821 if (loader == NULL) {
1822 result = -1; /* error */
1823 goto out;
1824 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001825 if (loader != Py_None) {
1826 /* a loader was found */
1827 *p_loader = loader;
1828 *p_fd = &importhookdescr;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001829 result = 2;
1830 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001831 }
1832 Py_DECREF(loader);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001833 result = 0;
1834 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001835 }
1836 }
1837 /* no hook was found, use builtin import */
1838
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001839 addsep = 0;
1840 if (len > 0 && PyUnicode_READ_CHAR(path_unicode, len-1) != SEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001841#ifdef ALTSEP
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001842 && PyUnicode_READ_CHAR(path_unicode, len-1) != ALTSEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001843#endif
1844 )
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001845 addsep = 1;
1846 filename = PyUnicode_New(len + PyUnicode_GET_LENGTH(name) + addsep,
1847 Py_MAX(PyUnicode_MAX_CHAR_VALUE(path_unicode),
1848 PyUnicode_MAX_CHAR_VALUE(name)));
1849 if (filename == NULL) {
1850 result = -1;
1851 goto out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001852 }
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001853 PyUnicode_CopyCharacters(filename, 0, path_unicode, 0, len);
1854 pos = len;
1855 if (addsep)
Victor Stinner1f795172011-11-17 00:45:54 +01001856 PyUnicode_WRITE(PyUnicode_KIND(filename),
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001857 PyUnicode_DATA(filename),
1858 pos++, SEP);
Victor Stinner1f795172011-11-17 00:45:54 +01001859 PyUnicode_CopyCharacters(filename, pos, name, 0,
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001860 PyUnicode_GET_LENGTH(name));
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001861
1862 /* Check for package import (buf holds a directory name,
1863 and there's an __init__ module in that directory */
1864#ifdef HAVE_STAT
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001865 err = _Py_stat(filename, &statbuf);
1866 if (err == -2) {
1867 result = -1;
1868 goto out;
1869 }
1870 if (err == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001871 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1872 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001873 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001874
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001875 match = case_ok(filename, 0, name);
1876 if (match < 0) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001877 result = -1;
1878 goto out;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001879 }
1880 if (match) { /* case matches */
1881 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001882 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001883 filename = NULL;
Victor Stinnerd0296212011-03-14 14:04:10 -04001884 *p_fd = &fd_package;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001885 result = 2;
1886 goto out;
Victor Stinnerd0296212011-03-14 14:04:10 -04001887 }
1888 else {
1889 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001890 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001891 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001892 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001893 if (err) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001894 result = -1;
1895 goto out;
Victor Stinner547a2a62011-03-20 03:07:28 +01001896 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001897 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001898 }
1899 }
1900#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001901 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001902 filename = NULL;
1903 result = 1;
1904 out:
1905 Py_DECREF(path_unicode);
1906 Py_XDECREF(filename);
1907 return result;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001908}
1909
1910/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001911 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001912
1913 If the module is found, return a file descriptor, write the path in
1914 *p_filename, write the pointer to the file object into *p_fp, and (if
1915 p_loader is not NULL) the loader into *p_loader.
1916
1917 Otherwise, raise an exception and return NULL. */
1918
Victor Stinner37580282011-03-20 01:34:43 +01001919static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001920find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001921 PyObject *search_path_list, PyObject *path_hooks,
1922 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001923 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 struct filedescr *fdp = NULL;
1927 char *filemode;
1928 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001929 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001930 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001931 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001932
Victor Stinner37580282011-03-20 01:34:43 +01001933 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001935 PyObject *path;
1936 int ok;
1937
1938 path = PyList_GetItem(search_path_list, i);
1939 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001941
Victor Stinner2fd76e42011-03-14 15:19:39 -04001942 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001943 ok = find_module_path(fullname, name, path,
1944 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001945 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001946 if (ok < 0)
1947 return NULL;
1948 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001950 if (ok == 2) {
1951 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001952 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001953 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001956 struct stat statbuf;
1957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 filemode = fdp->mode;
1959 if (filemode[0] == 'U')
1960 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001961
Victor Stinner2fd76e42011-03-14 15:19:39 -04001962 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1963 if (filename == NULL) {
1964 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001965 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001966 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001967
1968 if (Py_VerboseFlag > 1)
1969 PySys_FormatStderr("# trying %R\n", filename);
1970
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001971 err = _Py_stat(filename, &statbuf);
1972 if (err == -2) {
1973 Py_DECREF(prefix);
1974 Py_DECREF(filename);
1975 return NULL;
1976 }
1977 if (err != 0 || S_ISDIR(statbuf.st_mode)) {
Charles-François Natali1659b832011-12-07 23:17:58 +01001978 /* it doesn't exist, or it's a directory */
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001979 Py_DECREF(filename);
1980 continue;
1981 }
1982
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001983 fp = _Py_fopen(filename, filemode);
1984 if (fp == NULL) {
1985 Py_DECREF(filename);
Victor Stinner925ef392011-06-20 15:01:10 +02001986 if (PyErr_Occurred()) {
1987 Py_DECREF(prefix);
1988 return NULL;
1989 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001990 continue;
1991 }
1992 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
1993 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001994 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001995 Py_DECREF(filename);
1996 return NULL;
1997 }
1998 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001999 Py_DECREF(prefix);
2000 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04002001 *p_fp = fp;
2002 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002004 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04002005
2006 fclose(fp);
2007 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002009 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 }
Victor Stinnerd0296212011-03-14 14:04:10 -04002011 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002012 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04002013 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002014}
2015
Victor Stinner37580282011-03-20 01:34:43 +01002016/* Find a module:
2017
2018 - try find_module() of each sys.meta_path hook
2019 - try find_frozen()
2020 - try is_builtin()
2021 - try _PyWin_FindRegisteredModule() (Windows only)
2022 - otherwise, call find_module_path_list() with search_path_list (if not
2023 NULL) or sys.path
2024
Victor Stinner2fd76e42011-03-14 15:19:39 -04002025 fullname can be NULL, but only if p_loader is NULL.
2026
Victor Stinner37580282011-03-20 01:34:43 +01002027 Return:
2028
2029 - &fd_builtin (C_BUILTIN) if it is a builtin
2030 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04002031 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01002032 if it is a package
2033 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
2034 importer loader was found
2035 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
2036 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04002037 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01002038 - NULL on error
2039
Victor Stinner2fd76e42011-03-14 15:19:39 -04002040 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
2041 Eg. *p_path is set to NULL for a builtin package.
2042*/
Victor Stinner37580282011-03-20 01:34:43 +01002043
2044static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002045find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002046 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01002047{
2048 Py_ssize_t i, npath;
2049 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
2050 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
2051 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01002052
Victor Stinner2fd76e42011-03-14 15:19:39 -04002053 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01002054 *p_fp = NULL;
2055 if (p_loader != NULL)
2056 *p_loader = NULL;
2057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058 if (PyUnicode_GET_LENGTH(name) > MAXPATHLEN) {
2059 PyErr_SetString(PyExc_OverflowError,
2060 "module name is too long");
2061 return NULL;
2062 }
2063
Victor Stinner37580282011-03-20 01:34:43 +01002064 /* sys.meta_path import hook */
2065 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002066 _Py_IDENTIFIER(find_module);
Victor Stinner37580282011-03-20 01:34:43 +01002067 PyObject *meta_path;
2068
2069 meta_path = PySys_GetObject("meta_path");
2070 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02002071 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002072 "sys.meta_path must be a list of "
2073 "import hooks");
2074 return NULL;
2075 }
2076 Py_INCREF(meta_path); /* zap guard */
2077 npath = PyList_Size(meta_path);
2078 for (i = 0; i < npath; i++) {
2079 PyObject *loader;
2080 PyObject *hook = PyList_GetItem(meta_path, i);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002081 loader = _PyObject_CallMethodId(hook, &PyId_find_module,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002082 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01002083 search_path_list != NULL ?
2084 search_path_list : Py_None);
2085 if (loader == NULL) {
2086 Py_DECREF(meta_path);
2087 return NULL; /* true error */
2088 }
2089 if (loader != Py_None) {
2090 /* a loader was found */
2091 *p_loader = loader;
2092 Py_DECREF(meta_path);
2093 return &importhookdescr;
2094 }
2095 Py_DECREF(loader);
2096 }
2097 Py_DECREF(meta_path);
2098 }
2099
Victor Stinnerdf75a022011-03-14 13:40:04 -04002100 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002101 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01002102
2103 if (search_path_list == NULL) {
2104#ifdef MS_COREDLL
2105 FILE *fp;
2106 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01002107#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04002108 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01002109 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01002110#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04002111 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01002112 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01002113 *p_fp = fp;
2114 return fdp;
2115 }
2116 else if (PyErr_Occurred())
2117 return NULL;
2118#endif
Victor Stinner37580282011-03-20 01:34:43 +01002119 search_path_list = PySys_GetObject("path");
2120 }
2121
2122 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
Victor Stinner16191322011-09-15 19:28:05 +02002123 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002124 "sys.path must be a list of directory names");
2125 return NULL;
2126 }
2127
2128 path_hooks = PySys_GetObject("path_hooks");
2129 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02002130 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002131 "sys.path_hooks must be a list of "
2132 "import hooks");
2133 return NULL;
2134 }
2135 path_importer_cache = PySys_GetObject("path_importer_cache");
2136 if (path_importer_cache == NULL ||
2137 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02002138 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002139 "sys.path_importer_cache must be a dict");
2140 return NULL;
2141 }
2142
2143 return find_module_path_list(fullname, name,
2144 search_path_list, path_hooks,
2145 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002146 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01002147}
2148
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002149/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00002150 * The arguments here are tricky, best shown by example:
2151 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2152 * ^ ^ ^ ^
2153 * |--------------------- buf ---------------------|
2154 * |------------------- len ------------------|
2155 * |------ name -------|
2156 * |----- namelen -----|
2157 * buf is the full path, but len only counts up to (& exclusive of) the
2158 * extension. name is the module name, also exclusive of extension.
2159 *
2160 * We've already done a successful stat() or fopen() on buf, so know that
2161 * there's some match, possibly case-insensitive.
2162 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002163 * case_bytes() is to return 1 if there's a case-sensitive match for
2164 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00002165 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00002166 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002167 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00002168 * on platforms with case-insensitive filesystems. It's trivial to implement
2169 * for case-sensitive filesystems. It's pretty much a cross-platform
2170 * nightmare for systems with case-insensitive filesystems.
2171 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00002172
Tim Peters50d8d372001-02-28 05:34:27 +00002173/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002174 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00002175 */
Jason Tishler7961aa62005-05-20 00:56:54 +00002176#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002177#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00002178
Tim Peters50d8d372001-02-28 05:34:27 +00002179#elif defined(DJGPP)
2180#include <dir.h>
2181
Jason Tishler7961aa62005-05-20 00:56:54 +00002182#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00002183#include <sys/types.h>
2184#include <dirent.h>
2185
Andrew MacIntyred9400542002-02-26 11:41:34 +00002186#elif defined(PYOS_OS2)
2187#define INCL_DOS
2188#define INCL_DOSERRORS
2189#define INCL_NOPMAPI
2190#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00002191#endif
2192
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002193#if defined(DJGPP) \
2194 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
2195 && defined(HAVE_DIRENT_H)) \
2196 || defined(PYOS_OS2)
2197# define USE_CASE_OK_BYTES
2198#endif
2199
2200
2201#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00002202static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002203case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002204{
Tim Peters50d8d372001-02-28 05:34:27 +00002205/* Pick a platform-specific implementation; the sequence of #if's here should
2206 * match the sequence just above.
2207 */
2208
Tim Peters50d8d372001-02-28 05:34:27 +00002209/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002210#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 struct ffblk ffblk;
2212 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (Py_GETENV("PYTHONCASEOK") != NULL)
2215 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2218 if (done) {
2219 PyErr_Format(PyExc_NameError,
2220 "Can't find file for module %.100s\n(filename %.300s)",
2221 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01002222 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 }
2224 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002225
Jason Tishler7961aa62005-05-20 00:56:54 +00002226/* new-fangled macintosh (macosx) or Cygwin */
2227#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 DIR *dirp;
2229 struct dirent *dp;
2230 char dirname[MAXPATHLEN + 1];
2231 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (Py_GETENV("PYTHONCASEOK") != NULL)
2234 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* Copy the dir component into dirname; substitute "." if empty */
2237 if (dirlen <= 0) {
2238 dirname[0] = '.';
2239 dirname[1] = '\0';
2240 }
2241 else {
2242 assert(dirlen <= MAXPATHLEN);
2243 memcpy(dirname, buf, dirlen);
2244 dirname[dirlen] = '\0';
2245 }
2246 /* Open the directory and search the entries for an exact match. */
2247 dirp = opendir(dirname);
2248 if (dirp) {
2249 char *nameWithExt = buf + len - namelen;
2250 while ((dp = readdir(dirp)) != NULL) {
2251 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002252#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002254#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002256#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (thislen >= namelen &&
2258 strcmp(dp->d_name, nameWithExt) == 0) {
2259 (void)closedir(dirp);
2260 return 1; /* Found */
2261 }
2262 }
2263 (void)closedir(dirp);
2264 }
2265 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002266
Andrew MacIntyred9400542002-02-26 11:41:34 +00002267/* OS/2 */
2268#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 HDIR hdir = 1;
2270 ULONG srchcnt = 1;
2271 FILEFINDBUF3 ffbuf;
2272 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (Py_GETENV("PYTHONCASEOK") != NULL)
2275 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 rc = DosFindFirst(buf,
2278 &hdir,
2279 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2280 &ffbuf, sizeof(ffbuf),
2281 &srchcnt,
2282 FIL_STANDARD);
2283 if (rc != NO_ERROR)
2284 return 0;
2285 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002286
Tim Peters50d8d372001-02-28 05:34:27 +00002287/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2288#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002289# error "USE_CASE_OK_BYTES is not correctly defined"
2290#endif
2291}
2292#endif
2293
2294/*
2295 * Check if a filename case matchs the name case. We've already done a
2296 * successful stat() or fopen() on buf, so know that there's some match,
2297 * possibly case-insensitive.
2298 *
2299 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
2300 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
2301 * if envar PYTHONCASEOK exists.
2302 *
2303 * case_ok() is used to implement case-sensitive import semantics even
2304 * on platforms with case-insensitive filesystems. It's trivial to implement
2305 * for case-sensitive filesystems. It's pretty much a cross-platform
2306 * nightmare for systems with case-insensitive filesystems.
2307 */
2308
2309static int
2310case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
2311{
2312#ifdef MS_WINDOWS
2313 WIN32_FIND_DATAW data;
2314 HANDLE h;
2315 int cmp;
Victor Stinner1f795172011-11-17 00:45:54 +01002316 wchar_t *wfilename, *wname;
Victor Stinner8c981892011-10-11 22:27:13 +02002317 Py_ssize_t wname_len;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002318
2319 if (Py_GETENV("PYTHONCASEOK") != NULL)
2320 return 1;
2321
Victor Stinner1f795172011-11-17 00:45:54 +01002322 wfilename = PyUnicode_AsUnicode(filename);
2323 if (wfilename == NULL)
2324 return -1;
2325
2326 h = FindFirstFileW(wfilename, &data);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002327 if (h == INVALID_HANDLE_VALUE) {
2328 PyErr_Format(PyExc_NameError,
2329 "Can't find file for module %R\n(filename %R)",
2330 name, filename);
Victor Stinner1f795172011-11-17 00:45:54 +01002331 return -1;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002332 }
2333 FindClose(h);
Victor Stinnerbeac78b2011-10-11 21:55:01 +02002334
2335 wname = PyUnicode_AsUnicodeAndSize(name, &wname_len);
2336 if (wname == NULL)
2337 return -1;
2338
2339 cmp = wcsncmp(data.cFileName, wname, wname_len);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002340 return cmp == 0;
2341#elif defined(USE_CASE_OK_BYTES)
2342 int match;
2343 PyObject *filebytes, *namebytes;
2344 filebytes = PyUnicode_EncodeFSDefault(filename);
2345 if (filebytes == NULL)
2346 return -1;
2347 namebytes = PyUnicode_EncodeFSDefault(name);
2348 if (namebytes == NULL) {
2349 Py_DECREF(filebytes);
2350 return -1;
2351 }
2352 match = case_bytes(
2353 PyBytes_AS_STRING(filebytes),
2354 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01002355 PyBytes_GET_SIZE(namebytes),
2356 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002357 Py_DECREF(filebytes);
2358 Py_DECREF(namebytes);
2359 return match;
2360#else
2361 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002363
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002364#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002365}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002366
Guido van Rossum197346f1997-10-31 18:38:52 +00002367#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002368
Victor Stinner547a2a62011-03-20 03:07:28 +01002369/* Helper to look for __init__.py or __init__.py[co] in potential package.
2370 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00002371static int
Victor Stinner547a2a62011-03-20 03:07:28 +01002372find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01002375 PyObject *filename;
2376 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002377 int err;
Guido van Rossum197346f1997-10-31 18:38:52 +00002378
Victor Stinner547a2a62011-03-20 03:07:28 +01002379 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
2380 if (filename == NULL)
2381 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002382 err = _Py_stat(filename, &statbuf);
2383 if (err == -2)
2384 return -1;
2385 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002386 /* 3=len(".py") */
2387 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002388 if (match < 0) {
2389 Py_DECREF(filename);
2390 return -1;
2391 }
2392 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002393 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return 1;
2395 }
2396 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002397 Py_DECREF(filename);
2398
2399 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
2400 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
2401 if (filename == NULL)
2402 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002403 err = _Py_stat(filename, &statbuf);
2404 if (err == -2) {
2405 Py_DECREF(filename);
2406 return -1;
2407 }
2408 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002409 /* 4=len(".pyc") */
2410 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002411 if (match < 0) {
2412 Py_DECREF(filename);
2413 return -1;
2414 }
2415 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002416 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 return 1;
2418 }
2419 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002420 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002422}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002423
Guido van Rossum197346f1997-10-31 18:38:52 +00002424#endif /* HAVE_STAT */
2425
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002426
Victor Stinner95872862011-03-07 18:20:56 +01002427static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002428
Victor Stinner44c6c152010-08-09 00:59:10 +00002429static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002430load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002431{
2432 PyObject *m, *modules;
2433 int err;
2434
Victor Stinner44c6c152010-08-09 00:59:10 +00002435 if (type == C_BUILTIN)
2436 err = init_builtin(name);
2437 else
Victor Stinner95872862011-03-07 18:20:56 +01002438 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002439 if (err < 0)
2440 return NULL;
2441 if (err == 0) {
2442 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002443 "Purported %s module %R not found",
2444 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002445 name);
2446 return NULL;
2447 }
2448
2449 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002450 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002451 if (m == NULL) {
2452 PyErr_Format(
2453 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002454 "%s module %R not properly initialized",
2455 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002456 name);
2457 return NULL;
2458 }
2459 Py_INCREF(m);
2460 return m;
2461}
2462
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002463/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002464 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002465
Guido van Rossum79f25d91997-04-29 20:08:16 +00002466static PyObject *
Victor Stinner41c5fec2011-03-13 21:46:30 -04002467load_module(PyObject *name, FILE *fp, PyObject *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 /* First check that there's an open file (if we need one) */
2472 switch (type) {
2473 case PY_SOURCE:
2474 case PY_COMPILED:
2475 if (fp == NULL) {
2476 PyErr_Format(PyExc_ValueError,
Victor Stinner41c5fec2011-03-13 21:46:30 -04002477 "file object required for import (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 type);
2479 return NULL;
2480 }
2481 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002484
Victor Stinner41c5fec2011-03-13 21:46:30 -04002485 case PY_SOURCE:
2486 m = load_source_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002488
Victor Stinner41c5fec2011-03-13 21:46:30 -04002489 case PY_COMPILED:
2490 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002492
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002493#ifdef HAVE_DYNAMIC_LOADING
Victor Stinner41c5fec2011-03-13 21:46:30 -04002494 case C_EXTENSION:
2495 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002497#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002498
Victor Stinner41c5fec2011-03-13 21:46:30 -04002499 case PKG_DIRECTORY:
2500 m = load_package(name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 case C_BUILTIN:
Victor Stinner41c5fec2011-03-13 21:46:30 -04002504 case PY_FROZEN:
2505 m = load_builtin(name, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 case IMP_HOOK: {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002509 _Py_IDENTIFIER(load_module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (loader == NULL) {
2511 PyErr_SetString(PyExc_ImportError,
2512 "import hook without loader");
2513 return NULL;
2514 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002515 m = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 break;
2517 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 default:
2520 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002521 "Don't know how to import %R (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 name, type);
2523 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002528}
2529
2530
2531/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002532 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002533 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002534
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002535static int
Victor Stinner95872862011-03-07 18:20:56 +01002536init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002539
Victor Stinner95872862011-03-07 18:20:56 +01002540 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 for (p = PyImport_Inittab; p->name != NULL; p++) {
2544 PyObject *mod;
Victor Stinner95872862011-03-07 18:20:56 +01002545 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (p->initfunc == NULL) {
2547 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002548 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 name);
2550 return -1;
2551 }
2552 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002553 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 mod = (*p->initfunc)();
2555 if (mod == 0)
2556 return -1;
Victor Stinner95872862011-03-07 18:20:56 +01002557 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return -1;
2559 /* FixupExtension has put the module into sys.modules,
2560 so we can release our own reference. */
2561 Py_DECREF(mod);
2562 return 1;
2563 }
2564 }
2565 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002566}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002567
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002568
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002569/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002570
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002571static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002572find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002575
Victor Stinner53dc7352011-03-20 01:50:21 +01002576 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 for (p = PyImport_FrozenModules; ; p++) {
2580 if (p->name == NULL)
2581 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002582 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 break;
2584 }
2585 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002586}
2587
Guido van Rossum79f25d91997-04-29 20:08:16 +00002588static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002589get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 struct _frozen *p = find_frozen(name);
2592 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 if (p == NULL) {
2595 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002596 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 name);
2598 return NULL;
2599 }
2600 if (p->code == NULL) {
2601 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002602 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 name);
2604 return NULL;
2605 }
2606 size = p->size;
2607 if (size < 0)
2608 size = -size;
2609 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002610}
2611
Brett Cannon8d110132009-03-15 02:20:16 +00002612static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002613is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 struct _frozen *p = find_frozen(name);
2616 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 if (p == NULL) {
2619 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002620 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 name);
2622 return NULL;
2623 }
Brett Cannon8d110132009-03-15 02:20:16 +00002624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (size < 0)
2628 Py_RETURN_TRUE;
2629 else
2630 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002631}
2632
2633
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002634/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002635 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002636 an exception set if the initialization failed.
2637 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002638
2639int
Victor Stinner53dc7352011-03-20 01:50:21 +01002640PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002641{
Victor Stinner53dc7352011-03-20 01:50:21 +01002642 struct _frozen *p;
2643 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 int ispackage;
2645 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002646
Victor Stinner53dc7352011-03-20 01:50:21 +01002647 p = find_frozen(name);
2648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (p == NULL)
2650 return 0;
2651 if (p->code == NULL) {
2652 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002653 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 name);
2655 return -1;
2656 }
2657 size = p->size;
2658 ispackage = (size < 0);
2659 if (ispackage)
2660 size = -size;
2661 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002662 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 name, ispackage ? " package" : "");
2664 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2665 if (co == NULL)
2666 return -1;
2667 if (!PyCode_Check(co)) {
2668 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002669 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 name);
2671 goto err_return;
2672 }
2673 if (ispackage) {
2674 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002675 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002677 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 if (m == NULL)
2679 goto err_return;
2680 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 l = PyList_New(1);
2682 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 goto err_return;
2684 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002685 Py_INCREF(name);
2686 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 err = PyDict_SetItemString(d, "__path__", l);
2688 Py_DECREF(l);
2689 if (err != 0)
2690 goto err_return;
2691 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002692 path = PyUnicode_FromString("<frozen>");
2693 if (path == NULL)
2694 goto err_return;
2695 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2696 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (m == NULL)
2698 goto err_return;
2699 Py_DECREF(co);
2700 Py_DECREF(m);
2701 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002702err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 Py_DECREF(co);
2704 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002705}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002706
Victor Stinner53dc7352011-03-20 01:50:21 +01002707int
2708PyImport_ImportFrozenModule(char *name)
2709{
2710 PyObject *nameobj;
2711 int ret;
2712 nameobj = PyUnicode_InternFromString(name);
2713 if (nameobj == NULL)
2714 return -1;
2715 ret = PyImport_ImportFrozenModuleObject(nameobj);
2716 Py_DECREF(nameobj);
2717 return ret;
2718}
2719
Guido van Rossum74e6a111994-08-29 12:54:38 +00002720
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002721/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002722 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002723
Guido van Rossum79f25d91997-04-29 20:08:16 +00002724PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002725PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 PyObject *pname;
2728 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 pname = PyUnicode_FromString(name);
2731 if (pname == NULL)
2732 return NULL;
2733 result = PyImport_Import(pname);
2734 Py_DECREF(pname);
2735 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002736}
2737
Christian Heimes072c0f12008-01-03 23:01:04 +00002738/* Import a module without blocking
2739 *
2740 * At first it tries to fetch the module from sys.modules. If the module was
2741 * never loaded before it loads it with PyImport_ImportModule() unless another
2742 * thread holds the import lock. In the latter case the function raises an
2743 * ImportError instead of blocking.
2744 *
2745 * Returns the module object with incremented ref count.
2746 */
2747PyObject *
2748PyImport_ImportModuleNoBlock(const char *name)
2749{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002750 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002751#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002753#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 /* Try to get the module from sys.modules[name] */
2756 modules = PyImport_GetModuleDict();
2757 if (modules == NULL)
2758 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002759
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002760 nameobj = PyUnicode_FromString(name);
2761 if (nameobj == NULL)
2762 return NULL;
2763 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002765 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 Py_INCREF(result);
2767 return result;
2768 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002769 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002770#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* check the import lock
2772 * me might be -1 but I ignore the error here, the lock function
2773 * takes care of the problem */
2774 me = PyThread_get_thread_ident();
2775 if (import_lock_thread == -1 || import_lock_thread == me) {
2776 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002777 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 }
2779 else {
2780 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002781 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002783 nameobj);
2784 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002786#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002787 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002788#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002789 Py_DECREF(nameobj);
2790 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002791}
2792
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002793/* Forward declarations for helper routines */
Victor Stinner974389d2011-03-15 09:33:57 +01002794static PyObject *get_parent(PyObject *globals,
2795 PyObject **p_name,
2796 int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002797static PyObject *load_next(PyObject *mod, PyObject *altmod,
Victor Stinner974389d2011-03-15 09:33:57 +01002798 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002799 PyObject **p_prefix);
Victor Stinner974389d2011-03-15 09:33:57 +01002800static int mark_miss(PyObject *name);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002801static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Victor Stinner974389d2011-03-15 09:33:57 +01002802 PyObject *buf, int recursive);
2803static PyObject * import_submodule(PyObject *mod, PyObject *name,
2804 PyObject *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002805
2806/* The Magnum Opus of dotted-name import :-) */
2807
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002808static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01002809import_module_level(PyObject *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002811{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002812 PyObject *parent, *next, *inputname, *outputname;
2813 PyObject *head = NULL;
2814 PyObject *tail = NULL;
2815 PyObject *prefix = NULL;
2816 PyObject *result = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002817 Py_ssize_t sep, altsep;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002819 if (PyUnicode_READY(name))
2820 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002821
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002822 sep = PyUnicode_FindChar(name, SEP, 0, PyUnicode_GET_LENGTH(name), 1);
2823 if (sep == -2)
2824 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002825#ifdef ALTSEP
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002826 altsep = PyUnicode_FindChar(name, ALTSEP, 0, PyUnicode_GET_LENGTH(name), 1);
2827 if (altsep == -2)
2828 return NULL;
2829#else
2830 altsep = -1;
Christian Heimes454f37b2008-01-10 00:10:02 +00002831#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002832 if (sep != -1 || altsep != -1)
2833 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 PyErr_SetString(PyExc_ImportError,
2835 "Import by filename is not supported.");
2836 return NULL;
2837 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002838
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002839 parent = get_parent(globals, &prefix, level);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002840 if (parent == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002842 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002843
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002844 if (PyUnicode_READY(prefix))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002845 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002846
2847 head = load_next(parent, level < 0 ? Py_None : parent, name, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002848 &prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 if (head == NULL)
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002850 goto out;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 tail = head;
2853 Py_INCREF(tail);
Victor Stinner974389d2011-03-15 09:33:57 +01002854
2855 if (outputname != NULL) {
2856 while (1) {
2857 inputname = outputname;
2858 next = load_next(tail, tail, inputname, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002859 &prefix);
2860 Py_CLEAR(tail);
2861 Py_CLEAR(inputname);
2862 if (next == NULL)
2863 goto out;
Victor Stinner974389d2011-03-15 09:33:57 +01002864 tail = next;
2865
2866 if (outputname == NULL) {
2867 break;
2868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 }
2871 if (tail == Py_None) {
2872 /* If tail is Py_None, both get_parent and load_next found
2873 an empty module name: someone called __import__("") or
2874 doctored faulty bytecode */
Victor Stinner974389d2011-03-15 09:33:57 +01002875 PyErr_SetString(PyExc_ValueError, "Empty module name");
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002876 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 if (fromlist != NULL) {
2880 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2881 fromlist = NULL;
2882 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 if (fromlist == NULL) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002885 result = head;
2886 Py_INCREF(result);
2887 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002889
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002890 if (!ensure_fromlist(tail, fromlist, prefix, 0))
2891 goto out;
Victor Stinner1f795172011-11-17 00:45:54 +01002892
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002893 result = tail;
2894 Py_INCREF(result);
2895 out:
2896 Py_XDECREF(head);
2897 Py_XDECREF(tail);
2898 Py_XDECREF(prefix);
2899 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002900}
2901
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002902PyObject *
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002903PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2904 PyObject *locals, PyObject *fromlist,
2905 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002906{
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002907 PyObject *mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 _PyImport_AcquireLock();
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002909 mod = import_module_level(name, globals, locals, fromlist, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 if (_PyImport_ReleaseLock() < 0) {
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002911 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 PyErr_SetString(PyExc_RuntimeError,
2913 "not holding the import lock");
2914 return NULL;
2915 }
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002916 return mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002917}
2918
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002919PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002920PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002921 PyObject *fromlist, int level)
2922{
2923 PyObject *nameobj, *mod;
2924 nameobj = PyUnicode_FromString(name);
2925 if (nameobj == NULL)
2926 return NULL;
2927 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2928 fromlist, level);
2929 Py_DECREF(nameobj);
2930 return mod;
2931}
2932
2933
Fred Drake87590902004-05-28 20:21:36 +00002934/* Return the package that an import is being performed in. If globals comes
2935 from the module foo.bar.bat (not itself a package), this returns the
2936 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002937 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002938
Victor Stinner974389d2011-03-15 09:33:57 +01002939 The name of the returned package is returned in *p_name.
Fred Drake87590902004-05-28 20:21:36 +00002940
2941 If globals doesn't come from a package or a module in a package, or a
2942 corresponding entry is not found in sys.modules, Py_None is returned.
2943*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002944static PyObject *
Victor Stinner9599de52011-03-13 22:38:38 -04002945get_parent(PyObject *globals, PyObject **p_name, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002946{
Victor Stinner974389d2011-03-15 09:33:57 +01002947 PyObject *nameobj;
2948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 static PyObject *namestr = NULL;
2950 static PyObject *pathstr = NULL;
2951 static PyObject *pkgstr = NULL;
2952 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2953 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 if (globals == NULL || !PyDict_Check(globals) || !level)
Victor Stinner974389d2011-03-15 09:33:57 +01002956 goto return_none;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 if (namestr == NULL) {
2959 namestr = PyUnicode_InternFromString("__name__");
2960 if (namestr == NULL)
2961 return NULL;
2962 }
2963 if (pathstr == NULL) {
2964 pathstr = PyUnicode_InternFromString("__path__");
2965 if (pathstr == NULL)
2966 return NULL;
2967 }
2968 if (pkgstr == NULL) {
2969 pkgstr = PyUnicode_InternFromString("__package__");
2970 if (pkgstr == NULL)
2971 return NULL;
2972 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 if ((pkgname != NULL) && (pkgname != Py_None)) {
2977 /* __package__ is set, so use it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 if (!PyUnicode_Check(pkgname)) {
2979 PyErr_SetString(PyExc_ValueError,
2980 "__package__ set to non-string");
2981 return NULL;
2982 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002983 if (PyUnicode_GET_LENGTH(pkgname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 if (level > 0) {
2985 PyErr_SetString(PyExc_ValueError,
2986 "Attempted relative import in non-package");
2987 return NULL;
2988 }
Victor Stinner974389d2011-03-15 09:33:57 +01002989 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002991 Py_INCREF(pkgname);
2992 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 } else {
2994 /* __package__ not set, so figure it out and set it */
2995 modname = PyDict_GetItem(globals, namestr);
2996 if (modname == NULL || !PyUnicode_Check(modname))
Victor Stinner974389d2011-03-15 09:33:57 +01002997 goto return_none;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 modpath = PyDict_GetItem(globals, pathstr);
3000 if (modpath != NULL) {
3001 /* __path__ is set, so modname is already the package name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 error = PyDict_SetItem(globals, pkgstr, modname);
3005 if (error) {
3006 PyErr_SetString(PyExc_ValueError,
3007 "Could not set __package__");
3008 return NULL;
3009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003010 Py_INCREF(modname);
3011 nameobj = modname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 } else {
3013 /* Normal module, so work out the package name if any */
Victor Stinner974389d2011-03-15 09:33:57 +01003014 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003015 len = PyUnicode_FindChar(modname, '.',
3016 0, PyUnicode_GET_LENGTH(modname), -1);
3017 if (len == -2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003019 if (len < 0) {
3020 if (level > 0) {
3021 PyErr_SetString(PyExc_ValueError,
3022 "Attempted relative import in non-package");
3023 return NULL;
3024 }
3025 if (PyDict_SetItem(globals, pkgstr, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 PyErr_SetString(PyExc_ValueError,
3027 "Could not set __package__");
3028 return NULL;
3029 }
Victor Stinner974389d2011-03-15 09:33:57 +01003030 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003032 pkgname = PyUnicode_Substring(modname, 0, len);
3033 if (pkgname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003035 if (PyDict_SetItem(globals, pkgstr, pkgname)) {
3036 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 PyErr_SetString(PyExc_ValueError,
3038 "Could not set __package__");
3039 return NULL;
3040 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003041 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 }
3043 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003044 if (level > 1) {
3045 Py_ssize_t dot, end = PyUnicode_GET_LENGTH(nameobj);
3046 PyObject *newname;
3047 while (--level > 0) {
3048 dot = PyUnicode_FindChar(nameobj, '.', 0, end, -1);
3049 if (dot == -2) {
3050 Py_DECREF(nameobj);
3051 return NULL;
3052 }
3053 if (dot < 0) {
3054 Py_DECREF(nameobj);
3055 PyErr_SetString(PyExc_ValueError,
3056 "Attempted relative import beyond "
3057 "toplevel package");
3058 return NULL;
3059 }
3060 end = dot;
3061 }
3062 newname = PyUnicode_Substring(nameobj, 0, end);
3063 Py_DECREF(nameobj);
3064 if (newname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003066 nameobj = newname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 }
Victor Stinner974389d2011-03-15 09:33:57 +01003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003070 parent = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 if (parent == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003072 int err;
3073
3074 if (orig_level >= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 PyErr_Format(PyExc_SystemError,
Victor Stinner974389d2011-03-15 09:33:57 +01003076 "Parent module %R not loaded, "
3077 "cannot perform relative import", nameobj);
3078 Py_DECREF(nameobj);
3079 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 }
Victor Stinner974389d2011-03-15 09:33:57 +01003081
3082 err = PyErr_WarnFormat(
3083 PyExc_RuntimeWarning, 1,
3084 "Parent module %R not found while handling absolute import",
3085 nameobj);
3086 Py_DECREF(nameobj);
3087 if (err)
3088 return NULL;
3089
3090 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 }
Victor Stinner974389d2011-03-15 09:33:57 +01003092 *p_name = nameobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 return parent;
3094 /* We expect, but can't guarantee, if parent != None, that:
Victor Stinner974389d2011-03-15 09:33:57 +01003095 - parent.__name__ == name
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 - parent.__dict__ is globals
3097 If this is violated... Who cares? */
Victor Stinner974389d2011-03-15 09:33:57 +01003098
3099return_none:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003100 nameobj = PyUnicode_New(0, 0);
Victor Stinner974389d2011-03-15 09:33:57 +01003101 if (nameobj == NULL)
3102 return NULL;
3103 *p_name = nameobj;
3104 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003105}
3106
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003107/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003108static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003109load_next(PyObject *mod, PyObject *altmod,
3110 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003111 PyObject **p_prefix)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003112{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003113 Py_ssize_t dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003114 Py_ssize_t len;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003115 PyObject *fullname, *name = NULL, *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003116
Victor Stinner974389d2011-03-15 09:33:57 +01003117 *p_outputname = NULL;
3118
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003119 len = PyUnicode_GET_LENGTH(inputname);
3120 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 /* completely empty module name should only happen in
3122 'from . import' (or '__import__("")')*/
3123 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 return mod;
3125 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003126
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003127
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003128 dot = PyUnicode_FindChar(inputname, '.', 0, len, 1);
3129 if (dot >= 0) {
3130 len = dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003131 if (len == 0) {
3132 PyErr_SetString(PyExc_ValueError,
3133 "Empty module name");
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003134 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003135 }
3136 }
Victor Stinner974389d2011-03-15 09:33:57 +01003137
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003138 /* name = inputname[:len] */
3139 name = PyUnicode_Substring(inputname, 0, len);
3140 if (name == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003141 goto error;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003142
3143 if (PyUnicode_GET_LENGTH(*p_prefix)) {
3144 /* fullname = prefix + "." + name */
3145 fullname = PyUnicode_FromFormat("%U.%U", *p_prefix, name);
3146 if (fullname == NULL)
3147 goto error;
3148 }
3149 else {
3150 fullname = name;
3151 Py_INCREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003153
Victor Stinner974389d2011-03-15 09:33:57 +01003154 result = import_submodule(mod, name, fullname);
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003155 Py_DECREF(*p_prefix);
3156 /* Transfer reference. */
3157 *p_prefix = fullname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 if (result == Py_None && altmod != mod) {
3159 Py_DECREF(result);
3160 /* Here, altmod must be None and mod must not be None */
Victor Stinner974389d2011-03-15 09:33:57 +01003161 result = import_submodule(altmod, name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 if (result != NULL && result != Py_None) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003163 if (mark_miss(*p_prefix) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003165 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 }
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003167 Py_DECREF(*p_prefix);
3168 *p_prefix = name;
3169 Py_INCREF(*p_prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 }
3171 }
3172 if (result == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003173 goto error;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 if (result == Py_None) {
3176 Py_DECREF(result);
3177 PyErr_Format(PyExc_ImportError,
Victor Stinner974389d2011-03-15 09:33:57 +01003178 "No module named %R", inputname);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003179 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003181
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003182 if (dot >= 0) {
3183 *p_outputname = PyUnicode_Substring(inputname, dot+1,
3184 PyUnicode_GET_LENGTH(inputname));
Victor Stinner974389d2011-03-15 09:33:57 +01003185 if (*p_outputname == NULL) {
3186 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003187 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003188 }
3189 }
3190
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003191 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 return result;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003193
3194error:
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003195 Py_XDECREF(name);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003196 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003197}
3198
3199static int
Victor Stinner974389d2011-03-15 09:33:57 +01003200mark_miss(PyObject *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003203 return PyDict_SetItem(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003204}
3205
3206static int
Victor Stinner974389d2011-03-15 09:33:57 +01003207ensure_fromlist(PyObject *mod, PyObject *fromlist, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 int i;
Victor Stinner974389d2011-03-15 09:33:57 +01003211 PyObject *fullname;
3212 Py_ssize_t fromlist_len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003213
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003214 if (!_PyObject_HasAttrId(mod, &PyId___path__))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003216
Victor Stinner974389d2011-03-15 09:33:57 +01003217 fromlist_len = PySequence_Size(fromlist);
3218
3219 for (i = 0; i < fromlist_len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 PyObject *item = PySequence_GetItem(fromlist, i);
3221 int hasit;
Victor Stinner974389d2011-03-15 09:33:57 +01003222 if (item == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 if (!PyUnicode_Check(item)) {
3225 PyErr_SetString(PyExc_TypeError,
3226 "Item in ``from list'' not a string");
3227 Py_DECREF(item);
3228 return 0;
3229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003230 if (PyUnicode_READ_CHAR(item, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 PyObject *all;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003232 _Py_IDENTIFIER(__all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 Py_DECREF(item);
3234 /* See if the package defines __all__ */
3235 if (recursive)
3236 continue; /* Avoid endless recursion */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003237 all = _PyObject_GetAttrId(mod, &PyId___all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 if (all == NULL)
3239 PyErr_Clear();
3240 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003241 int ret = ensure_fromlist(mod, all, name, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 Py_DECREF(all);
3243 if (!ret)
3244 return 0;
3245 }
3246 continue;
3247 }
3248 hasit = PyObject_HasAttr(mod, item);
3249 if (!hasit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 PyObject *submod;
Victor Stinner974389d2011-03-15 09:33:57 +01003251 fullname = PyUnicode_FromFormat("%U.%U", name, item);
3252 if (fullname != NULL) {
3253 submod = import_submodule(mod, item, fullname);
3254 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 }
Victor Stinner974389d2011-03-15 09:33:57 +01003256 else
3257 submod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 Py_XDECREF(submod);
3259 if (submod == NULL) {
3260 Py_DECREF(item);
3261 return 0;
3262 }
3263 }
3264 Py_DECREF(item);
3265 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003266
Victor Stinner974389d2011-03-15 09:33:57 +01003267 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003268}
3269
Neil Schemenauer00b09662003-06-16 21:03:07 +00003270static int
Victor Stinner974389d2011-03-15 09:33:57 +01003271add_submodule(PyObject *mod, PyObject *submod, PyObject *fullname,
3272 PyObject *subname, PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00003273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 if (mod == Py_None)
3275 return 1;
3276 /* Irrespective of the success of this load, make a
3277 reference to it in the parent package module. A copy gets
3278 saved in the modules dictionary under the full name, so get a
3279 reference from there, if need be. (The exception is when the
3280 load failed with a SyntaxError -- then there's no trace in
3281 sys.modules. In that case, of course, do nothing extra.) */
3282 if (submod == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003283 submod = PyDict_GetItem(modules, fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 if (submod == NULL)
3285 return 1;
3286 }
3287 if (PyModule_Check(mod)) {
3288 /* We can't use setattr here since it can give a
3289 * spurious warning if the submodule name shadows a
3290 * builtin name */
3291 PyObject *dict = PyModule_GetDict(mod);
3292 if (!dict)
3293 return 0;
Victor Stinner974389d2011-03-15 09:33:57 +01003294 if (PyDict_SetItem(dict, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 return 0;
3296 }
3297 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003298 if (PyObject_SetAttr(mod, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 return 0;
3300 }
3301 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00003302}
3303
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003304static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003305import_submodule(PyObject *mod, PyObject *subname, PyObject *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003308 PyObject *m = NULL, *bufobj, *path_list, *loader;
Victor Stinner9599de52011-03-13 22:38:38 -04003309 struct filedescr *fdp;
3310 FILE *fp;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 /* Require:
3313 if mod == None: subname == fullname
3314 else: mod.__name__ + "." + subname == fullname
3315 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003316
Victor Stinner974389d2011-03-15 09:33:57 +01003317 if ((m = PyDict_GetItem(modules, fullname)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 Py_INCREF(m);
Victor Stinner9599de52011-03-13 22:38:38 -04003319 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 }
Victor Stinner9599de52011-03-13 22:38:38 -04003321
3322 if (mod == Py_None)
Victor Stinner533d7832011-03-14 13:22:54 -04003323 path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003325 path_list = _PyObject_GetAttrId(mod, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003326 if (path_list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 PyErr_Clear();
3328 Py_INCREF(Py_None);
3329 return Py_None;
3330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003332
Victor Stinner533d7832011-03-14 13:22:54 -04003333 fdp = find_module(fullname, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003334 &bufobj, &fp, &loader);
Victor Stinner533d7832011-03-14 13:22:54 -04003335 Py_XDECREF(path_list);
Victor Stinner9599de52011-03-13 22:38:38 -04003336 if (fdp == NULL) {
3337 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3338 return NULL;
3339 PyErr_Clear();
3340 Py_INCREF(Py_None);
3341 return Py_None;
3342 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003343 m = load_module(fullname, fp, bufobj, fdp->type, loader);
3344 Py_XDECREF(bufobj);
Victor Stinner9599de52011-03-13 22:38:38 -04003345 Py_XDECREF(loader);
3346 if (fp)
3347 fclose(fp);
3348 if (m == NULL)
3349 return NULL;
3350 if (!add_submodule(mod, m, fullname, subname, modules)) {
3351 Py_XDECREF(m);
3352 return NULL;
3353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003355}
3356
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003357
3358/* Re-import a module of any kind and return its module object, WITH
3359 INCREMENTED REFERENCE COUNT */
3360
Guido van Rossum79f25d91997-04-29 20:08:16 +00003361PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003362PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 PyInterpreterState *interp = PyThreadState_Get()->interp;
3365 PyObject *modules_reloading = interp->modules_reloading;
3366 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003367 PyObject *path_list = NULL, *loader = NULL, *existing_m = NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003368 PyObject *name, *bufobj, *subname;
3369 Py_ssize_t subname_start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 struct filedescr *fdp;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003371 FILE *fp = NULL;
3372 PyObject *newm = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 if (modules_reloading == NULL) {
3375 Py_FatalError("PyImport_ReloadModule: "
3376 "no modules_reloading dictionary!");
3377 return NULL;
3378 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 if (m == NULL || !PyModule_Check(m)) {
3381 PyErr_SetString(PyExc_TypeError,
3382 "reload() argument must be module");
3383 return NULL;
3384 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003385 name = PyModule_GetNameObject(m);
3386 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003388 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003390 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01003391 name);
3392 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 return NULL;
3394 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003395 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 if (existing_m != NULL) {
3397 /* Due to a recursive reload, this module is already
3398 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003399 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 Py_INCREF(existing_m);
3401 return existing_m;
3402 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003403 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
3404 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003406 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003407
Martin v. Löwis796ea532011-10-30 09:07:07 +01003408 subname_start = PyUnicode_FindChar(name, '.', 0,
3409 PyUnicode_GET_LENGTH(name), -1);
3410 if (subname_start == -1) {
3411 Py_INCREF(name);
3412 subname = name;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 else {
3415 PyObject *parentname, *parent;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003416 Py_ssize_t len;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003417 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003419 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 }
3421 parent = PyDict_GetItem(modules, parentname);
3422 if (parent == NULL) {
3423 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003424 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 parentname);
3426 Py_DECREF(parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003427 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 }
3429 Py_DECREF(parentname);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003430 path_list = _PyObject_GetAttrId(parent, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003431 if (path_list == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 PyErr_Clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003433 subname_start++;
3434 len = PyUnicode_GET_LENGTH(name) - (subname_start + 1);
3435 subname = PyUnicode_Substring(name, subname_start, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003437 if (subname == NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003438 goto error;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003439 fdp = find_module(name, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003440 &bufobj, &fp, &loader);
Martin v. Löwis796ea532011-10-30 09:07:07 +01003441 Py_DECREF(subname);
Victor Stinner533d7832011-03-14 13:22:54 -04003442 Py_XDECREF(path_list);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (fdp == NULL) {
3445 Py_XDECREF(loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003446 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003448
Martin v. Löwis796ea532011-10-30 09:07:07 +01003449 newm = load_module(name, fp, bufobj, fdp->type, loader);
Victor Stinner2fd76e42011-03-14 15:19:39 -04003450 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 if (fp)
3454 fclose(fp);
3455 if (newm == NULL) {
3456 /* load_module probably removed name from modules because of
3457 * the error. Put back the original module object. We're
3458 * going to return NULL in this case regardless of whether
3459 * replacing name succeeds, so the return value is ignored.
3460 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003461 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003463
3464error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003466 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003468}
3469
3470
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003471/* Higher-level import emulator which emulates the "import" statement
3472 more accurately -- it invokes the __import__() function from the
3473 builtins of the current globals. This means that the import is
3474 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003475 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003476 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003477 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003478 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003479
3480PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003481PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 static PyObject *silly_list = NULL;
3484 static PyObject *builtins_str = NULL;
3485 static PyObject *import_str = NULL;
3486 PyObject *globals = NULL;
3487 PyObject *import = NULL;
3488 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003489 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 /* Initialize constant string objects */
3493 if (silly_list == NULL) {
3494 import_str = PyUnicode_InternFromString("__import__");
3495 if (import_str == NULL)
3496 return NULL;
3497 builtins_str = PyUnicode_InternFromString("__builtins__");
3498 if (builtins_str == NULL)
3499 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003500 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 if (silly_list == NULL)
3502 return NULL;
3503 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 /* Get the builtins from current globals */
3506 globals = PyEval_GetGlobals();
3507 if (globals != NULL) {
3508 Py_INCREF(globals);
3509 builtins = PyObject_GetItem(globals, builtins_str);
3510 if (builtins == NULL)
3511 goto err;
3512 }
3513 else {
3514 /* No globals -- use standard builtins, and fake globals */
3515 builtins = PyImport_ImportModuleLevel("builtins",
3516 NULL, NULL, NULL, 0);
3517 if (builtins == NULL)
3518 return NULL;
3519 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3520 if (globals == NULL)
3521 goto err;
3522 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 /* Get the __import__ function from the builtins */
3525 if (PyDict_Check(builtins)) {
3526 import = PyObject_GetItem(builtins, import_str);
3527 if (import == NULL)
3528 PyErr_SetObject(PyExc_KeyError, import_str);
3529 }
3530 else
3531 import = PyObject_GetAttr(builtins, import_str);
3532 if (import == NULL)
3533 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003536 Always use absolute import here.
3537 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3539 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003540 if (r == NULL)
3541 goto err;
3542 Py_DECREF(r);
3543
3544 modules = PyImport_GetModuleDict();
3545 r = PyDict_GetItem(modules, module_name);
3546 if (r != NULL)
3547 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003548
3549 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 Py_XDECREF(globals);
3551 Py_XDECREF(builtins);
3552 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003555}
3556
3557
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003558/* Module 'imp' provides Python access to the primitives used for
3559 importing modules.
3560*/
3561
Guido van Rossum79f25d91997-04-29 20:08:16 +00003562static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003563imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 buf[0] = (char) ((magic >> 0) & 0xff);
3568 buf[1] = (char) ((magic >> 8) & 0xff);
3569 buf[2] = (char) ((magic >> 16) & 0xff);
3570 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003573}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003574
3575static PyObject *
3576imp_get_magic(PyObject *self, PyObject *noargs)
3577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003579}
3580
3581static PyObject *
3582imp_get_tag(PyObject *self, PyObject *noargs)
3583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003585}
3586
Guido van Rossum79f25d91997-04-29 20:08:16 +00003587static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003588imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 PyObject *list;
3591 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 list = PyList_New(0);
3594 if (list == NULL)
3595 return NULL;
3596 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3597 PyObject *item = Py_BuildValue("ssi",
3598 fdp->suffix, fdp->mode, fdp->type);
3599 if (item == NULL) {
3600 Py_DECREF(list);
3601 return NULL;
3602 }
3603 if (PyList_Append(list, item) < 0) {
3604 Py_DECREF(list);
3605 Py_DECREF(item);
3606 return NULL;
3607 }
3608 Py_DECREF(item);
3609 }
3610 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003611}
3612
Guido van Rossum79f25d91997-04-29 20:08:16 +00003613static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003614call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 extern int fclose(FILE *);
3617 PyObject *fob, *ret;
3618 PyObject *pathobj;
3619 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003620 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 int fd = -1;
3622 char *found_encoding = NULL;
3623 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003624
Victor Stinner533d7832011-03-14 13:22:54 -04003625 if (path_list == Py_None)
3626 path_list = NULL;
3627 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003628 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 if (fdp == NULL)
3630 return NULL;
3631 if (fp != NULL) {
3632 fd = fileno(fp);
3633 if (fd != -1)
3634 fd = dup(fd);
3635 fclose(fp);
Victor Stinnerd417d012011-06-20 15:16:55 +02003636 if (fd == -1) {
3637 PyErr_SetFromErrno(PyExc_OSError);
3638 return NULL;
3639 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 fp = NULL;
3641 }
3642 if (fd != -1) {
3643 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003644 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003646 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003648 if (found_encoding == NULL && PyErr_Occurred()) {
3649 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 encoding = (found_encoding != NULL) ? found_encoding :
3653 (char*)PyUnicode_GetDefaultEncoding();
3654 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003655 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 (char*)encoding, NULL, NULL, 1);
3657 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003658 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 close(fd);
3660 PyMem_FREE(found_encoding);
3661 return NULL;
3662 }
3663 }
3664 else {
3665 fob = Py_None;
3666 Py_INCREF(fob);
3667 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003668 if (pathobj == NULL) {
3669 Py_INCREF(Py_None);
3670 pathobj = Py_None;
3671 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 ret = Py_BuildValue("NN(ssi)",
3673 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3674 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003677}
3678
Guido van Rossum79f25d91997-04-29 20:08:16 +00003679static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003680imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003681{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003682 PyObject *name, *path_list = NULL;
3683 if (!PyArg_ParseTuple(args, "U|O:find_module",
3684 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003686 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003687}
3688
3689static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003690imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003691{
Victor Stinner95872862011-03-07 18:20:56 +01003692 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 int ret;
3694 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003695 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 return NULL;
3697 ret = init_builtin(name);
3698 if (ret < 0)
3699 return NULL;
3700 if (ret == 0) {
3701 Py_INCREF(Py_None);
3702 return Py_None;
3703 }
Victor Stinner95872862011-03-07 18:20:56 +01003704 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 Py_XINCREF(m);
3706 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003707}
3708
Guido van Rossum79f25d91997-04-29 20:08:16 +00003709static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003710imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003711{
Victor Stinner53dc7352011-03-20 01:50:21 +01003712 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 int ret;
3714 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003715 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003717 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 if (ret < 0)
3719 return NULL;
3720 if (ret == 0) {
3721 Py_INCREF(Py_None);
3722 return Py_None;
3723 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003724 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 Py_XINCREF(m);
3726 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003727}
3728
Guido van Rossum79f25d91997-04-29 20:08:16 +00003729static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003730imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003731{
Victor Stinner53dc7352011-03-20 01:50:21 +01003732 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003733
Victor Stinner53dc7352011-03-20 01:50:21 +01003734 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 return NULL;
3736 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003737}
3738
Guido van Rossum79f25d91997-04-29 20:08:16 +00003739static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003740imp_is_frozen_package(PyObject *self, PyObject *args)
3741{
Victor Stinner53dc7352011-03-20 01:50:21 +01003742 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003743
Victor Stinner53dc7352011-03-20 01:50:21 +01003744 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 return NULL;
3746 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003747}
3748
3749static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003750imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003751{
Victor Stinner95872862011-03-07 18:20:56 +01003752 PyObject *name;
3753 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 return NULL;
3755 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003756}
3757
Guido van Rossum79f25d91997-04-29 20:08:16 +00003758static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003759imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003760{
Victor Stinner53dc7352011-03-20 01:50:21 +01003761 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003763 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 return NULL;
3765 p = find_frozen(name);
3766 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003767}
3768
3769static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003770get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 FILE *fp;
3773 if (mode[0] == 'U')
3774 mode = "r" PY_STDIOTEXTMODE;
3775 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003776 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003777 if (!fp) {
3778 if (!PyErr_Occurred())
3779 PyErr_SetFromErrno(PyExc_IOError);
3780 return NULL;
3781 }
3782 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 }
3784 else {
3785 int fd = PyObject_AsFileDescriptor(fob);
3786 if (fd == -1)
3787 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01003788 if (!_PyVerify_fd(fd)) {
3789 PyErr_SetFromErrno(PyExc_IOError);
3790 return NULL;
3791 }
3792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 /* the FILE struct gets a new fd, so that it can be closed
3794 * independently of the file descriptor given
3795 */
3796 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01003797 if (fd == -1) {
3798 PyErr_SetFromErrno(PyExc_IOError);
3799 return NULL;
3800 }
3801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003803 if (!fp) {
3804 PyErr_SetFromErrno(PyExc_IOError);
3805 return NULL;
3806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003808 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003809}
3810
Guido van Rossum79f25d91997-04-29 20:08:16 +00003811static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003812imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003813{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003814 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 PyObject *fob = NULL;
3816 PyObject *m;
3817 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003818 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003820 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 &fob))
3822 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003823 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003825 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 return NULL;
3827 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003828 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003830 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003832}
3833
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003834#ifdef HAVE_DYNAMIC_LOADING
3835
Guido van Rossum79f25d91997-04-29 20:08:16 +00003836static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003837imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003838{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003839 PyObject *name, *pathname, *fob = NULL, *mod;
3840 FILE *fp;
3841
3842 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3843 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003845 if (fob != NULL) {
3846 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003847 if (fp == NULL) {
3848 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003852 else
3853 fp = NULL;
3854 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003855 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 if (fp)
3857 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003858 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003859}
3860
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003861#endif /* HAVE_DYNAMIC_LOADING */
3862
Guido van Rossum79f25d91997-04-29 20:08:16 +00003863static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003864imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003865{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003866 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 PyObject *fob = NULL;
3868 PyObject *m;
3869 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003870 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003872 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 &fob))
3874 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003875 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003877 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 return NULL;
3879 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003880 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003881 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 fclose(fp);
3883 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003884}
3885
Guido van Rossum79f25d91997-04-29 20:08:16 +00003886static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003887imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003888{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003889 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 char *suffix; /* Unused */
3891 char *mode;
3892 int type;
3893 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003894
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003895 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3896 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003898 if (pathname_obj != Py_None) {
3899 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3900 return NULL;
3901 }
3902 else
3903 pathname = NULL;
3904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 if (*mode) {
3906 /* Mode must start with 'r' or 'U' and must not contain '+'.
3907 Implicit in this test is the assumption that the mode
3908 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3911 PyErr_Format(PyExc_ValueError,
3912 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003913 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 return NULL;
3915 }
3916 }
3917 if (fob == Py_None)
3918 fp = NULL;
3919 else {
3920 fp = get_file(NULL, fob, mode);
3921 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003922 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 return NULL;
3924 }
3925 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003926 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003927 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 if (fp)
3929 fclose(fp);
3930 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003931}
3932
3933static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003934imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003935{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003936 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003938 if (!PyArg_ParseTuple(args, "UO&:load_package",
3939 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003941 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003942 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003944}
3945
3946static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003947imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003948{
Victor Stinnerfe19d212011-03-14 14:53:28 -04003949 PyObject *name;
3950 if (!PyArg_ParseTuple(args, "U:new_module", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 return NULL;
Victor Stinnerfe19d212011-03-14 14:53:28 -04003952 return PyModule_NewObject(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003953}
3954
Christian Heimes13a7a212008-01-07 17:13:09 +00003955static PyObject *
3956imp_reload(PyObject *self, PyObject *v)
3957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003959}
3960
3961PyDoc_STRVAR(doc_reload,
3962"reload(module) -> module\n\
3963\n\
3964Reload the module. The module must have been successfully imported before.");
3965
Barry Warsaw28a691b2010-04-17 00:19:56 +00003966static PyObject *
3967imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003970
Victor Stinner2f42ae52011-03-20 00:41:24 +01003971 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003972 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003976 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003977 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003979
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003980 if (debug_override != NULL &&
3981 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003982 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003983 return NULL;
3984 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003985
Martin v. Löwis30260a72011-10-23 17:35:46 +02003986 if (PyUnicode_READY(pathname) < 0)
3987 return NULL;
3988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003989 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003990 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 if (cpathname == NULL) {
3993 PyErr_Format(PyExc_SystemError, "path buffer too short");
3994 return NULL;
3995 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003996 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003997}
3998
3999PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01004000"cache_from_source(path, [debug_override]) -> path\n\
4001Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004002\n\
4003The .py file does not need to exist; this simply returns the path to the\n\
4004.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
4005will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
4006\n\
4007If debug_override is not None, then it must be a boolean and is taken as\n\
4008the value of __debug__ instead.");
4009
4010static PyObject *
4011imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
4012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04004014 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00004017 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04004018 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004020
Victor Stinnerc9abda02011-03-14 13:33:46 -04004021 source = make_source_pathname(pathname);
4022 if (source == NULL) {
4023 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004024 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04004025 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 return NULL;
4027 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04004028 Py_DECREF(pathname);
4029 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004030}
4031
4032PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01004033"source_from_cache(path) -> path\n\
4034Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004035\n\
4036The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
4037the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
4038does not conform to PEP 3147 format, ValueError will be raised.");
4039
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004040/* Doc strings */
4041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004042PyDoc_STRVAR(doc_imp,
4043"This module provides the components needed to build your own\n\
4044__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004046PyDoc_STRVAR(doc_find_module,
4047"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004048Search for a module. If path is omitted or None, search for a\n\
4049built-in, frozen or special module and continue search in sys.path.\n\
4050The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004051package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004053PyDoc_STRVAR(doc_load_module,
4054"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004055Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004056The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004057
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004058PyDoc_STRVAR(doc_get_magic,
4059"get_magic() -> string\n\
4060Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004061
Barry Warsaw28a691b2010-04-17 00:19:56 +00004062PyDoc_STRVAR(doc_get_tag,
4063"get_tag() -> string\n\
4064Return the magic tag for .pyc or .pyo files.");
4065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004066PyDoc_STRVAR(doc_get_suffixes,
4067"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004068Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004069that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004071PyDoc_STRVAR(doc_new_module,
4072"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004073Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004074The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004076PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00004077"lock_held() -> boolean\n\
4078Return True if the import lock is currently held, else False.\n\
4079On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00004080
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004081PyDoc_STRVAR(doc_acquire_lock,
4082"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00004083Acquires the interpreter's import lock for the current thread.\n\
4084This lock should be used by import hooks to ensure thread-safety\n\
4085when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004086On platforms without threads, this function does nothing.");
4087
4088PyDoc_STRVAR(doc_release_lock,
4089"release_lock() -> None\n\
4090Release the interpreter's import lock.\n\
4091On platforms without threads, this function does nothing.");
4092
Guido van Rossum79f25d91997-04-29 20:08:16 +00004093static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
4095 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
4096 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
4097 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
4098 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
4099 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
4100 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
4101 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
4102 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
4103 {"reload", imp_reload, METH_O, doc_reload},
4104 {"cache_from_source", (PyCFunction)imp_cache_from_source,
4105 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
4106 {"source_from_cache", (PyCFunction)imp_source_from_cache,
4107 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
4108 /* The rest are obsolete */
4109 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
4110 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
4111 {"init_builtin", imp_init_builtin, METH_VARARGS},
4112 {"init_frozen", imp_init_frozen, METH_VARARGS},
4113 {"is_builtin", imp_is_builtin, METH_VARARGS},
4114 {"is_frozen", imp_is_frozen, METH_VARARGS},
4115 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004116#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004118#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 {"load_package", imp_load_package, METH_VARARGS},
4120 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07004121 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004123};
4124
Guido van Rossum1a8791e1998-08-04 22:46:29 +00004125static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004126setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 PyObject *v;
4129 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 v = PyLong_FromLong((long)value);
4132 err = PyDict_SetItemString(d, name, v);
4133 Py_XDECREF(v);
4134 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004135}
4136
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004137typedef struct {
4138 PyObject_HEAD
4139} NullImporter;
4140
4141static int
4142NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
4143{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004144#ifndef MS_WINDOWS
4145 PyObject *path;
4146 struct stat statbuf;
4147 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4150 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004151
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004152 if (!PyArg_ParseTuple(args, "O&:NullImporter",
4153 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004155
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004156 if (PyBytes_GET_SIZE(path) == 0) {
4157 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 PyErr_SetString(PyExc_ImportError, "empty pathname");
4159 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004161
4162 rv = stat(PyBytes_AS_STRING(path), &statbuf);
4163 Py_DECREF(path);
4164 if (rv == 0) {
4165 /* it exists */
4166 if (S_ISDIR(statbuf.st_mode)) {
4167 /* it's a directory */
4168 PyErr_SetString(PyExc_ImportError, "existing directory");
4169 return -1;
4170 }
4171 }
4172#else /* MS_WINDOWS */
4173 PyObject *pathobj;
4174 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00004175 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004176
4177 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4178 return -1;
4179
4180 if (!PyArg_ParseTuple(args, "U:NullImporter",
4181 &pathobj))
4182 return -1;
4183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004184 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004185 PyErr_SetString(PyExc_ImportError, "empty pathname");
4186 return -1;
4187 }
4188
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00004189 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004190 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004191 return -1;
4192 /* see issue1293 and issue3677:
4193 * stat() on Windows doesn't recognise paths like
4194 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
4195 */
4196 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004197 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004198 if (rv != INVALID_FILE_ATTRIBUTES) {
4199 /* it exists */
4200 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
4201 /* it's a directory */
4202 PyErr_SetString(PyExc_ImportError, "existing directory");
4203 return -1;
4204 }
4205 }
4206#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004208}
4209
4210static PyObject *
4211NullImporter_find_module(NullImporter *self, PyObject *args)
4212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004214}
4215
4216static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
4218 "Always return None"
4219 },
4220 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004221};
4222
4223
Christian Heimes9cd17752007-11-18 19:35:23 +00004224PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 PyVarObject_HEAD_INIT(NULL, 0)
4226 "imp.NullImporter", /*tp_name*/
4227 sizeof(NullImporter), /*tp_basicsize*/
4228 0, /*tp_itemsize*/
4229 0, /*tp_dealloc*/
4230 0, /*tp_print*/
4231 0, /*tp_getattr*/
4232 0, /*tp_setattr*/
4233 0, /*tp_reserved*/
4234 0, /*tp_repr*/
4235 0, /*tp_as_number*/
4236 0, /*tp_as_sequence*/
4237 0, /*tp_as_mapping*/
4238 0, /*tp_hash */
4239 0, /*tp_call*/
4240 0, /*tp_str*/
4241 0, /*tp_getattro*/
4242 0, /*tp_setattro*/
4243 0, /*tp_as_buffer*/
4244 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4245 "Null importer object", /* tp_doc */
4246 0, /* tp_traverse */
4247 0, /* tp_clear */
4248 0, /* tp_richcompare */
4249 0, /* tp_weaklistoffset */
4250 0, /* tp_iter */
4251 0, /* tp_iternext */
4252 NullImporter_methods, /* tp_methods */
4253 0, /* tp_members */
4254 0, /* tp_getset */
4255 0, /* tp_base */
4256 0, /* tp_dict */
4257 0, /* tp_descr_get */
4258 0, /* tp_descr_set */
4259 0, /* tp_dictoffset */
4260 (initproc)NullImporter_init, /* tp_init */
4261 0, /* tp_alloc */
4262 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004263};
4264
Martin v. Löwis1a214512008-06-11 05:26:20 +00004265static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 PyModuleDef_HEAD_INIT,
4267 "imp",
4268 doc_imp,
4269 0,
4270 imp_methods,
4271 NULL,
4272 NULL,
4273 NULL,
4274 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004275};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004276
Jason Tishler6bc06ec2003-09-04 11:59:50 +00004277PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004278PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 if (PyType_Ready(&PyNullImporter_Type) < 0)
4283 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 m = PyModule_Create(&impmodule);
4286 if (m == NULL)
4287 goto failure;
4288 d = PyModule_GetDict(m);
4289 if (d == NULL)
4290 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
4293 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
4294 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
4295 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
4296 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
4297 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
4298 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4299 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4300 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4301 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 Py_INCREF(&PyNullImporter_Type);
4304 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4305 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004306 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 Py_XDECREF(m);
4308 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004309}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004310
4311
Guido van Rossumb18618d2000-05-03 23:44:39 +00004312/* API for embedding applications that want to add their own entries
4313 to the table of built-in modules. This should normally be called
4314 *before* Py_Initialize(). When the table resize fails, -1 is
4315 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004316
4317 After a similar function by Just van Rossum. */
4318
4319int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004320PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 static struct _inittab *our_copy = NULL;
4323 struct _inittab *p;
4324 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 /* Count the number of entries in both tables */
4327 for (n = 0; newtab[n].name != NULL; n++)
4328 ;
4329 if (n == 0)
4330 return 0; /* Nothing to do */
4331 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4332 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 /* Allocate new memory for the combined table */
4335 p = our_copy;
4336 PyMem_RESIZE(p, struct _inittab, i+n+1);
4337 if (p == NULL)
4338 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 /* Copy the tables into the new memory */
4341 if (our_copy != PyImport_Inittab)
4342 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4343 PyImport_Inittab = our_copy = p;
4344 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004347}
4348
4349/* Shorthand to add a single entry given a name and a function */
4350
4351int
Brett Cannona826f322009-04-02 03:41:46 +00004352PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 newtab[0].name = (char *)name;
4359 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004362}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004363
4364#ifdef __cplusplus
4365}
4366#endif