blob: 76f40d300b5e0ec7eceaf8d31c7e14c5fab44a0d [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;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002545 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01002546 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (p->initfunc == NULL) {
2548 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002549 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 name);
2551 return -1;
2552 }
2553 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002554 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 mod = (*p->initfunc)();
2556 if (mod == 0)
2557 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002558 /* Remember pointer to module init function. */
2559 def = PyModule_GetDef(mod);
2560 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01002561 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return -1;
2563 /* FixupExtension has put the module into sys.modules,
2564 so we can release our own reference. */
2565 Py_DECREF(mod);
2566 return 1;
2567 }
2568 }
2569 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002570}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002571
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002572
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002573/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002574
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002575static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002576find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002579
Victor Stinner53dc7352011-03-20 01:50:21 +01002580 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 for (p = PyImport_FrozenModules; ; p++) {
2584 if (p->name == NULL)
2585 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002586 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 break;
2588 }
2589 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002590}
2591
Guido van Rossum79f25d91997-04-29 20:08:16 +00002592static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002593get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 struct _frozen *p = find_frozen(name);
2596 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 if (p == NULL) {
2599 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002600 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 name);
2602 return NULL;
2603 }
2604 if (p->code == NULL) {
2605 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002606 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 name);
2608 return NULL;
2609 }
2610 size = p->size;
2611 if (size < 0)
2612 size = -size;
2613 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002614}
2615
Brett Cannon8d110132009-03-15 02:20:16 +00002616static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002617is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 struct _frozen *p = find_frozen(name);
2620 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 if (p == NULL) {
2623 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002624 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 name);
2626 return NULL;
2627 }
Brett Cannon8d110132009-03-15 02:20:16 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (size < 0)
2632 Py_RETURN_TRUE;
2633 else
2634 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002635}
2636
2637
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002638/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002639 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002640 an exception set if the initialization failed.
2641 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002642
2643int
Victor Stinner53dc7352011-03-20 01:50:21 +01002644PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002645{
Victor Stinner53dc7352011-03-20 01:50:21 +01002646 struct _frozen *p;
2647 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 int ispackage;
2649 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002650
Victor Stinner53dc7352011-03-20 01:50:21 +01002651 p = find_frozen(name);
2652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (p == NULL)
2654 return 0;
2655 if (p->code == NULL) {
2656 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002657 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 name);
2659 return -1;
2660 }
2661 size = p->size;
2662 ispackage = (size < 0);
2663 if (ispackage)
2664 size = -size;
2665 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002666 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 name, ispackage ? " package" : "");
2668 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2669 if (co == NULL)
2670 return -1;
2671 if (!PyCode_Check(co)) {
2672 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002673 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 name);
2675 goto err_return;
2676 }
2677 if (ispackage) {
2678 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002679 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002681 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 if (m == NULL)
2683 goto err_return;
2684 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 l = PyList_New(1);
2686 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 goto err_return;
2688 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002689 Py_INCREF(name);
2690 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 err = PyDict_SetItemString(d, "__path__", l);
2692 Py_DECREF(l);
2693 if (err != 0)
2694 goto err_return;
2695 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002696 path = PyUnicode_FromString("<frozen>");
2697 if (path == NULL)
2698 goto err_return;
2699 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2700 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 if (m == NULL)
2702 goto err_return;
2703 Py_DECREF(co);
2704 Py_DECREF(m);
2705 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002706err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 Py_DECREF(co);
2708 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002709}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002710
Victor Stinner53dc7352011-03-20 01:50:21 +01002711int
2712PyImport_ImportFrozenModule(char *name)
2713{
2714 PyObject *nameobj;
2715 int ret;
2716 nameobj = PyUnicode_InternFromString(name);
2717 if (nameobj == NULL)
2718 return -1;
2719 ret = PyImport_ImportFrozenModuleObject(nameobj);
2720 Py_DECREF(nameobj);
2721 return ret;
2722}
2723
Guido van Rossum74e6a111994-08-29 12:54:38 +00002724
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002725/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002726 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002727
Guido van Rossum79f25d91997-04-29 20:08:16 +00002728PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002729PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyObject *pname;
2732 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 pname = PyUnicode_FromString(name);
2735 if (pname == NULL)
2736 return NULL;
2737 result = PyImport_Import(pname);
2738 Py_DECREF(pname);
2739 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002740}
2741
Christian Heimes072c0f12008-01-03 23:01:04 +00002742/* Import a module without blocking
2743 *
2744 * At first it tries to fetch the module from sys.modules. If the module was
2745 * never loaded before it loads it with PyImport_ImportModule() unless another
2746 * thread holds the import lock. In the latter case the function raises an
2747 * ImportError instead of blocking.
2748 *
2749 * Returns the module object with incremented ref count.
2750 */
2751PyObject *
2752PyImport_ImportModuleNoBlock(const char *name)
2753{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002754 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002755#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002757#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 /* Try to get the module from sys.modules[name] */
2760 modules = PyImport_GetModuleDict();
2761 if (modules == NULL)
2762 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002763
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002764 nameobj = PyUnicode_FromString(name);
2765 if (nameobj == NULL)
2766 return NULL;
2767 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002769 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 Py_INCREF(result);
2771 return result;
2772 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002773 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002774#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 /* check the import lock
2776 * me might be -1 but I ignore the error here, the lock function
2777 * takes care of the problem */
2778 me = PyThread_get_thread_ident();
2779 if (import_lock_thread == -1 || import_lock_thread == me) {
2780 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002781 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 }
2783 else {
2784 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002785 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002787 nameobj);
2788 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002790#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002791 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002792#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002793 Py_DECREF(nameobj);
2794 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002795}
2796
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002797/* Forward declarations for helper routines */
Victor Stinner974389d2011-03-15 09:33:57 +01002798static PyObject *get_parent(PyObject *globals,
2799 PyObject **p_name,
2800 int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002801static PyObject *load_next(PyObject *mod, PyObject *altmod,
Victor Stinner974389d2011-03-15 09:33:57 +01002802 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002803 PyObject **p_prefix);
Victor Stinner974389d2011-03-15 09:33:57 +01002804static int mark_miss(PyObject *name);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002805static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Victor Stinner974389d2011-03-15 09:33:57 +01002806 PyObject *buf, int recursive);
2807static PyObject * import_submodule(PyObject *mod, PyObject *name,
2808 PyObject *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002809
2810/* The Magnum Opus of dotted-name import :-) */
2811
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002812static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01002813import_module_level(PyObject *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002815{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002816 PyObject *parent, *next, *inputname, *outputname;
2817 PyObject *head = NULL;
2818 PyObject *tail = NULL;
2819 PyObject *prefix = NULL;
2820 PyObject *result = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 Py_ssize_t sep, altsep;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002823 if (PyUnicode_READY(name))
2824 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002826 sep = PyUnicode_FindChar(name, SEP, 0, PyUnicode_GET_LENGTH(name), 1);
2827 if (sep == -2)
2828 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002829#ifdef ALTSEP
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 altsep = PyUnicode_FindChar(name, ALTSEP, 0, PyUnicode_GET_LENGTH(name), 1);
2831 if (altsep == -2)
2832 return NULL;
2833#else
2834 altsep = -1;
Christian Heimes454f37b2008-01-10 00:10:02 +00002835#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002836 if (sep != -1 || altsep != -1)
2837 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 PyErr_SetString(PyExc_ImportError,
2839 "Import by filename is not supported.");
2840 return NULL;
2841 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002842
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002843 parent = get_parent(globals, &prefix, level);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002844 if (parent == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002846 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002847
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002848 if (PyUnicode_READY(prefix))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002849 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002850
2851 head = load_next(parent, level < 0 ? Py_None : parent, name, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002852 &prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 if (head == NULL)
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002854 goto out;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 tail = head;
2857 Py_INCREF(tail);
Victor Stinner974389d2011-03-15 09:33:57 +01002858
2859 if (outputname != NULL) {
2860 while (1) {
2861 inputname = outputname;
2862 next = load_next(tail, tail, inputname, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002863 &prefix);
2864 Py_CLEAR(tail);
2865 Py_CLEAR(inputname);
2866 if (next == NULL)
2867 goto out;
Victor Stinner974389d2011-03-15 09:33:57 +01002868 tail = next;
2869
2870 if (outputname == NULL) {
2871 break;
2872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 }
2875 if (tail == Py_None) {
2876 /* If tail is Py_None, both get_parent and load_next found
2877 an empty module name: someone called __import__("") or
2878 doctored faulty bytecode */
Victor Stinner974389d2011-03-15 09:33:57 +01002879 PyErr_SetString(PyExc_ValueError, "Empty module name");
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002880 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if (fromlist != NULL) {
2884 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2885 fromlist = NULL;
2886 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (fromlist == NULL) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002889 result = head;
2890 Py_INCREF(result);
2891 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002893
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002894 if (!ensure_fromlist(tail, fromlist, prefix, 0))
2895 goto out;
Victor Stinner1f795172011-11-17 00:45:54 +01002896
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002897 result = tail;
2898 Py_INCREF(result);
2899 out:
2900 Py_XDECREF(head);
2901 Py_XDECREF(tail);
2902 Py_XDECREF(prefix);
2903 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002904}
2905
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002906PyObject *
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002907PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2908 PyObject *locals, PyObject *fromlist,
2909 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002910{
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002911 PyObject *mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 _PyImport_AcquireLock();
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002913 mod = import_module_level(name, globals, locals, fromlist, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 if (_PyImport_ReleaseLock() < 0) {
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002915 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 PyErr_SetString(PyExc_RuntimeError,
2917 "not holding the import lock");
2918 return NULL;
2919 }
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002920 return mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002921}
2922
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002923PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002924PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002925 PyObject *fromlist, int level)
2926{
2927 PyObject *nameobj, *mod;
2928 nameobj = PyUnicode_FromString(name);
2929 if (nameobj == NULL)
2930 return NULL;
2931 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2932 fromlist, level);
2933 Py_DECREF(nameobj);
2934 return mod;
2935}
2936
2937
Fred Drake87590902004-05-28 20:21:36 +00002938/* Return the package that an import is being performed in. If globals comes
2939 from the module foo.bar.bat (not itself a package), this returns the
2940 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002941 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002942
Victor Stinner974389d2011-03-15 09:33:57 +01002943 The name of the returned package is returned in *p_name.
Fred Drake87590902004-05-28 20:21:36 +00002944
2945 If globals doesn't come from a package or a module in a package, or a
2946 corresponding entry is not found in sys.modules, Py_None is returned.
2947*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002948static PyObject *
Victor Stinner9599de52011-03-13 22:38:38 -04002949get_parent(PyObject *globals, PyObject **p_name, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002950{
Victor Stinner974389d2011-03-15 09:33:57 +01002951 PyObject *nameobj;
2952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 static PyObject *namestr = NULL;
2954 static PyObject *pathstr = NULL;
2955 static PyObject *pkgstr = NULL;
2956 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2957 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 if (globals == NULL || !PyDict_Check(globals) || !level)
Victor Stinner974389d2011-03-15 09:33:57 +01002960 goto return_none;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 if (namestr == NULL) {
2963 namestr = PyUnicode_InternFromString("__name__");
2964 if (namestr == NULL)
2965 return NULL;
2966 }
2967 if (pathstr == NULL) {
2968 pathstr = PyUnicode_InternFromString("__path__");
2969 if (pathstr == NULL)
2970 return NULL;
2971 }
2972 if (pkgstr == NULL) {
2973 pkgstr = PyUnicode_InternFromString("__package__");
2974 if (pkgstr == NULL)
2975 return NULL;
2976 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 if ((pkgname != NULL) && (pkgname != Py_None)) {
2981 /* __package__ is set, so use it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 if (!PyUnicode_Check(pkgname)) {
2983 PyErr_SetString(PyExc_ValueError,
2984 "__package__ set to non-string");
2985 return NULL;
2986 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002987 if (PyUnicode_GET_LENGTH(pkgname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 if (level > 0) {
2989 PyErr_SetString(PyExc_ValueError,
2990 "Attempted relative import in non-package");
2991 return NULL;
2992 }
Victor Stinner974389d2011-03-15 09:33:57 +01002993 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002995 Py_INCREF(pkgname);
2996 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 } else {
2998 /* __package__ not set, so figure it out and set it */
2999 modname = PyDict_GetItem(globals, namestr);
3000 if (modname == NULL || !PyUnicode_Check(modname))
Victor Stinner974389d2011-03-15 09:33:57 +01003001 goto return_none;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 modpath = PyDict_GetItem(globals, pathstr);
3004 if (modpath != NULL) {
3005 /* __path__ is set, so modname is already the package name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 error = PyDict_SetItem(globals, pkgstr, modname);
3009 if (error) {
3010 PyErr_SetString(PyExc_ValueError,
3011 "Could not set __package__");
3012 return NULL;
3013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014 Py_INCREF(modname);
3015 nameobj = modname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 } else {
3017 /* Normal module, so work out the package name if any */
Victor Stinner974389d2011-03-15 09:33:57 +01003018 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003019 len = PyUnicode_FindChar(modname, '.',
3020 0, PyUnicode_GET_LENGTH(modname), -1);
3021 if (len == -2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003023 if (len < 0) {
3024 if (level > 0) {
3025 PyErr_SetString(PyExc_ValueError,
3026 "Attempted relative import in non-package");
3027 return NULL;
3028 }
3029 if (PyDict_SetItem(globals, pkgstr, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 PyErr_SetString(PyExc_ValueError,
3031 "Could not set __package__");
3032 return NULL;
3033 }
Victor Stinner974389d2011-03-15 09:33:57 +01003034 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003036 pkgname = PyUnicode_Substring(modname, 0, len);
3037 if (pkgname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003039 if (PyDict_SetItem(globals, pkgstr, pkgname)) {
3040 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 PyErr_SetString(PyExc_ValueError,
3042 "Could not set __package__");
3043 return NULL;
3044 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003045 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 }
3047 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003048 if (level > 1) {
3049 Py_ssize_t dot, end = PyUnicode_GET_LENGTH(nameobj);
3050 PyObject *newname;
3051 while (--level > 0) {
3052 dot = PyUnicode_FindChar(nameobj, '.', 0, end, -1);
3053 if (dot == -2) {
3054 Py_DECREF(nameobj);
3055 return NULL;
3056 }
3057 if (dot < 0) {
3058 Py_DECREF(nameobj);
3059 PyErr_SetString(PyExc_ValueError,
3060 "Attempted relative import beyond "
3061 "toplevel package");
3062 return NULL;
3063 }
3064 end = dot;
3065 }
3066 newname = PyUnicode_Substring(nameobj, 0, end);
3067 Py_DECREF(nameobj);
3068 if (newname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003070 nameobj = newname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 }
Victor Stinner974389d2011-03-15 09:33:57 +01003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003074 parent = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (parent == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003076 int err;
3077
3078 if (orig_level >= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 PyErr_Format(PyExc_SystemError,
Victor Stinner974389d2011-03-15 09:33:57 +01003080 "Parent module %R not loaded, "
3081 "cannot perform relative import", nameobj);
3082 Py_DECREF(nameobj);
3083 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 }
Victor Stinner974389d2011-03-15 09:33:57 +01003085
3086 err = PyErr_WarnFormat(
3087 PyExc_RuntimeWarning, 1,
3088 "Parent module %R not found while handling absolute import",
3089 nameobj);
3090 Py_DECREF(nameobj);
3091 if (err)
3092 return NULL;
3093
3094 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 }
Victor Stinner974389d2011-03-15 09:33:57 +01003096 *p_name = nameobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 return parent;
3098 /* We expect, but can't guarantee, if parent != None, that:
Victor Stinner974389d2011-03-15 09:33:57 +01003099 - parent.__name__ == name
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 - parent.__dict__ is globals
3101 If this is violated... Who cares? */
Victor Stinner974389d2011-03-15 09:33:57 +01003102
3103return_none:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003104 nameobj = PyUnicode_New(0, 0);
Victor Stinner974389d2011-03-15 09:33:57 +01003105 if (nameobj == NULL)
3106 return NULL;
3107 *p_name = nameobj;
3108 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003109}
3110
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003111/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003112static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003113load_next(PyObject *mod, PyObject *altmod,
3114 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003115 PyObject **p_prefix)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003116{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003117 Py_ssize_t dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003118 Py_ssize_t len;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003119 PyObject *fullname, *name = NULL, *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003120
Victor Stinner974389d2011-03-15 09:33:57 +01003121 *p_outputname = NULL;
3122
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003123 len = PyUnicode_GET_LENGTH(inputname);
3124 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 /* completely empty module name should only happen in
3126 'from . import' (or '__import__("")')*/
3127 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 return mod;
3129 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003130
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003131
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003132 dot = PyUnicode_FindChar(inputname, '.', 0, len, 1);
3133 if (dot >= 0) {
3134 len = dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003135 if (len == 0) {
3136 PyErr_SetString(PyExc_ValueError,
3137 "Empty module name");
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003138 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003139 }
3140 }
Victor Stinner974389d2011-03-15 09:33:57 +01003141
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003142 /* name = inputname[:len] */
3143 name = PyUnicode_Substring(inputname, 0, len);
3144 if (name == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003145 goto error;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003146
3147 if (PyUnicode_GET_LENGTH(*p_prefix)) {
3148 /* fullname = prefix + "." + name */
3149 fullname = PyUnicode_FromFormat("%U.%U", *p_prefix, name);
3150 if (fullname == NULL)
3151 goto error;
3152 }
3153 else {
3154 fullname = name;
3155 Py_INCREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003157
Victor Stinner974389d2011-03-15 09:33:57 +01003158 result = import_submodule(mod, name, fullname);
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003159 Py_DECREF(*p_prefix);
3160 /* Transfer reference. */
3161 *p_prefix = fullname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 if (result == Py_None && altmod != mod) {
3163 Py_DECREF(result);
3164 /* Here, altmod must be None and mod must not be None */
Victor Stinner974389d2011-03-15 09:33:57 +01003165 result = import_submodule(altmod, name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 if (result != NULL && result != Py_None) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003167 if (mark_miss(*p_prefix) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003169 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 }
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003171 Py_DECREF(*p_prefix);
3172 *p_prefix = name;
3173 Py_INCREF(*p_prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 }
3175 }
3176 if (result == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003177 goto error;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 if (result == Py_None) {
3180 Py_DECREF(result);
3181 PyErr_Format(PyExc_ImportError,
Victor Stinner974389d2011-03-15 09:33:57 +01003182 "No module named %R", inputname);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003183 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003185
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003186 if (dot >= 0) {
3187 *p_outputname = PyUnicode_Substring(inputname, dot+1,
3188 PyUnicode_GET_LENGTH(inputname));
Victor Stinner974389d2011-03-15 09:33:57 +01003189 if (*p_outputname == NULL) {
3190 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003191 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003192 }
3193 }
3194
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003195 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 return result;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003197
3198error:
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003199 Py_XDECREF(name);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003200 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003201}
3202
3203static int
Victor Stinner974389d2011-03-15 09:33:57 +01003204mark_miss(PyObject *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003207 return PyDict_SetItem(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003208}
3209
3210static int
Victor Stinner974389d2011-03-15 09:33:57 +01003211ensure_fromlist(PyObject *mod, PyObject *fromlist, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 int i;
Victor Stinner974389d2011-03-15 09:33:57 +01003215 PyObject *fullname;
3216 Py_ssize_t fromlist_len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003217
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003218 if (!_PyObject_HasAttrId(mod, &PyId___path__))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003220
Victor Stinner974389d2011-03-15 09:33:57 +01003221 fromlist_len = PySequence_Size(fromlist);
3222
3223 for (i = 0; i < fromlist_len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 PyObject *item = PySequence_GetItem(fromlist, i);
3225 int hasit;
Victor Stinner974389d2011-03-15 09:33:57 +01003226 if (item == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 if (!PyUnicode_Check(item)) {
3229 PyErr_SetString(PyExc_TypeError,
3230 "Item in ``from list'' not a string");
3231 Py_DECREF(item);
3232 return 0;
3233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003234 if (PyUnicode_READ_CHAR(item, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 PyObject *all;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003236 _Py_IDENTIFIER(__all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 Py_DECREF(item);
3238 /* See if the package defines __all__ */
3239 if (recursive)
3240 continue; /* Avoid endless recursion */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003241 all = _PyObject_GetAttrId(mod, &PyId___all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 if (all == NULL)
3243 PyErr_Clear();
3244 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003245 int ret = ensure_fromlist(mod, all, name, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 Py_DECREF(all);
3247 if (!ret)
3248 return 0;
3249 }
3250 continue;
3251 }
3252 hasit = PyObject_HasAttr(mod, item);
3253 if (!hasit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 PyObject *submod;
Victor Stinner974389d2011-03-15 09:33:57 +01003255 fullname = PyUnicode_FromFormat("%U.%U", name, item);
3256 if (fullname != NULL) {
3257 submod = import_submodule(mod, item, fullname);
3258 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 }
Victor Stinner974389d2011-03-15 09:33:57 +01003260 else
3261 submod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 Py_XDECREF(submod);
3263 if (submod == NULL) {
3264 Py_DECREF(item);
3265 return 0;
3266 }
3267 }
3268 Py_DECREF(item);
3269 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003270
Victor Stinner974389d2011-03-15 09:33:57 +01003271 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003272}
3273
Neil Schemenauer00b09662003-06-16 21:03:07 +00003274static int
Victor Stinner974389d2011-03-15 09:33:57 +01003275add_submodule(PyObject *mod, PyObject *submod, PyObject *fullname,
3276 PyObject *subname, PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00003277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 if (mod == Py_None)
3279 return 1;
3280 /* Irrespective of the success of this load, make a
3281 reference to it in the parent package module. A copy gets
3282 saved in the modules dictionary under the full name, so get a
3283 reference from there, if need be. (The exception is when the
3284 load failed with a SyntaxError -- then there's no trace in
3285 sys.modules. In that case, of course, do nothing extra.) */
3286 if (submod == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003287 submod = PyDict_GetItem(modules, fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 if (submod == NULL)
3289 return 1;
3290 }
3291 if (PyModule_Check(mod)) {
3292 /* We can't use setattr here since it can give a
3293 * spurious warning if the submodule name shadows a
3294 * builtin name */
3295 PyObject *dict = PyModule_GetDict(mod);
3296 if (!dict)
3297 return 0;
Victor Stinner974389d2011-03-15 09:33:57 +01003298 if (PyDict_SetItem(dict, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 return 0;
3300 }
3301 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003302 if (PyObject_SetAttr(mod, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 return 0;
3304 }
3305 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00003306}
3307
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003308static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003309import_submodule(PyObject *mod, PyObject *subname, PyObject *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003312 PyObject *m = NULL, *bufobj, *path_list, *loader;
Victor Stinner9599de52011-03-13 22:38:38 -04003313 struct filedescr *fdp;
3314 FILE *fp;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 /* Require:
3317 if mod == None: subname == fullname
3318 else: mod.__name__ + "." + subname == fullname
3319 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003320
Victor Stinner974389d2011-03-15 09:33:57 +01003321 if ((m = PyDict_GetItem(modules, fullname)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 Py_INCREF(m);
Victor Stinner9599de52011-03-13 22:38:38 -04003323 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 }
Victor Stinner9599de52011-03-13 22:38:38 -04003325
3326 if (mod == Py_None)
Victor Stinner533d7832011-03-14 13:22:54 -04003327 path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003329 path_list = _PyObject_GetAttrId(mod, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003330 if (path_list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 PyErr_Clear();
3332 Py_INCREF(Py_None);
3333 return Py_None;
3334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003336
Victor Stinner533d7832011-03-14 13:22:54 -04003337 fdp = find_module(fullname, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003338 &bufobj, &fp, &loader);
Victor Stinner533d7832011-03-14 13:22:54 -04003339 Py_XDECREF(path_list);
Victor Stinner9599de52011-03-13 22:38:38 -04003340 if (fdp == NULL) {
3341 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3342 return NULL;
3343 PyErr_Clear();
3344 Py_INCREF(Py_None);
3345 return Py_None;
3346 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003347 m = load_module(fullname, fp, bufobj, fdp->type, loader);
3348 Py_XDECREF(bufobj);
Victor Stinner9599de52011-03-13 22:38:38 -04003349 Py_XDECREF(loader);
3350 if (fp)
3351 fclose(fp);
3352 if (m == NULL)
3353 return NULL;
3354 if (!add_submodule(mod, m, fullname, subname, modules)) {
3355 Py_XDECREF(m);
3356 return NULL;
3357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003359}
3360
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003361
3362/* Re-import a module of any kind and return its module object, WITH
3363 INCREMENTED REFERENCE COUNT */
3364
Guido van Rossum79f25d91997-04-29 20:08:16 +00003365PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003366PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 PyInterpreterState *interp = PyThreadState_Get()->interp;
3369 PyObject *modules_reloading = interp->modules_reloading;
3370 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003371 PyObject *path_list = NULL, *loader = NULL, *existing_m = NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003372 PyObject *name, *bufobj, *subname;
3373 Py_ssize_t subname_start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 struct filedescr *fdp;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003375 FILE *fp = NULL;
3376 PyObject *newm = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 if (modules_reloading == NULL) {
3379 Py_FatalError("PyImport_ReloadModule: "
3380 "no modules_reloading dictionary!");
3381 return NULL;
3382 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 if (m == NULL || !PyModule_Check(m)) {
3385 PyErr_SetString(PyExc_TypeError,
3386 "reload() argument must be module");
3387 return NULL;
3388 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003389 name = PyModule_GetNameObject(m);
3390 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003392 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003394 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01003395 name);
3396 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 return NULL;
3398 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003399 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 if (existing_m != NULL) {
3401 /* Due to a recursive reload, this module is already
3402 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003403 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 Py_INCREF(existing_m);
3405 return existing_m;
3406 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003407 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
3408 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003410 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003411
Martin v. Löwis796ea532011-10-30 09:07:07 +01003412 subname_start = PyUnicode_FindChar(name, '.', 0,
3413 PyUnicode_GET_LENGTH(name), -1);
3414 if (subname_start == -1) {
3415 Py_INCREF(name);
3416 subname = name;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003417 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 else {
3419 PyObject *parentname, *parent;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003420 Py_ssize_t len;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003421 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003423 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 }
3425 parent = PyDict_GetItem(modules, parentname);
3426 if (parent == NULL) {
3427 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003428 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 parentname);
3430 Py_DECREF(parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003431 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 }
3433 Py_DECREF(parentname);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003434 path_list = _PyObject_GetAttrId(parent, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003435 if (path_list == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 PyErr_Clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003437 subname_start++;
3438 len = PyUnicode_GET_LENGTH(name) - (subname_start + 1);
3439 subname = PyUnicode_Substring(name, subname_start, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003441 if (subname == NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003442 goto error;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003443 fdp = find_module(name, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003444 &bufobj, &fp, &loader);
Martin v. Löwis796ea532011-10-30 09:07:07 +01003445 Py_DECREF(subname);
Victor Stinner533d7832011-03-14 13:22:54 -04003446 Py_XDECREF(path_list);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 if (fdp == NULL) {
3449 Py_XDECREF(loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003450 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003452
Martin v. Löwis796ea532011-10-30 09:07:07 +01003453 newm = load_module(name, fp, bufobj, fdp->type, loader);
Victor Stinner2fd76e42011-03-14 15:19:39 -04003454 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 if (fp)
3458 fclose(fp);
3459 if (newm == NULL) {
3460 /* load_module probably removed name from modules because of
3461 * the error. Put back the original module object. We're
3462 * going to return NULL in this case regardless of whether
3463 * replacing name succeeds, so the return value is ignored.
3464 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003465 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003467
3468error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003470 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003472}
3473
3474
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003475/* Higher-level import emulator which emulates the "import" statement
3476 more accurately -- it invokes the __import__() function from the
3477 builtins of the current globals. This means that the import is
3478 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003479 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003480 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003481 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003482 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003483
3484PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003485PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 static PyObject *silly_list = NULL;
3488 static PyObject *builtins_str = NULL;
3489 static PyObject *import_str = NULL;
3490 PyObject *globals = NULL;
3491 PyObject *import = NULL;
3492 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003493 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 /* Initialize constant string objects */
3497 if (silly_list == NULL) {
3498 import_str = PyUnicode_InternFromString("__import__");
3499 if (import_str == NULL)
3500 return NULL;
3501 builtins_str = PyUnicode_InternFromString("__builtins__");
3502 if (builtins_str == NULL)
3503 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003504 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 if (silly_list == NULL)
3506 return NULL;
3507 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 /* Get the builtins from current globals */
3510 globals = PyEval_GetGlobals();
3511 if (globals != NULL) {
3512 Py_INCREF(globals);
3513 builtins = PyObject_GetItem(globals, builtins_str);
3514 if (builtins == NULL)
3515 goto err;
3516 }
3517 else {
3518 /* No globals -- use standard builtins, and fake globals */
3519 builtins = PyImport_ImportModuleLevel("builtins",
3520 NULL, NULL, NULL, 0);
3521 if (builtins == NULL)
3522 return NULL;
3523 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3524 if (globals == NULL)
3525 goto err;
3526 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /* Get the __import__ function from the builtins */
3529 if (PyDict_Check(builtins)) {
3530 import = PyObject_GetItem(builtins, import_str);
3531 if (import == NULL)
3532 PyErr_SetObject(PyExc_KeyError, import_str);
3533 }
3534 else
3535 import = PyObject_GetAttr(builtins, import_str);
3536 if (import == NULL)
3537 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003540 Always use absolute import here.
3541 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3543 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003544 if (r == NULL)
3545 goto err;
3546 Py_DECREF(r);
3547
3548 modules = PyImport_GetModuleDict();
3549 r = PyDict_GetItem(modules, module_name);
3550 if (r != NULL)
3551 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003552
3553 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 Py_XDECREF(globals);
3555 Py_XDECREF(builtins);
3556 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003559}
3560
3561
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003562/* Module 'imp' provides Python access to the primitives used for
3563 importing modules.
3564*/
3565
Guido van Rossum79f25d91997-04-29 20:08:16 +00003566static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003567imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 buf[0] = (char) ((magic >> 0) & 0xff);
3572 buf[1] = (char) ((magic >> 8) & 0xff);
3573 buf[2] = (char) ((magic >> 16) & 0xff);
3574 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003577}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003578
3579static PyObject *
3580imp_get_magic(PyObject *self, PyObject *noargs)
3581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003583}
3584
3585static PyObject *
3586imp_get_tag(PyObject *self, PyObject *noargs)
3587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003589}
3590
Guido van Rossum79f25d91997-04-29 20:08:16 +00003591static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003592imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 PyObject *list;
3595 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 list = PyList_New(0);
3598 if (list == NULL)
3599 return NULL;
3600 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3601 PyObject *item = Py_BuildValue("ssi",
3602 fdp->suffix, fdp->mode, fdp->type);
3603 if (item == NULL) {
3604 Py_DECREF(list);
3605 return NULL;
3606 }
3607 if (PyList_Append(list, item) < 0) {
3608 Py_DECREF(list);
3609 Py_DECREF(item);
3610 return NULL;
3611 }
3612 Py_DECREF(item);
3613 }
3614 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003615}
3616
Guido van Rossum79f25d91997-04-29 20:08:16 +00003617static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003618call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 extern int fclose(FILE *);
3621 PyObject *fob, *ret;
3622 PyObject *pathobj;
3623 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003624 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 int fd = -1;
3626 char *found_encoding = NULL;
3627 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003628
Victor Stinner533d7832011-03-14 13:22:54 -04003629 if (path_list == Py_None)
3630 path_list = NULL;
3631 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003632 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 if (fdp == NULL)
3634 return NULL;
3635 if (fp != NULL) {
3636 fd = fileno(fp);
3637 if (fd != -1)
3638 fd = dup(fd);
3639 fclose(fp);
Victor Stinnerd417d012011-06-20 15:16:55 +02003640 if (fd == -1) {
3641 PyErr_SetFromErrno(PyExc_OSError);
3642 return NULL;
3643 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 fp = NULL;
3645 }
3646 if (fd != -1) {
3647 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003648 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003650 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003652 if (found_encoding == NULL && PyErr_Occurred()) {
3653 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003655 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 encoding = (found_encoding != NULL) ? found_encoding :
3657 (char*)PyUnicode_GetDefaultEncoding();
3658 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003659 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 (char*)encoding, NULL, NULL, 1);
3661 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003662 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 close(fd);
3664 PyMem_FREE(found_encoding);
3665 return NULL;
3666 }
3667 }
3668 else {
3669 fob = Py_None;
3670 Py_INCREF(fob);
3671 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003672 if (pathobj == NULL) {
3673 Py_INCREF(Py_None);
3674 pathobj = Py_None;
3675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 ret = Py_BuildValue("NN(ssi)",
3677 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3678 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003681}
3682
Guido van Rossum79f25d91997-04-29 20:08:16 +00003683static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003684imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003685{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003686 PyObject *name, *path_list = NULL;
3687 if (!PyArg_ParseTuple(args, "U|O:find_module",
3688 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003690 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003691}
3692
3693static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003694imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003695{
Victor Stinner95872862011-03-07 18:20:56 +01003696 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 int ret;
3698 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003699 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 return NULL;
3701 ret = init_builtin(name);
3702 if (ret < 0)
3703 return NULL;
3704 if (ret == 0) {
3705 Py_INCREF(Py_None);
3706 return Py_None;
3707 }
Victor Stinner95872862011-03-07 18:20:56 +01003708 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 Py_XINCREF(m);
3710 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003711}
3712
Guido van Rossum79f25d91997-04-29 20:08:16 +00003713static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003714imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003715{
Victor Stinner53dc7352011-03-20 01:50:21 +01003716 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 int ret;
3718 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003719 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003721 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 if (ret < 0)
3723 return NULL;
3724 if (ret == 0) {
3725 Py_INCREF(Py_None);
3726 return Py_None;
3727 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003728 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 Py_XINCREF(m);
3730 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003731}
3732
Guido van Rossum79f25d91997-04-29 20:08:16 +00003733static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003734imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003735{
Victor Stinner53dc7352011-03-20 01:50:21 +01003736 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003737
Victor Stinner53dc7352011-03-20 01:50:21 +01003738 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 return NULL;
3740 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003741}
3742
Guido van Rossum79f25d91997-04-29 20:08:16 +00003743static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003744imp_is_frozen_package(PyObject *self, PyObject *args)
3745{
Victor Stinner53dc7352011-03-20 01:50:21 +01003746 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003747
Victor Stinner53dc7352011-03-20 01:50:21 +01003748 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 return NULL;
3750 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003751}
3752
3753static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003754imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003755{
Victor Stinner95872862011-03-07 18:20:56 +01003756 PyObject *name;
3757 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 return NULL;
3759 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003760}
3761
Guido van Rossum79f25d91997-04-29 20:08:16 +00003762static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003763imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003764{
Victor Stinner53dc7352011-03-20 01:50:21 +01003765 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003767 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 return NULL;
3769 p = find_frozen(name);
3770 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003771}
3772
3773static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003774get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 FILE *fp;
3777 if (mode[0] == 'U')
3778 mode = "r" PY_STDIOTEXTMODE;
3779 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003780 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003781 if (!fp) {
3782 if (!PyErr_Occurred())
3783 PyErr_SetFromErrno(PyExc_IOError);
3784 return NULL;
3785 }
3786 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 }
3788 else {
3789 int fd = PyObject_AsFileDescriptor(fob);
3790 if (fd == -1)
3791 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01003792 if (!_PyVerify_fd(fd)) {
3793 PyErr_SetFromErrno(PyExc_IOError);
3794 return NULL;
3795 }
3796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 /* the FILE struct gets a new fd, so that it can be closed
3798 * independently of the file descriptor given
3799 */
3800 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01003801 if (fd == -1) {
3802 PyErr_SetFromErrno(PyExc_IOError);
3803 return NULL;
3804 }
3805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003807 if (!fp) {
3808 PyErr_SetFromErrno(PyExc_IOError);
3809 return NULL;
3810 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003812 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003813}
3814
Guido van Rossum79f25d91997-04-29 20:08:16 +00003815static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003816imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003817{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003818 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 PyObject *fob = NULL;
3820 PyObject *m;
3821 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003822 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003824 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 &fob))
3826 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003827 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003829 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 return NULL;
3831 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003832 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003834 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003836}
3837
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003838#ifdef HAVE_DYNAMIC_LOADING
3839
Guido van Rossum79f25d91997-04-29 20:08:16 +00003840static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003841imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003842{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003843 PyObject *name, *pathname, *fob = NULL, *mod;
3844 FILE *fp;
3845
3846 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3847 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003849 if (fob != NULL) {
3850 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003851 if (fp == NULL) {
3852 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003856 else
3857 fp = NULL;
3858 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003859 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 if (fp)
3861 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003862 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003863}
3864
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003865#endif /* HAVE_DYNAMIC_LOADING */
3866
Guido van Rossum79f25d91997-04-29 20:08:16 +00003867static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003868imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003869{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003870 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 PyObject *fob = NULL;
3872 PyObject *m;
3873 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003874 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003876 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 &fob))
3878 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003879 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003881 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 return NULL;
3883 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003884 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003885 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 fclose(fp);
3887 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003888}
3889
Guido van Rossum79f25d91997-04-29 20:08:16 +00003890static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003891imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003892{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003893 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 char *suffix; /* Unused */
3895 char *mode;
3896 int type;
3897 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003898
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003899 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3900 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003902 if (pathname_obj != Py_None) {
3903 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3904 return NULL;
3905 }
3906 else
3907 pathname = NULL;
3908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 if (*mode) {
3910 /* Mode must start with 'r' or 'U' and must not contain '+'.
3911 Implicit in this test is the assumption that the mode
3912 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3915 PyErr_Format(PyExc_ValueError,
3916 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003917 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 return NULL;
3919 }
3920 }
3921 if (fob == Py_None)
3922 fp = NULL;
3923 else {
3924 fp = get_file(NULL, fob, mode);
3925 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003926 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 return NULL;
3928 }
3929 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003930 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003931 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 if (fp)
3933 fclose(fp);
3934 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003935}
3936
3937static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003938imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003939{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003940 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003942 if (!PyArg_ParseTuple(args, "UO&:load_package",
3943 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003945 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003946 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003948}
3949
3950static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003951imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003952{
Victor Stinnerfe19d212011-03-14 14:53:28 -04003953 PyObject *name;
3954 if (!PyArg_ParseTuple(args, "U:new_module", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 return NULL;
Victor Stinnerfe19d212011-03-14 14:53:28 -04003956 return PyModule_NewObject(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003957}
3958
Christian Heimes13a7a212008-01-07 17:13:09 +00003959static PyObject *
3960imp_reload(PyObject *self, PyObject *v)
3961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003963}
3964
3965PyDoc_STRVAR(doc_reload,
3966"reload(module) -> module\n\
3967\n\
3968Reload the module. The module must have been successfully imported before.");
3969
Barry Warsaw28a691b2010-04-17 00:19:56 +00003970static PyObject *
3971imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003974
Victor Stinner2f42ae52011-03-20 00:41:24 +01003975 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003976 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003980 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003981 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003983
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003984 if (debug_override != NULL &&
3985 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003986 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003987 return NULL;
3988 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003989
Martin v. Löwis30260a72011-10-23 17:35:46 +02003990 if (PyUnicode_READY(pathname) < 0)
3991 return NULL;
3992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003993 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003994 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 if (cpathname == NULL) {
3997 PyErr_Format(PyExc_SystemError, "path buffer too short");
3998 return NULL;
3999 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01004000 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004001}
4002
4003PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01004004"cache_from_source(path, [debug_override]) -> path\n\
4005Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004006\n\
4007The .py file does not need to exist; this simply returns the path to the\n\
4008.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
4009will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
4010\n\
4011If debug_override is not None, then it must be a boolean and is taken as\n\
4012the value of __debug__ instead.");
4013
4014static PyObject *
4015imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
4016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04004018 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00004021 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04004022 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004024
Victor Stinnerc9abda02011-03-14 13:33:46 -04004025 source = make_source_pathname(pathname);
4026 if (source == NULL) {
4027 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04004029 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 return NULL;
4031 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04004032 Py_DECREF(pathname);
4033 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004034}
4035
4036PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01004037"source_from_cache(path) -> path\n\
4038Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004039\n\
4040The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
4041the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
4042does not conform to PEP 3147 format, ValueError will be raised.");
4043
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004044/* Doc strings */
4045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004046PyDoc_STRVAR(doc_imp,
4047"This module provides the components needed to build your own\n\
4048__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004050PyDoc_STRVAR(doc_find_module,
4051"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004052Search for a module. If path is omitted or None, search for a\n\
4053built-in, frozen or special module and continue search in sys.path.\n\
4054The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004055package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004056
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004057PyDoc_STRVAR(doc_load_module,
4058"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004059Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004060The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004062PyDoc_STRVAR(doc_get_magic,
4063"get_magic() -> string\n\
4064Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004065
Barry Warsaw28a691b2010-04-17 00:19:56 +00004066PyDoc_STRVAR(doc_get_tag,
4067"get_tag() -> string\n\
4068Return the magic tag for .pyc or .pyo files.");
4069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004070PyDoc_STRVAR(doc_get_suffixes,
4071"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004072Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004073that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004075PyDoc_STRVAR(doc_new_module,
4076"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004077Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004078The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004079
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004080PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00004081"lock_held() -> boolean\n\
4082Return True if the import lock is currently held, else False.\n\
4083On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00004084
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004085PyDoc_STRVAR(doc_acquire_lock,
4086"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00004087Acquires the interpreter's import lock for the current thread.\n\
4088This lock should be used by import hooks to ensure thread-safety\n\
4089when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004090On platforms without threads, this function does nothing.");
4091
4092PyDoc_STRVAR(doc_release_lock,
4093"release_lock() -> None\n\
4094Release the interpreter's import lock.\n\
4095On platforms without threads, this function does nothing.");
4096
Guido van Rossum79f25d91997-04-29 20:08:16 +00004097static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
4099 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
4100 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
4101 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
4102 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
4103 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
4104 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
4105 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
4106 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
4107 {"reload", imp_reload, METH_O, doc_reload},
4108 {"cache_from_source", (PyCFunction)imp_cache_from_source,
4109 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
4110 {"source_from_cache", (PyCFunction)imp_source_from_cache,
4111 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
4112 /* The rest are obsolete */
4113 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
4114 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
4115 {"init_builtin", imp_init_builtin, METH_VARARGS},
4116 {"init_frozen", imp_init_frozen, METH_VARARGS},
4117 {"is_builtin", imp_is_builtin, METH_VARARGS},
4118 {"is_frozen", imp_is_frozen, METH_VARARGS},
4119 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004120#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004122#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 {"load_package", imp_load_package, METH_VARARGS},
4124 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07004125 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004127};
4128
Guido van Rossum1a8791e1998-08-04 22:46:29 +00004129static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004130setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 PyObject *v;
4133 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 v = PyLong_FromLong((long)value);
4136 err = PyDict_SetItemString(d, name, v);
4137 Py_XDECREF(v);
4138 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004139}
4140
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004141typedef struct {
4142 PyObject_HEAD
4143} NullImporter;
4144
4145static int
4146NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
4147{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004148#ifndef MS_WINDOWS
4149 PyObject *path;
4150 struct stat statbuf;
4151 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4154 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004155
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004156 if (!PyArg_ParseTuple(args, "O&:NullImporter",
4157 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004159
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004160 if (PyBytes_GET_SIZE(path) == 0) {
4161 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 PyErr_SetString(PyExc_ImportError, "empty pathname");
4163 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004165
4166 rv = stat(PyBytes_AS_STRING(path), &statbuf);
4167 Py_DECREF(path);
4168 if (rv == 0) {
4169 /* it exists */
4170 if (S_ISDIR(statbuf.st_mode)) {
4171 /* it's a directory */
4172 PyErr_SetString(PyExc_ImportError, "existing directory");
4173 return -1;
4174 }
4175 }
4176#else /* MS_WINDOWS */
4177 PyObject *pathobj;
4178 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00004179 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004180
4181 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4182 return -1;
4183
4184 if (!PyArg_ParseTuple(args, "U:NullImporter",
4185 &pathobj))
4186 return -1;
4187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004188 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004189 PyErr_SetString(PyExc_ImportError, "empty pathname");
4190 return -1;
4191 }
4192
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00004193 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004194 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004195 return -1;
4196 /* see issue1293 and issue3677:
4197 * stat() on Windows doesn't recognise paths like
4198 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
4199 */
4200 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004201 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004202 if (rv != INVALID_FILE_ATTRIBUTES) {
4203 /* it exists */
4204 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
4205 /* it's a directory */
4206 PyErr_SetString(PyExc_ImportError, "existing directory");
4207 return -1;
4208 }
4209 }
4210#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004212}
4213
4214static PyObject *
4215NullImporter_find_module(NullImporter *self, PyObject *args)
4216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004218}
4219
4220static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
4222 "Always return None"
4223 },
4224 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004225};
4226
4227
Christian Heimes9cd17752007-11-18 19:35:23 +00004228PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 PyVarObject_HEAD_INIT(NULL, 0)
4230 "imp.NullImporter", /*tp_name*/
4231 sizeof(NullImporter), /*tp_basicsize*/
4232 0, /*tp_itemsize*/
4233 0, /*tp_dealloc*/
4234 0, /*tp_print*/
4235 0, /*tp_getattr*/
4236 0, /*tp_setattr*/
4237 0, /*tp_reserved*/
4238 0, /*tp_repr*/
4239 0, /*tp_as_number*/
4240 0, /*tp_as_sequence*/
4241 0, /*tp_as_mapping*/
4242 0, /*tp_hash */
4243 0, /*tp_call*/
4244 0, /*tp_str*/
4245 0, /*tp_getattro*/
4246 0, /*tp_setattro*/
4247 0, /*tp_as_buffer*/
4248 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4249 "Null importer object", /* tp_doc */
4250 0, /* tp_traverse */
4251 0, /* tp_clear */
4252 0, /* tp_richcompare */
4253 0, /* tp_weaklistoffset */
4254 0, /* tp_iter */
4255 0, /* tp_iternext */
4256 NullImporter_methods, /* tp_methods */
4257 0, /* tp_members */
4258 0, /* tp_getset */
4259 0, /* tp_base */
4260 0, /* tp_dict */
4261 0, /* tp_descr_get */
4262 0, /* tp_descr_set */
4263 0, /* tp_dictoffset */
4264 (initproc)NullImporter_init, /* tp_init */
4265 0, /* tp_alloc */
4266 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004267};
4268
Martin v. Löwis1a214512008-06-11 05:26:20 +00004269static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 PyModuleDef_HEAD_INIT,
4271 "imp",
4272 doc_imp,
4273 0,
4274 imp_methods,
4275 NULL,
4276 NULL,
4277 NULL,
4278 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004279};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004280
Jason Tishler6bc06ec2003-09-04 11:59:50 +00004281PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004282PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 if (PyType_Ready(&PyNullImporter_Type) < 0)
4287 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 m = PyModule_Create(&impmodule);
4290 if (m == NULL)
4291 goto failure;
4292 d = PyModule_GetDict(m);
4293 if (d == NULL)
4294 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
4297 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
4298 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
4299 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
4300 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
4301 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
4302 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4303 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4304 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4305 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 Py_INCREF(&PyNullImporter_Type);
4308 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4309 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004310 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004311 Py_XDECREF(m);
4312 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004313}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004314
4315
Guido van Rossumb18618d2000-05-03 23:44:39 +00004316/* API for embedding applications that want to add their own entries
4317 to the table of built-in modules. This should normally be called
4318 *before* Py_Initialize(). When the table resize fails, -1 is
4319 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004320
4321 After a similar function by Just van Rossum. */
4322
4323int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004324PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004326 static struct _inittab *our_copy = NULL;
4327 struct _inittab *p;
4328 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 /* Count the number of entries in both tables */
4331 for (n = 0; newtab[n].name != NULL; n++)
4332 ;
4333 if (n == 0)
4334 return 0; /* Nothing to do */
4335 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4336 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 /* Allocate new memory for the combined table */
4339 p = our_copy;
4340 PyMem_RESIZE(p, struct _inittab, i+n+1);
4341 if (p == NULL)
4342 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 /* Copy the tables into the new memory */
4345 if (our_copy != PyImport_Inittab)
4346 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4347 PyImport_Inittab = our_copy = p;
4348 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004351}
4352
4353/* Shorthand to add a single entry given a name and a function */
4354
4355int
Brett Cannona826f322009-04-02 03:41:46 +00004356PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 newtab[0].name = (char *)name;
4363 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004366}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004367
4368#ifdef __cplusplus
4369}
4370#endif