blob: aaf649f858a6de81c8c8ab6c64e8b77255091054 [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)
Tim Peters36515e22001-11-18 04:06:29 +0000105*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000106
Nick Coghlancd419ab2010-09-11 00:39:25 +0000107/* MAGIC must change whenever the bytecode emitted by the compiler may no
108 longer be understood by older implementations of the eval loop (usually
109 due to the addition of new opcodes)
Victor Stinner2f42ae52011-03-20 00:41:24 +0100110 TAG and PYC_TAG_UNICODE must change for each major Python release. The magic
111 number will take care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112*/
Benjamin Peterson48deae12011-06-03 17:50:16 -0500113#define QUOTE(arg) #arg
114#define STRIFY(name) QUOTE(name)
115#define MAJOR STRIFY(PY_MAJOR_VERSION)
116#define MINOR STRIFY(PY_MINOR_VERSION)
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000117#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Benjamin Peterson48deae12011-06-03 17:50:16 -0500118#define TAG "cpython-" MAJOR MINOR;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000119#define CACHEDIR "__pycache__"
Victor Stinnerc9abda02011-03-14 13:33:46 -0400120static const Py_UNICODE CACHEDIR_UNICODE[] = {
121 '_', '_', 'p', 'y', 'c', 'a', 'c', 'h', 'e', '_', '_', '\0'};
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000123static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000124static const char *pyc_tag = TAG;
Victor Stinner2f42ae52011-03-20 00:41:24 +0100125static const Py_UNICODE PYC_TAG_UNICODE[] = {
Benjamin Peterson48deae12011-06-03 17:50:16 -0500126 'c', 'p', 'y', 't', 'h', 'o', 'n', '-', PY_MAJOR_VERSION + 48, PY_MINOR_VERSION + 48, '\0'};
127#undef QUOTE
128#undef STRIFY
129#undef MAJOR
130#undef MINOR
Guido van Rossum96774c12000-05-01 20:19:08 +0000131
Victor Stinner95872862011-03-07 18:20:56 +0100132/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000134
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200135/* Function from Parser/tokenizer.c */
136extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
137
Guido van Rossum771c6c81997-10-31 18:37:24 +0000138/* This table is defined in config.c: */
139extern struct _inittab _PyImport_Inittab[];
140
141struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000142
Guido van Rossumed1170e1999-12-20 21:23:41 +0000143/* these tables define the module suffixes that Python recognizes */
144struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000145
Guido van Rossumed1170e1999-12-20 21:23:41 +0000146static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000148#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000150#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 {".pyc", "rb", PY_COMPILED},
152 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153};
154
Victor Stinnerd0296212011-03-14 14:04:10 -0400155static PyObject *initstr = NULL;
156
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000158/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159
160void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000161_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 const struct filedescr *scan;
164 struct filedescr *filetab;
165 int countD = 0;
166 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000167
Victor Stinnerd0296212011-03-14 14:04:10 -0400168 initstr = PyUnicode_InternFromString("__init__");
169 if (initstr == NULL)
170 Py_FatalError("Can't initialize import variables");
171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 /* prepare _PyImport_Filetab: copy entries from
173 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
174 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000175#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
177 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000178#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
180 ++countS;
181 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
182 if (filetab == NULL)
183 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000184#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 memcpy(filetab, _PyImport_DynLoadFiletab,
186 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000187#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 memcpy(filetab + countD, _PyImport_StandardFiletab,
189 countS * sizeof(struct filedescr));
190 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 if (Py_OptimizeFlag) {
195 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
196 for (; filetab->suffix != NULL; filetab++) {
197 if (strcmp(filetab->suffix, ".pyc") == 0)
198 filetab->suffix = ".pyo";
199 }
200 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201}
202
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203void
Just van Rossum52e14d62002-12-30 22:08:05 +0000204_PyImportHooks_Init(void)
205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 PyObject *v, *path_hooks = NULL, *zimpimport;
207 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 /* adding sys.path_hooks and sys.path_importer_cache, setting up
210 zipimport */
211 if (PyType_Ready(&PyNullImporter_Type) < 0)
212 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (Py_VerboseFlag)
215 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 v = PyList_New(0);
218 if (v == NULL)
219 goto error;
220 err = PySys_SetObject("meta_path", v);
221 Py_DECREF(v);
222 if (err)
223 goto error;
224 v = PyDict_New();
225 if (v == NULL)
226 goto error;
227 err = PySys_SetObject("path_importer_cache", v);
228 Py_DECREF(v);
229 if (err)
230 goto error;
231 path_hooks = PyList_New(0);
232 if (path_hooks == NULL)
233 goto error;
234 err = PySys_SetObject("path_hooks", path_hooks);
235 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000236 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyErr_Print();
238 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
239 "path_importer_cache, or NullImporter failed"
240 );
241 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 zimpimport = PyImport_ImportModule("zipimport");
244 if (zimpimport == NULL) {
245 PyErr_Clear(); /* No zip import module -- okay */
246 if (Py_VerboseFlag)
247 PySys_WriteStderr("# can't import zipimport\n");
248 }
249 else {
250 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
251 "zipimporter");
252 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
273void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000274_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 Py_XDECREF(extensions);
277 extensions = NULL;
278 PyMem_DEL(_PyImport_Filetab);
279 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000280}
281
282
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000283/* Locking primitives to prevent parallel imports of the same module
284 in different threads to return with a partially loaded module.
285 These calls are serialized by the global interpreter lock. */
286
287#ifdef WITH_THREAD
288
Guido van Rossum49b56061998-10-01 20:42:43 +0000289#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290
Guido van Rossum65d5b571998-12-21 19:32:43 +0000291static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000292static long import_lock_thread = -1;
293static int import_lock_level = 0;
294
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000295void
296_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 long me = PyThread_get_thread_ident();
299 if (me == -1)
300 return; /* Too bad */
301 if (import_lock == NULL) {
302 import_lock = PyThread_allocate_lock();
303 if (import_lock == NULL)
304 return; /* Nothing much we can do. */
305 }
306 if (import_lock_thread == me) {
307 import_lock_level++;
308 return;
309 }
310 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
311 {
312 PyThreadState *tstate = PyEval_SaveThread();
313 PyThread_acquire_lock(import_lock, 1);
314 PyEval_RestoreThread(tstate);
315 }
316 import_lock_thread = me;
317 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000318}
319
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000320int
321_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 long me = PyThread_get_thread_ident();
324 if (me == -1 || import_lock == NULL)
325 return 0; /* Too bad */
326 if (import_lock_thread != me)
327 return -1;
328 import_lock_level--;
329 if (import_lock_level == 0) {
330 import_lock_thread = -1;
331 PyThread_release_lock(import_lock);
332 }
333 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000334}
335
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000336/* This function is called from PyOS_AfterFork to ensure that newly
337 created child processes do not share locks with the parent.
338 We now acquire the import lock around fork() calls but on some platforms
339 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000340
341void
342_PyImport_ReInitLock(void)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (import_lock != NULL)
345 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000346 if (import_lock_level > 1) {
347 /* Forked as a side effect of import */
348 long me = PyThread_get_thread_ident();
349 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100350 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000351 import_lock_thread = me;
352 import_lock_level--;
353 } else {
354 import_lock_thread = -1;
355 import_lock_level = 0;
356 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000357}
358
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000359#endif
360
Tim Peters69232342001-08-30 05:16:13 +0000361static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000362imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000363{
Tim Peters69232342001-08-30 05:16:13 +0000364#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000366#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000368#endif
369}
370
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000371static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000372imp_acquire_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 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000376#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 Py_INCREF(Py_None);
378 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000379}
380
381static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000382imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000383{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000384#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (_PyImport_ReleaseLock() < 0) {
386 PyErr_SetString(PyExc_RuntimeError,
387 "not holding the import lock");
388 return NULL;
389 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000390#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_INCREF(Py_None);
392 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000393}
394
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395static void
396imp_modules_reloading_clear(void)
397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 PyInterpreterState *interp = PyThreadState_Get()->interp;
399 if (interp->modules_reloading != NULL)
400 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401}
402
Guido van Rossum25ce5661997-08-02 03:10:38 +0000403/* Helper for sys */
404
405PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000406PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyInterpreterState *interp = PyThreadState_GET()->interp;
409 if (interp->modules == NULL)
410 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
411 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412}
413
Guido van Rossum3f5da241990-12-20 15:06:42 +0000414
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415/* List of names to clear in sys */
416static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 "path", "argv", "ps1", "ps2",
418 "last_type", "last_value", "last_traceback",
419 "path_hooks", "path_importer_cache", "meta_path",
420 /* misc stuff */
421 "flags", "float_info",
422 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000423};
424
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000425static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 "stdin", "__stdin__",
427 "stdout", "__stdout__",
428 "stderr", "__stderr__",
429 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430};
431
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000432
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000433/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000434
Guido van Rossum3f5da241990-12-20 15:06:42 +0000435void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000436PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject *key, *value, *dict;
440 PyInterpreterState *interp = PyThreadState_GET()->interp;
441 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (modules == NULL)
444 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 /* Delete some special variables first. These are common
447 places where user values hide and people complain when their
448 destructors fail. Since the modules containing them are
449 deleted *last* of all, they would come too late in the normal
450 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 value = PyDict_GetItemString(modules, "builtins");
453 if (value != NULL && PyModule_Check(value)) {
454 dict = PyModule_GetDict(value);
455 if (Py_VerboseFlag)
456 PySys_WriteStderr("# clear builtins._\n");
457 PyDict_SetItemString(dict, "_", Py_None);
458 }
459 value = PyDict_GetItemString(modules, "sys");
460 if (value != NULL && PyModule_Check(value)) {
461 char **p;
462 PyObject *v;
463 dict = PyModule_GetDict(value);
464 for (p = sys_deletes; *p != NULL; p++) {
465 if (Py_VerboseFlag)
466 PySys_WriteStderr("# clear sys.%s\n", *p);
467 PyDict_SetItemString(dict, *p, Py_None);
468 }
469 for (p = sys_files; *p != NULL; p+=2) {
470 if (Py_VerboseFlag)
471 PySys_WriteStderr("# restore sys.%s\n", *p);
472 v = PyDict_GetItemString(dict, *(p+1));
473 if (v == NULL)
474 v = Py_None;
475 PyDict_SetItemString(dict, *p, v);
476 }
477 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 /* First, delete __main__ */
480 value = PyDict_GetItemString(modules, "__main__");
481 if (value != NULL && PyModule_Check(value)) {
482 if (Py_VerboseFlag)
483 PySys_WriteStderr("# cleanup __main__\n");
484 _PyModule_Clear(value);
485 PyDict_SetItemString(modules, "__main__", Py_None);
486 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* The special treatment of "builtins" here is because even
489 when it's not referenced as a module, its dictionary is
490 referenced by almost every module's __builtins__. Since
491 deleting a module clears its dictionary (even if there are
492 references left to it), we need to delete the "builtins"
493 module last. Likewise, we don't delete sys until the very
494 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 Also note that we 'delete' modules by replacing their entry
497 in the modules dict with None, rather than really deleting
498 them; this avoids a rehash of the modules dictionary and
499 also marks them as "non existent" so they won't be
500 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* Next, repeatedly delete modules with a reference count of
503 one (skipping builtins and sys) and delete them */
504 do {
505 ndone = 0;
506 pos = 0;
507 while (PyDict_Next(modules, &pos, &key, &value)) {
508 if (value->ob_refcnt != 1)
509 continue;
510 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100511 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100513 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 continue;
515 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100516 PySys_FormatStderr(
517 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 _PyModule_Clear(value);
519 PyDict_SetItem(modules, key, Py_None);
520 ndone++;
521 }
522 }
523 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Next, delete all modules (still skipping builtins and sys) */
526 pos = 0;
527 while (PyDict_Next(modules, &pos, &key, &value)) {
528 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100529 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100531 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 continue;
533 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100534 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 _PyModule_Clear(value);
536 PyDict_SetItem(modules, key, Py_None);
537 }
538 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* Next, delete sys and builtins (in that order) */
541 value = PyDict_GetItemString(modules, "sys");
542 if (value != NULL && PyModule_Check(value)) {
543 if (Py_VerboseFlag)
544 PySys_WriteStderr("# cleanup sys\n");
545 _PyModule_Clear(value);
546 PyDict_SetItemString(modules, "sys", Py_None);
547 }
548 value = PyDict_GetItemString(modules, "builtins");
549 if (value != NULL && PyModule_Check(value)) {
550 if (Py_VerboseFlag)
551 PySys_WriteStderr("# cleanup builtins\n");
552 _PyModule_Clear(value);
553 PyDict_SetItemString(modules, "builtins", Py_None);
554 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 /* Finally, clear and delete the modules directory */
557 PyDict_Clear(modules);
558 interp->modules = NULL;
559 Py_DECREF(modules);
560 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000561}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000562
563
Barry Warsaw28a691b2010-04-17 00:19:56 +0000564/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565
566long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000567PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570}
571
572
Barry Warsaw28a691b2010-04-17 00:19:56 +0000573const char *
574PyImport_GetMagicTag(void)
575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000577}
578
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579/* Magic for extension modules (built-in as well as dynamically
580 loaded). To prevent initializing an extension module more than
581 once, we keep a static dictionary 'extensions' keyed by module name
582 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000583 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100584 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585 immediately after the module initialization function succeeds. A
586 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100587 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000588
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000589 Modules which do support multiple initialization set their m_size
590 field to a non-negative number (indicating the size of the
591 module-specific state). They are still recorded in the extensions
592 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000593*/
594
595int
Victor Stinner95872862011-03-07 18:20:56 +0100596_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
597 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 PyObject *modules, *dict;
600 struct PyModuleDef *def;
601 if (extensions == NULL) {
602 extensions = PyDict_New();
603 if (extensions == NULL)
604 return -1;
605 }
606 if (mod == NULL || !PyModule_Check(mod)) {
607 PyErr_BadInternalCall();
608 return -1;
609 }
610 def = PyModule_GetDef(mod);
611 if (!def) {
612 PyErr_BadInternalCall();
613 return -1;
614 }
615 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100616 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 return -1;
618 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100619 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return -1;
621 }
622 if (def->m_size == -1) {
623 if (def->m_base.m_copy) {
624 /* Somebody already imported the module,
625 likely under a different name.
626 XXX this should really not happen. */
627 Py_DECREF(def->m_base.m_copy);
628 def->m_base.m_copy = NULL;
629 }
630 dict = PyModule_GetDict(mod);
631 if (dict == NULL)
632 return -1;
633 def->m_base.m_copy = PyDict_Copy(dict);
634 if (def->m_base.m_copy == NULL)
635 return -1;
636 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000637 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639}
640
Victor Stinner49d3f252010-10-17 01:24:53 +0000641int
642_PyImport_FixupBuiltin(PyObject *mod, char *name)
643{
644 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100645 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100646 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100647 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000648 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100649 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
650 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000651 return res;
652}
653
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100655_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyObject *mod, *mdict;
658 PyModuleDef* def;
659 if (extensions == NULL)
660 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000661 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (def == NULL)
663 return NULL;
664 if (def->m_size == -1) {
665 /* Module does not support repeated initialization */
666 if (def->m_base.m_copy == NULL)
667 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100668 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (mod == NULL)
670 return NULL;
671 mdict = PyModule_GetDict(mod);
672 if (mdict == NULL)
673 return NULL;
674 if (PyDict_Update(mdict, def->m_base.m_copy))
675 return NULL;
676 }
677 else {
678 if (def->m_base.m_init == NULL)
679 return NULL;
680 mod = def->m_base.m_init();
681 if (mod == NULL)
682 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100683 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 Py_DECREF(mod);
685 }
686 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100687 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 Py_DECREF(mod);
689 return NULL;
690 }
691 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100692 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 name, filename);
694 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000695
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696}
697
Victor Stinner49d3f252010-10-17 01:24:53 +0000698PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000699_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000700{
Victor Stinner95872862011-03-07 18:20:56 +0100701 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100702 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100703 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000704 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100705 res = _PyImport_FindExtensionObject(nameobj, nameobj);
706 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000707 return res;
708}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000709
710/* Get the module object corresponding to a module name.
711 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000712 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000713 Because the former action is most common, THIS DOES NOT RETURN A
714 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715
Guido van Rossum79f25d91997-04-29 20:08:16 +0000716PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000717PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyObject *modules = PyImport_GetModuleDict();
720 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721
Victor Stinner27ee0892011-03-04 12:57:09 +0000722 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyModule_Check(m))
724 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000725 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (m == NULL)
727 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000728 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 Py_DECREF(m);
730 return NULL;
731 }
732 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735}
736
Victor Stinner27ee0892011-03-04 12:57:09 +0000737PyObject *
738PyImport_AddModule(const char *name)
739{
740 PyObject *nameobj, *module;
741 nameobj = PyUnicode_FromString(name);
742 if (nameobj == NULL)
743 return NULL;
744 module = PyImport_AddModuleObject(nameobj);
745 Py_DECREF(nameobj);
746 return module;
747}
748
749
Tim Peters1cd70172004-08-02 03:52:12 +0000750/* Remove name from sys.modules, if it's there. */
751static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000752remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000755 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000757 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 Py_FatalError("import: deleting existing key in"
759 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000760}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000761
Victor Stinnerc9abda02011-03-14 13:33:46 -0400762static PyObject * get_sourcefile(PyObject *filename);
763static PyObject *make_source_pathname(PyObject *pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +0100764static PyObject* make_compiled_pathname(Py_UNICODE *pathname, int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000765
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000766/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000767 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
768 * removed from sys.modules, to avoid leaving damaged module objects
769 * in sys.modules. The caller may wish to restore the original
770 * module object (if any) in this case; PyImport_ReloadModule is an
771 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000772 *
773 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
774 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000775 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000776PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000777PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return PyImport_ExecCodeModuleWithPathnames(
780 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000781}
782
783PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000784PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 return PyImport_ExecCodeModuleWithPathnames(
787 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000788}
789
790PyObject *
791PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000793{
Victor Stinner27ee0892011-03-04 12:57:09 +0000794 PyObject *m = NULL;
795 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
796
797 nameobj = PyUnicode_FromString(name);
798 if (nameobj == NULL)
799 return NULL;
800
801 if (pathname != NULL) {
802 pathobj = PyUnicode_DecodeFSDefault(pathname);
803 if (pathobj == NULL)
804 goto error;
805 } else
806 pathobj = NULL;
807 if (cpathname != NULL) {
808 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
809 if (cpathobj == NULL)
810 goto error;
811 } else
812 cpathobj = NULL;
813 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
814error:
815 Py_DECREF(nameobj);
816 Py_XDECREF(pathobj);
817 Py_XDECREF(cpathobj);
818 return m;
819}
820
821PyObject*
822PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
823 PyObject *cpathname)
824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 PyObject *modules = PyImport_GetModuleDict();
826 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000827
Victor Stinner27ee0892011-03-04 12:57:09 +0000828 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (m == NULL)
830 return NULL;
831 /* If the module is being reloaded, we get the old module back
832 and re-use its dict to exec the new code. */
833 d = PyModule_GetDict(m);
834 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
835 if (PyDict_SetItemString(d, "__builtins__",
836 PyEval_GetBuiltins()) != 0)
837 goto error;
838 }
839 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400841 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (v == NULL)
843 PyErr_Clear();
844 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000845 else
846 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (v == NULL) {
848 v = ((PyCodeObject *)co)->co_filename;
849 Py_INCREF(v);
850 }
851 if (PyDict_SetItemString(d, "__file__", v) != 0)
852 PyErr_Clear(); /* Not important enough to report */
853 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000856 if (cpathname != NULL)
857 v = cpathname;
858 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (PyDict_SetItemString(d, "__cached__", v) != 0)
861 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000862
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000863 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (v == NULL)
865 goto error;
866 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000867
Victor Stinner27ee0892011-03-04 12:57:09 +0000868 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000870 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 name);
872 return NULL;
873 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000878
879 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 remove_module(name);
881 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882}
883
884
Barry Warsaw28a691b2010-04-17 00:19:56 +0000885/* Like strrchr(string, '/') but searches for the rightmost of either SEP
886 or ALTSEP, if the latter is defined.
887*/
Victor Stinnerc9abda02011-03-14 13:33:46 -0400888static Py_UNICODE*
Victor Stinner2f42ae52011-03-20 00:41:24 +0100889rightmost_sep(Py_UNICODE *s)
Victor Stinnerc9abda02011-03-14 13:33:46 -0400890{
891 Py_UNICODE *found, c;
892 for (found = NULL; (c = *s); s++) {
893 if (c == SEP
894#ifdef ALTSEP
895 || c == ALTSEP
896#endif
897 )
898 {
899 found = s;
900 }
901 }
902 return found;
903}
904
905
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000906/* Given a pathname for a Python source file, fill a buffer with the
907 pathname for the corresponding compiled file. Return the pathname
908 for the compiled file, or NULL if there's no space in the buffer.
Victor Stinner2f42ae52011-03-20 00:41:24 +0100909 Doesn't set an exception.
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000910
Victor Stinner2f42ae52011-03-20 00:41:24 +0100911 foo.py -> __pycache__/foo.<tag>.pyc */
912
913static PyObject*
914make_compiled_pathname(Py_UNICODE *pathname, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100916 Py_UNICODE buf[MAXPATHLEN];
917 size_t buflen = (size_t)MAXPATHLEN;
918 size_t len = Py_UNICODE_strlen(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 size_t i, save;
Victor Stinner2f42ae52011-03-20 00:41:24 +0100920 Py_UNICODE *pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Sanity check that the buffer has roughly enough space to hold what
924 will eventually be the full path to the compiled file. The 5 extra
925 bytes include the slash afer __pycache__, the two extra dots, the
926 extra trailing character ('c' or 'o') and null. This isn't exact
927 because the contents of the buffer can affect how many actual
928 characters of the string get into the buffer. We'll do a final
929 sanity check before writing the extension to ensure we do not
930 overflow the buffer.
931 */
Victor Stinner2f42ae52011-03-20 00:41:24 +0100932 if (len + Py_UNICODE_strlen(CACHEDIR_UNICODE) + Py_UNICODE_strlen(PYC_TAG_UNICODE) + 5 > buflen)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Find the last path separator and copy everything from the start of
936 the source string up to and including the separator.
937 */
Victor Stinner2f42ae52011-03-20 00:41:24 +0100938 pos = rightmost_sep(pathname);
939 if (pos == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 i = 0;
941 }
942 else {
943 sep = *pos;
944 i = pos - pathname + 1;
Victor Stinner2f42ae52011-03-20 00:41:24 +0100945 Py_UNICODE_strncpy(buf, pathname, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 save = i;
949 buf[i++] = '\0';
950 /* Add __pycache__/ */
Victor Stinner2f42ae52011-03-20 00:41:24 +0100951 Py_UNICODE_strcat(buf, CACHEDIR_UNICODE);
952 i += Py_UNICODE_strlen(CACHEDIR_UNICODE) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 buf[i++] = sep;
Victor Stinnerccbf4752011-03-14 15:05:12 -0400954 buf[i] = '\0';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Add the base filename, but remove the .py or .pyw extension, since
956 the tag name must go before the extension.
957 */
Victor Stinner2f42ae52011-03-20 00:41:24 +0100958 Py_UNICODE_strcat(buf, pathname + save);
Victor Stinnerccbf4752011-03-14 15:05:12 -0400959 pos = Py_UNICODE_strrchr(buf + i, '.');
Victor Stinner2f42ae52011-03-20 00:41:24 +0100960 if (pos != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 *++pos = '\0';
Victor Stinner2f42ae52011-03-20 00:41:24 +0100962 Py_UNICODE_strcat(buf, PYC_TAG_UNICODE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* The length test above assumes that we're only adding one character
964 to the end of what would normally be the extension. What if there
965 is no extension, or the string ends in '.' or '.p', and otherwise
966 fills the buffer? By appending 4 more characters onto the string
967 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 As a simple example, let's say buflen=32 and the input string is
970 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 which is false and so the name mangling would continue. This would
975 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
980 We can even handle an input string of say 'xxxxx' above because
981 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
982 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 which is 32 characters including the nul, and thus fits in the
987 buffer. However, an input string of 'xxxxxx' would yield a result
988 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 which is 33 characters long (including the nul), thus overflowing
993 the buffer, even though the first test would fail, i.e.: the input
994 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 The reason the first test fails but we still overflow the buffer is
997 that the test above only expects to add one extra character to be
998 added to the extension, and here we're adding three (pyc). We
999 don't add the first dot, so that reclaims one of expected
1000 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
1001 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 The best we can do is ensure that we still have enough room in the
1004 target buffer before we write the extension. Because it's always
1005 only the extension that can cause the overflow, and never the other
1006 path bytes we've written, it's sufficient to just do one more test
1007 here. Still, the assertion that follows can't hurt.
1008 */
Barry Warsaw28a691b2010-04-17 00:19:56 +00001009#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001011#endif
Victor Stinner2f42ae52011-03-20 00:41:24 +01001012 len = Py_UNICODE_strlen(buf);
1013 if (len + 5 > buflen)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001015 buf[len] = '.'; len++;
1016 buf[len] = 'p'; len++;
1017 buf[len] = 'y'; len++;
1018 buf[len] = debug ? 'c' : 'o'; len++;
1019 assert(len <= buflen);
1020 return PyUnicode_FromUnicode(buf, len);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001021}
1022
1023
Barry Warsaw28a691b2010-04-17 00:19:56 +00001024/* Given a pathname to a Python byte compiled file, return the path to the
1025 source file, if the path matches the PEP 3147 format. This does not check
1026 for any file existence, however, if the pyc file name does not match PEP
1027 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001028 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029
Victor Stinnerc9abda02011-03-14 13:33:46 -04001030 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
1031
1032static PyObject*
1033make_source_pathname(PyObject *pathobj)
Barry Warsaw28a691b2010-04-17 00:19:56 +00001034{
Victor Stinnerc9abda02011-03-14 13:33:46 -04001035 Py_UNICODE buf[MAXPATHLEN];
1036 Py_UNICODE *pathname;
1037 Py_UNICODE *left, *right, *dot0, *dot1, sep;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 size_t i, j;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001039
1040 if (PyUnicode_GET_SIZE(pathobj) > MAXPATHLEN)
1041 return NULL;
1042 pathname = PyUnicode_AS_UNICODE(pathobj);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Look back two slashes from the end. In between these two slashes
1045 must be the string __pycache__ or this is not a PEP 3147 style
1046 path. It's possible for there to be only one slash.
1047 */
Victor Stinner2f42ae52011-03-20 00:41:24 +01001048 right = rightmost_sep(pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001049 if (right == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return NULL;
1051 sep = *right;
1052 *right = '\0';
Victor Stinner2f42ae52011-03-20 00:41:24 +01001053 left = rightmost_sep(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 *right = sep;
1055 if (left == NULL)
1056 left = pathname;
1057 else
1058 left++;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001059 if (right-left != Py_UNICODE_strlen(CACHEDIR_UNICODE) ||
1060 Py_UNICODE_strncmp(left, CACHEDIR_UNICODE, right-left) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 /* Now verify that the path component to the right of the last slash
1064 has two dots in it.
1065 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001066 if ((dot0 = Py_UNICODE_strchr(right + 1, '.')) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001068 if ((dot1 = Py_UNICODE_strchr(dot0 + 1, '.')) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 return NULL;
1070 /* Too many dots? */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001071 if (Py_UNICODE_strchr(dot1 + 1, '.') != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* This is a PEP 3147 path. Start by copying everything from the
1075 start of pathname up to and including the leftmost slash. Then
1076 copy the file's basename, removing the magic tag and adding a .py
1077 suffix.
1078 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001079 Py_UNICODE_strncpy(buf, pathname, (i=left-pathname));
1080 Py_UNICODE_strncpy(buf+i, right+1, (j=dot0-right));
1081 buf[i+j] = 'p';
1082 buf[i+j+1] = 'y';
1083 return PyUnicode_FromUnicode(buf, i+j+2);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001084}
1085
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001086/* Given a pathname for a Python source file, its time of last
1087 modification, and a pathname for a compiled file, check whether the
1088 compiled file represents the same version of the source. If so,
1089 return a FILE pointer for the compiled file, positioned just after
1090 the header; if not, return NULL.
1091 Doesn't set an exception. */
1092
1093static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001094check_compiled_module(PyObject *pathname, time_t mtime, PyObject *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 FILE *fp;
1097 long magic;
1098 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001099
Victor Stinner2f42ae52011-03-20 00:41:24 +01001100 fp = _Py_fopen(cpathname, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (fp == NULL)
1102 return NULL;
1103 magic = PyMarshal_ReadLongFromFile(fp);
1104 if (magic != pyc_magic) {
1105 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001106 PySys_FormatStderr("# %R has bad magic\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 fclose(fp);
1108 return NULL;
1109 }
1110 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1111 if (pyc_mtime != mtime) {
1112 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001113 PySys_FormatStderr("# %R has bad mtime\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 fclose(fp);
1115 return NULL;
1116 }
1117 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001118 PySys_FormatStderr("# %R matches %R\n", cpathname, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001120}
1121
1122
1123/* Read a code object from a file and check it for validity */
1124
Guido van Rossum79f25d91997-04-29 20:08:16 +00001125static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001126read_compiled_module(PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 co = PyMarshal_ReadLastObjectFromFile(fp);
1131 if (co == NULL)
1132 return NULL;
1133 if (!PyCode_Check(co)) {
1134 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001135 "Non-code object in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 Py_DECREF(co);
1137 return NULL;
1138 }
1139 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001140}
1141
1142
1143/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001144 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001145
Guido van Rossum79f25d91997-04-29 20:08:16 +00001146static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001147load_compiled_module(PyObject *name, PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 long magic;
1150 PyCodeObject *co;
1151 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 magic = PyMarshal_ReadLongFromFile(fp);
1154 if (magic != pyc_magic) {
1155 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001156 "Bad magic number in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return NULL;
1158 }
1159 (void) PyMarshal_ReadLongFromFile(fp);
1160 co = read_compiled_module(cpathname, fp);
1161 if (co == NULL)
1162 return NULL;
1163 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001164 PySys_FormatStderr("import %U # precompiled from %R\n",
1165 name, cpathname);
1166 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1167 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171}
1172
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001173/* Parse a source file and return the corresponding code object */
1174
Guido van Rossum79f25d91997-04-29 20:08:16 +00001175static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001176parse_source_module(PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001177{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001178 PyCodeObject *co;
1179 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 mod_ty mod;
1181 PyCompilerFlags flags;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001182 PyArena *arena;
1183
1184 pathbytes = PyUnicode_EncodeFSDefault(pathname);
1185 if (pathbytes == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001187
Victor Stinner2f42ae52011-03-20 00:41:24 +01001188 arena = PyArena_New();
1189 if (arena == NULL) {
1190 Py_DECREF(pathbytes);
1191 return NULL;
1192 }
1193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 flags.cf_flags = 0;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001195 mod = PyParser_ASTFromFile(fp, PyBytes_AS_STRING(pathbytes), NULL,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_file_input, 0, 0, &flags,
1197 NULL, arena);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001198 if (mod != NULL)
1199 co = PyAST_Compile(mod, PyBytes_AS_STRING(pathbytes), NULL, arena);
1200 else
1201 co = NULL;
1202 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyArena_Free(arena);
1204 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001205}
1206
Guido van Rossum55a83382000-09-20 20:31:38 +00001207/* Helper to open a bytecode file for writing in exclusive mode */
1208
Victor Stinner783c82c2011-04-20 03:27:51 +02001209#ifndef MS_WINDOWS
Guido van Rossum55a83382000-09-20 20:31:38 +00001210static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001211open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001212{
1213#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* Use O_EXCL to avoid a race condition when another process tries to
1215 write the same file. When that happens, our open() call fails,
1216 which is just fine (since it's only a cache).
1217 XXX If the file exists and is writable but the directory is not
1218 writable, the file will never be written. Oh well.
1219 */
1220 int fd;
1221 (void) unlink(filename);
1222 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001223#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001225#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001226#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001228#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001230#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 );
1232 if (fd < 0)
1233 return NULL;
1234 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001235#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /* Best we can do -- on Windows this can't happen anyway */
1237 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001238#endif
1239}
Victor Stinner783c82c2011-04-20 03:27:51 +02001240#endif
Guido van Rossum55a83382000-09-20 20:31:38 +00001241
1242
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243/* Write a compiled module to a file, placing the time of last
1244 modification of its source into the header.
1245 Errors are ignored, if a write error occurs an attempt is made to
1246 remove the file. */
1247
1248static void
Victor Stinner2f42ae52011-03-20 00:41:24 +01001249write_compiled_module(PyCodeObject *co, PyObject *cpathname,
1250 struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001254#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001256#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1258 mode_t dirmode = (srcstat->st_mode |
1259 S_IXUSR | S_IXGRP | S_IXOTH |
1260 S_IWUSR | S_IWGRP | S_IWOTH);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001261 PyObject *dirbytes;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001262#endif
Victor Stinner783c82c2011-04-20 03:27:51 +02001263#ifdef MS_WINDOWS
1264 int fd;
1265#else
1266 PyObject *cpathbytes;
1267#endif
1268 PyObject *dirname;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001269 Py_UNICODE *dirsep;
1270 int res, ok;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* Ensure that the __pycache__ directory exists. */
Victor Stinner2f42ae52011-03-20 00:41:24 +01001273 dirsep = rightmost_sep(PyUnicode_AS_UNICODE(cpathname));
1274 if (dirsep == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001276 PySys_FormatStderr("# no %s path found %R\n", CACHEDIR, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return;
1278 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001279 dirname = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(cpathname),
1280 dirsep - PyUnicode_AS_UNICODE(cpathname));
1281 if (dirname == NULL) {
1282 PyErr_Clear();
1283 return;
1284 }
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001285
1286#ifdef MS_WINDOWS
Victor Stinner2f42ae52011-03-20 00:41:24 +01001287 res = CreateDirectoryW(PyUnicode_AS_UNICODE(dirname), NULL);
1288 ok = (res != 0);
1289 if (!ok && GetLastError() == ERROR_ALREADY_EXISTS)
1290 ok = 1;
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001291#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001292 dirbytes = PyUnicode_EncodeFSDefault(dirname);
1293 if (dirbytes == NULL) {
1294 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 return;
1296 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001297 res = mkdir(PyBytes_AS_STRING(dirbytes), dirmode);
1298 Py_DECREF(dirbytes);
1299 if (0 <= res)
1300 ok = 1;
1301 else
1302 ok = (errno == EEXIST);
1303#endif
1304 if (!ok) {
1305 if (Py_VerboseFlag)
1306 PySys_FormatStderr("# cannot create cache dir %R\n", dirname);
1307 Py_DECREF(dirname);
1308 return;
1309 }
1310 Py_DECREF(dirname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001311
Victor Stinner783c82c2011-04-20 03:27:51 +02001312#ifdef MS_WINDOWS
1313 (void)DeleteFileW(PyUnicode_AS_UNICODE(cpathname));
1314 fd = _wopen(PyUnicode_AS_UNICODE(cpathname),
1315 O_EXCL | O_CREAT | O_WRONLY | O_TRUNC | O_BINARY,
1316 mode);
1317 if (0 <= fd)
1318 fp = fdopen(fd, "wb");
1319 else
1320 fp = NULL;
1321#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001322 cpathbytes = PyUnicode_EncodeFSDefault(cpathname);
1323 if (cpathbytes == NULL) {
1324 PyErr_Clear();
1325 return;
1326 }
1327
1328 fp = open_exclusive(PyBytes_AS_STRING(cpathbytes), mode);
Victor Stinner783c82c2011-04-20 03:27:51 +02001329#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (fp == NULL) {
1331 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001332 PySys_FormatStderr(
1333 "# can't create %R\n", cpathname);
Victor Stinner783c82c2011-04-20 03:27:51 +02001334#ifndef MS_WINDOWS
Victor Stinner2f42ae52011-03-20 00:41:24 +01001335 Py_DECREF(cpathbytes);
Victor Stinner783c82c2011-04-20 03:27:51 +02001336#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 return;
1338 }
1339 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1340 /* First write a 0 for mtime */
1341 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1342 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1343 if (fflush(fp) != 0 || ferror(fp)) {
1344 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001345 PySys_FormatStderr("# can't write %R\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* Don't keep partial file */
1347 fclose(fp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001348#ifdef MS_WINDOWS
1349 (void)DeleteFileW(PyUnicode_AS_UNICODE(cpathname));
1350#else
1351 (void) unlink(PyBytes_AS_STRING(cpathbytes));
Victor Stinner2f42ae52011-03-20 00:41:24 +01001352 Py_DECREF(cpathbytes);
Victor Stinner783c82c2011-04-20 03:27:51 +02001353#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 return;
1355 }
Victor Stinner783c82c2011-04-20 03:27:51 +02001356#ifndef MS_WINDOWS
Victor Stinner2f42ae52011-03-20 00:41:24 +01001357 Py_DECREF(cpathbytes);
Victor Stinner783c82c2011-04-20 03:27:51 +02001358#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* Now write the true mtime */
1360 fseek(fp, 4L, 0);
1361 assert(mtime < LONG_MAX);
1362 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1363 fflush(fp);
1364 fclose(fp);
1365 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001366 PySys_FormatStderr("# wrote %R\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001367}
1368
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001369static void
1370update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 PyObject *constants, *tmp;
1373 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (PyUnicode_Compare(co->co_filename, oldname))
1376 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 tmp = co->co_filename;
1379 co->co_filename = newname;
1380 Py_INCREF(co->co_filename);
1381 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 constants = co->co_consts;
1384 n = PyTuple_GET_SIZE(constants);
1385 for (i = 0; i < n; i++) {
1386 tmp = PyTuple_GET_ITEM(constants, i);
1387 if (PyCode_Check(tmp))
1388 update_code_filenames((PyCodeObject *)tmp,
1389 oldname, newname);
1390 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001391}
1392
Victor Stinner2f42ae52011-03-20 00:41:24 +01001393static void
1394update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001395{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001396 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001397
Victor Stinner2f42ae52011-03-20 00:41:24 +01001398 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1399 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 oldname = co->co_filename;
1402 Py_INCREF(oldname);
1403 update_code_filenames(co, oldname, newname);
1404 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001405}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001406
Brett Cannon442c9b92011-03-23 16:14:42 -07001407static PyObject *
1408imp_fix_co_filename(PyObject *self, PyObject *args)
1409{
1410 PyObject *co;
1411 PyObject *file_path;
1412
1413 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1414 return NULL;
1415
1416 if (!PyCode_Check(co)) {
1417 PyErr_SetString(PyExc_TypeError,
1418 "first argument must be a code object");
1419 return NULL;
1420 }
1421
1422 if (!PyUnicode_Check(file_path)) {
1423 PyErr_SetString(PyExc_TypeError,
1424 "second argument must be a string");
1425 return NULL;
1426 }
1427
1428 update_compiled_module((PyCodeObject*)co, file_path);
1429
1430 Py_RETURN_NONE;
1431}
1432
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001433/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001434 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1435 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001436
Guido van Rossum79f25d91997-04-29 20:08:16 +00001437static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001438load_source_module(PyObject *name, PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 struct stat st;
1441 FILE *fpc;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001442 PyObject *cpathname = NULL, *cpathbytes = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyCodeObject *co;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001444 PyObject *m = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (fstat(fileno(fp), &st) != 0) {
1447 PyErr_Format(PyExc_RuntimeError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001448 "unable to get file status from %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001450 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 }
Fred Drake4c82b232000-06-30 16:18:57 +00001452#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* Python's .pyc timestamp handling presumes that the timestamp fits
1454 in 4 bytes. This will be fine until sometime in the year 2038,
1455 when a 4-byte signed time_t will overflow.
1456 */
1457 if (st.st_mtime >> 32) {
1458 PyErr_SetString(PyExc_OverflowError,
1459 "modification time overflows a 4 byte field");
Victor Stinner2f42ae52011-03-20 00:41:24 +01001460 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 }
Fred Drake4c82b232000-06-30 16:18:57 +00001462#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 cpathname = make_compiled_pathname(
Victor Stinner2f42ae52011-03-20 00:41:24 +01001464 PyUnicode_AS_UNICODE(pathname),
1465 !Py_OptimizeFlag);
1466
1467 if (cpathname != NULL)
1468 fpc = check_compiled_module(pathname, st.st_mtime, cpathname);
1469 else
1470 fpc = NULL;
1471
1472 if (fpc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 co = read_compiled_module(cpathname, fpc);
1474 fclose(fpc);
1475 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001476 goto error;
1477 update_compiled_module(co, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001479 PySys_FormatStderr("import %U # precompiled from %R\n",
1480 name, cpathname);
1481 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1482 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 }
1484 else {
1485 co = parse_source_module(pathname, fp);
1486 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001487 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001489 PySys_FormatStderr("import %U # from %R\n",
Victor Stinner98dbba52011-03-14 15:15:47 -04001490 name, pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001491 if (cpathname != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1493 if (ro == NULL || !PyObject_IsTrue(ro))
1494 write_compiled_module(co, cpathname, &st);
1495 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001496 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1497 pathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001500
Victor Stinner2f42ae52011-03-20 00:41:24 +01001501error:
1502 Py_XDECREF(cpathbytes);
1503 Py_XDECREF(cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001505}
1506
Christian Heimes3b06e532008-01-07 20:12:44 +00001507/* Get source file -> unicode or None
1508 * Returns the path to the py file if available, else the given path
1509 */
1510static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001511get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 Py_ssize_t len;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001514 Py_UNICODE *fileuni;
1515 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001517
Victor Stinnerc9abda02011-03-14 13:33:46 -04001518 len = PyUnicode_GET_SIZE(filename);
1519 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001521
Victor Stinnerc9abda02011-03-14 13:33:46 -04001522 /* don't match *.pyc or *.pyo? */
1523 fileuni = PyUnicode_AS_UNICODE(filename);
1524 if (len < 5
1525 || fileuni[len-4] != '.'
1526 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1527 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1528 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 /* Start by trying to turn PEP 3147 path into source path. If that
1531 * fails, just chop off the trailing character, i.e. legacy pyc path
1532 * to py.
1533 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001534 py = make_source_pathname(filename);
1535 if (py == NULL) {
1536 PyErr_Clear();
1537 py = PyUnicode_FromUnicode(fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001539 if (py == NULL)
1540 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001541
Victor Stinnerc9abda02011-03-14 13:33:46 -04001542 if (_Py_stat(py, &statbuf) == 0 && S_ISREG(statbuf.st_mode))
1543 return py;
1544 Py_DECREF(py);
1545 goto unchanged;
1546
1547error:
1548 PyErr_Clear();
1549unchanged:
1550 Py_INCREF(filename);
1551 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001552}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001553
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001554/* Forward */
Victor Stinner41c5fec2011-03-13 21:46:30 -04001555static PyObject *load_module(PyObject *, FILE *, PyObject *, int, PyObject *);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001556static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001557 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001558static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001559
1560/* Load a package and return its module object WITH INCREMENTED
1561 REFERENCE COUNT */
1562
1563static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001564load_package(PyObject *name, PyObject *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001565{
Victor Stinner41c5fec2011-03-13 21:46:30 -04001566 PyObject *m, *d, *bufobj;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001567 PyObject *file = NULL, *path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 int err;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001569 FILE *fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001571
Victor Stinnerc9abda02011-03-14 13:33:46 -04001572 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (m == NULL)
1574 return NULL;
1575 if (Py_VerboseFlag)
Victor Stinner98dbba52011-03-14 15:15:47 -04001576 PySys_FormatStderr("import %U # directory %R\n",
1577 name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 file = get_sourcefile(pathname);
1579 if (file == NULL)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001580 return NULL;
1581 path_list = Py_BuildValue("[O]", file);
1582 if (path_list == NULL) {
1583 Py_DECREF(file);
1584 return NULL;
1585 }
1586 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 err = PyDict_SetItemString(d, "__file__", file);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001588 Py_DECREF(file);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (err == 0)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001590 err = PyDict_SetItemString(d, "__path__", path_list);
1591 if (err != 0) {
1592 Py_DECREF(path_list);
1593 return NULL;
1594 }
Victor Stinner533d7832011-03-14 13:22:54 -04001595 fdp = find_module(name, initstr, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001596 &bufobj, &fp, NULL);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001597 Py_DECREF(path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (fdp == NULL) {
1599 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1600 PyErr_Clear();
1601 Py_INCREF(m);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001602 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 }
1604 else
Victor Stinnerc9abda02011-03-14 13:33:46 -04001605 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001607 m = load_module(name, fp, bufobj, fdp->type, NULL);
1608 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (fp != NULL)
1610 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001612}
1613
1614
1615/* Helper to test for built-in module */
1616
1617static int
Victor Stinner95872862011-03-07 18:20:56 +01001618is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001619{
Victor Stinner95872862011-03-07 18:20:56 +01001620 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001622 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1623 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (PyImport_Inittab[i].initfunc == NULL)
1625 return -1;
1626 else
1627 return 1;
1628 }
1629 }
1630 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001631}
1632
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001633
Just van Rossum52e14d62002-12-30 22:08:05 +00001634/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1635 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001636 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001637 that can handle the path item. Return None if no hook could;
1638 this tells our caller it should fall back to the builtin
1639 import mechanism. Cache the result in path_importer_cache.
1640 Returns a borrowed reference. */
1641
1642static PyObject *
1643get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PyObject *importer;
1647 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 /* These conditions are the caller's responsibility: */
1650 assert(PyList_Check(path_hooks));
1651 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 nhooks = PyList_Size(path_hooks);
1654 if (nhooks < 0)
1655 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 importer = PyDict_GetItem(path_importer_cache, p);
1658 if (importer != NULL)
1659 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* set path_importer_cache[p] to None to avoid recursion */
1662 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1663 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 for (j = 0; j < nhooks; j++) {
1666 PyObject *hook = PyList_GetItem(path_hooks, j);
1667 if (hook == NULL)
1668 return NULL;
1669 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1670 if (importer != NULL)
1671 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1674 return NULL;
1675 }
1676 PyErr_Clear();
1677 }
1678 if (importer == NULL) {
1679 importer = PyObject_CallFunctionObjArgs(
1680 (PyObject *)&PyNullImporter_Type, p, NULL
1681 );
1682 if (importer == NULL) {
1683 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1684 PyErr_Clear();
1685 return Py_None;
1686 }
1687 }
1688 }
1689 if (importer != NULL) {
1690 int err = PyDict_SetItem(path_importer_cache, p, importer);
1691 Py_DECREF(importer);
1692 if (err != 0)
1693 return NULL;
1694 }
1695 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001696}
1697
Christian Heimes9cd17752007-11-18 19:35:23 +00001698PyAPI_FUNC(PyObject *)
1699PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1703 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1704 importer = get_path_importer(path_importer_cache,
1705 path_hooks, path);
1706 }
1707 }
1708 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1709 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001710}
1711
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001712/* Search the path (default sys.path) for a module. Return the
1713 corresponding filedescr struct, and (via return arguments) the
1714 pathname and an open file. Return NULL if the module is not found. */
1715
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001716#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001717extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1718 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001719#endif
1720
Victor Stinner547a2a62011-03-20 03:07:28 +01001721/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001722static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001723static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001724static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001725
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001726/* Get the path of a module: get its importer and call importer.find_module()
1727 hook, or check if the module if a package (if path/__init__.py exists).
1728
1729 -1: error: a Python error occurred
1730 0: ignore: an error occurred because of invalid data, but the error is not
1731 important enough to be reported.
1732 1: get path: module not found, but *buf contains its path
1733 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1734 and *buf is the path */
1735
1736static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001737find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001738 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001739 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001740{
Victor Stinner2fd76e42011-03-14 15:19:39 -04001741 Py_UNICODE buf[MAXPATHLEN+1];
1742 Py_ssize_t buflen = MAXPATHLEN+1;
1743 PyObject *path_unicode, *filename;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001744 Py_ssize_t len;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001745 struct stat statbuf;
1746 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1747
1748 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001749 Py_INCREF(path);
1750 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001751 }
1752 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001753 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1754 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1755 if (path_unicode == NULL)
1756 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001757 }
1758 else
1759 return 0;
1760
Victor Stinner2fd76e42011-03-14 15:19:39 -04001761 len = PyUnicode_GET_SIZE(path_unicode);
1762 if (len + 2 + PyUnicode_GET_SIZE(name) + MAXSUFFIXSIZE >= buflen) {
1763 Py_DECREF(path_unicode);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001764 return 0; /* Too long */
1765 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001766 Py_UNICODE_strcpy(buf, PyUnicode_AS_UNICODE(path_unicode));
1767 Py_DECREF(path_unicode);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001768
Victor Stinner2fd76e42011-03-14 15:19:39 -04001769 if (Py_UNICODE_strlen(buf) != len)
1770 return 0; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001771
1772 /* sys.path_hooks import hook */
1773 if (p_loader != NULL) {
1774 PyObject *importer;
1775
1776 importer = get_path_importer(path_importer_cache,
1777 path_hooks, path);
1778 if (importer == NULL) {
1779 return -1;
1780 }
1781 /* Note: importer is a borrowed reference */
1782 if (importer != Py_None) {
1783 PyObject *loader;
1784 loader = PyObject_CallMethod(importer,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001785 "find_module", "O", fullname);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001786 if (loader == NULL)
1787 return -1; /* error */
1788 if (loader != Py_None) {
1789 /* a loader was found */
1790 *p_loader = loader;
1791 *p_fd = &importhookdescr;
1792 return 2;
1793 }
1794 Py_DECREF(loader);
1795 return 0;
1796 }
1797 }
1798 /* no hook was found, use builtin import */
1799
1800 if (len > 0 && buf[len-1] != SEP
1801#ifdef ALTSEP
1802 && buf[len-1] != ALTSEP
1803#endif
1804 )
1805 buf[len++] = SEP;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001806 Py_UNICODE_strcpy(buf+len, PyUnicode_AS_UNICODE(name));
1807 len += PyUnicode_GET_SIZE(name);
1808
1809 filename = PyUnicode_FromUnicode(buf, len);
1810 if (filename == NULL)
1811 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001812
1813 /* Check for package import (buf holds a directory name,
1814 and there's an __init__ module in that directory */
1815#ifdef HAVE_STAT
Victor Stinner2fd76e42011-03-14 15:19:39 -04001816 if (_Py_stat(filename, &statbuf) == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001817 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1818 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001819 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001820
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001821 match = case_ok(filename, 0, name);
1822 if (match < 0) {
1823 Py_DECREF(filename);
1824 return -1;
1825 }
1826 if (match) { /* case matches */
1827 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001828 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04001829 *p_fd = &fd_package;
1830 return 2;
1831 }
1832 else {
1833 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001834 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001835 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001836 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001837 if (err) {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001838 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04001839 return -1;
Victor Stinner547a2a62011-03-20 03:07:28 +01001840 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001841 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001842 }
1843 }
1844#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001845 *p_path = filename;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001846 return 1;
1847}
1848
1849/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001850 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001851
1852 If the module is found, return a file descriptor, write the path in
1853 *p_filename, write the pointer to the file object into *p_fp, and (if
1854 p_loader is not NULL) the loader into *p_loader.
1855
1856 Otherwise, raise an exception and return NULL. */
1857
Victor Stinner37580282011-03-20 01:34:43 +01001858static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001859find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001860 PyObject *search_path_list, PyObject *path_hooks,
1861 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001862 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 struct filedescr *fdp = NULL;
1866 char *filemode;
1867 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001868 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001869 int match;
Victor Stinner53dc7352011-03-20 01:50:21 +01001870
Victor Stinner37580282011-03-20 01:34:43 +01001871 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001873 PyObject *path;
1874 int ok;
1875
1876 path = PyList_GetItem(search_path_list, i);
1877 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001879
Victor Stinner2fd76e42011-03-14 15:19:39 -04001880 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001881 ok = find_module_path(fullname, name, path,
1882 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001883 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001884 if (ok < 0)
1885 return NULL;
1886 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001888 if (ok == 2) {
1889 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001890 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001891 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 filemode = fdp->mode;
1895 if (filemode[0] == 'U')
1896 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001897
Victor Stinner2fd76e42011-03-14 15:19:39 -04001898 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1899 if (filename == NULL) {
1900 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001901 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001902 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001903
1904 if (Py_VerboseFlag > 1)
1905 PySys_FormatStderr("# trying %R\n", filename);
1906
1907 fp = _Py_fopen(filename, filemode);
1908 if (fp == NULL) {
1909 Py_DECREF(filename);
1910 continue;
1911 }
1912 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
1913 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001914 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001915 Py_DECREF(filename);
1916 return NULL;
1917 }
1918 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001919 Py_DECREF(prefix);
1920 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04001921 *p_fp = fp;
1922 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001924 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04001925
1926 fclose(fp);
1927 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001929 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001931 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04001932 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04001933 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001934}
1935
Victor Stinner37580282011-03-20 01:34:43 +01001936/* Find a module:
1937
1938 - try find_module() of each sys.meta_path hook
1939 - try find_frozen()
1940 - try is_builtin()
1941 - try _PyWin_FindRegisteredModule() (Windows only)
1942 - otherwise, call find_module_path_list() with search_path_list (if not
1943 NULL) or sys.path
1944
Victor Stinner2fd76e42011-03-14 15:19:39 -04001945 fullname can be NULL, but only if p_loader is NULL.
1946
Victor Stinner37580282011-03-20 01:34:43 +01001947 Return:
1948
1949 - &fd_builtin (C_BUILTIN) if it is a builtin
1950 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04001951 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01001952 if it is a package
1953 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
1954 importer loader was found
1955 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
1956 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04001957 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01001958 - NULL on error
1959
Victor Stinner2fd76e42011-03-14 15:19:39 -04001960 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
1961 Eg. *p_path is set to NULL for a builtin package.
1962*/
Victor Stinner37580282011-03-20 01:34:43 +01001963
1964static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001965find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001966 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01001967{
1968 Py_ssize_t i, npath;
1969 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1970 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1971 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01001972
Victor Stinner2fd76e42011-03-14 15:19:39 -04001973 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01001974 *p_fp = NULL;
1975 if (p_loader != NULL)
1976 *p_loader = NULL;
1977
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001978 if (PyUnicode_GET_SIZE(name) > MAXPATHLEN) {
Victor Stinner37580282011-03-20 01:34:43 +01001979 PyErr_SetString(PyExc_OverflowError,
1980 "module name is too long");
1981 return NULL;
1982 }
1983
1984 /* sys.meta_path import hook */
1985 if (p_loader != NULL) {
1986 PyObject *meta_path;
1987
1988 meta_path = PySys_GetObject("meta_path");
1989 if (meta_path == NULL || !PyList_Check(meta_path)) {
1990 PyErr_SetString(PyExc_ImportError,
1991 "sys.meta_path must be a list of "
1992 "import hooks");
1993 return NULL;
1994 }
1995 Py_INCREF(meta_path); /* zap guard */
1996 npath = PyList_Size(meta_path);
1997 for (i = 0; i < npath; i++) {
1998 PyObject *loader;
1999 PyObject *hook = PyList_GetItem(meta_path, i);
2000 loader = PyObject_CallMethod(hook, "find_module",
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002001 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01002002 search_path_list != NULL ?
2003 search_path_list : Py_None);
2004 if (loader == NULL) {
2005 Py_DECREF(meta_path);
2006 return NULL; /* true error */
2007 }
2008 if (loader != Py_None) {
2009 /* a loader was found */
2010 *p_loader = loader;
2011 Py_DECREF(meta_path);
2012 return &importhookdescr;
2013 }
2014 Py_DECREF(loader);
2015 }
2016 Py_DECREF(meta_path);
2017 }
2018
Victor Stinnerdf75a022011-03-14 13:40:04 -04002019 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002020 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01002021
2022 if (search_path_list == NULL) {
2023#ifdef MS_COREDLL
2024 FILE *fp;
2025 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01002026#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04002027 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01002028 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01002029#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04002030 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01002031 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01002032 *p_fp = fp;
2033 return fdp;
2034 }
2035 else if (PyErr_Occurred())
2036 return NULL;
2037#endif
Victor Stinner37580282011-03-20 01:34:43 +01002038 search_path_list = PySys_GetObject("path");
2039 }
2040
2041 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
2042 PyErr_SetString(PyExc_ImportError,
2043 "sys.path must be a list of directory names");
2044 return NULL;
2045 }
2046
2047 path_hooks = PySys_GetObject("path_hooks");
2048 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
2049 PyErr_SetString(PyExc_ImportError,
2050 "sys.path_hooks must be a list of "
2051 "import hooks");
2052 return NULL;
2053 }
2054 path_importer_cache = PySys_GetObject("path_importer_cache");
2055 if (path_importer_cache == NULL ||
2056 !PyDict_Check(path_importer_cache)) {
2057 PyErr_SetString(PyExc_ImportError,
2058 "sys.path_importer_cache must be a dict");
2059 return NULL;
2060 }
2061
2062 return find_module_path_list(fullname, name,
2063 search_path_list, path_hooks,
2064 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002065 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01002066}
2067
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002068/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00002069 * The arguments here are tricky, best shown by example:
2070 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2071 * ^ ^ ^ ^
2072 * |--------------------- buf ---------------------|
2073 * |------------------- len ------------------|
2074 * |------ name -------|
2075 * |----- namelen -----|
2076 * buf is the full path, but len only counts up to (& exclusive of) the
2077 * extension. name is the module name, also exclusive of extension.
2078 *
2079 * We've already done a successful stat() or fopen() on buf, so know that
2080 * there's some match, possibly case-insensitive.
2081 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002082 * case_bytes() is to return 1 if there's a case-sensitive match for
2083 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00002084 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00002085 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002086 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00002087 * on platforms with case-insensitive filesystems. It's trivial to implement
2088 * for case-sensitive filesystems. It's pretty much a cross-platform
2089 * nightmare for systems with case-insensitive filesystems.
2090 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00002091
Tim Peters50d8d372001-02-28 05:34:27 +00002092/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002093 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00002094 */
Jason Tishler7961aa62005-05-20 00:56:54 +00002095#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002096#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00002097
Tim Peters50d8d372001-02-28 05:34:27 +00002098#elif defined(DJGPP)
2099#include <dir.h>
2100
Jason Tishler7961aa62005-05-20 00:56:54 +00002101#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00002102#include <sys/types.h>
2103#include <dirent.h>
2104
Andrew MacIntyred9400542002-02-26 11:41:34 +00002105#elif defined(PYOS_OS2)
2106#define INCL_DOS
2107#define INCL_DOSERRORS
2108#define INCL_NOPMAPI
2109#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00002110#endif
2111
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002112#if defined(DJGPP) \
2113 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
2114 && defined(HAVE_DIRENT_H)) \
2115 || defined(PYOS_OS2)
2116# define USE_CASE_OK_BYTES
2117#endif
2118
2119
2120#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00002121static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002122case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002123{
Tim Peters50d8d372001-02-28 05:34:27 +00002124/* Pick a platform-specific implementation; the sequence of #if's here should
2125 * match the sequence just above.
2126 */
2127
Tim Peters50d8d372001-02-28 05:34:27 +00002128/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002129#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 struct ffblk ffblk;
2131 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (Py_GETENV("PYTHONCASEOK") != NULL)
2134 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2137 if (done) {
2138 PyErr_Format(PyExc_NameError,
2139 "Can't find file for module %.100s\n(filename %.300s)",
2140 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01002141 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 }
2143 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002144
Jason Tishler7961aa62005-05-20 00:56:54 +00002145/* new-fangled macintosh (macosx) or Cygwin */
2146#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 DIR *dirp;
2148 struct dirent *dp;
2149 char dirname[MAXPATHLEN + 1];
2150 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (Py_GETENV("PYTHONCASEOK") != NULL)
2153 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* Copy the dir component into dirname; substitute "." if empty */
2156 if (dirlen <= 0) {
2157 dirname[0] = '.';
2158 dirname[1] = '\0';
2159 }
2160 else {
2161 assert(dirlen <= MAXPATHLEN);
2162 memcpy(dirname, buf, dirlen);
2163 dirname[dirlen] = '\0';
2164 }
2165 /* Open the directory and search the entries for an exact match. */
2166 dirp = opendir(dirname);
2167 if (dirp) {
2168 char *nameWithExt = buf + len - namelen;
2169 while ((dp = readdir(dirp)) != NULL) {
2170 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002171#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002173#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002175#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (thislen >= namelen &&
2177 strcmp(dp->d_name, nameWithExt) == 0) {
2178 (void)closedir(dirp);
2179 return 1; /* Found */
2180 }
2181 }
2182 (void)closedir(dirp);
2183 }
2184 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002185
Andrew MacIntyred9400542002-02-26 11:41:34 +00002186/* OS/2 */
2187#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 HDIR hdir = 1;
2189 ULONG srchcnt = 1;
2190 FILEFINDBUF3 ffbuf;
2191 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (Py_GETENV("PYTHONCASEOK") != NULL)
2194 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 rc = DosFindFirst(buf,
2197 &hdir,
2198 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2199 &ffbuf, sizeof(ffbuf),
2200 &srchcnt,
2201 FIL_STANDARD);
2202 if (rc != NO_ERROR)
2203 return 0;
2204 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002205
Tim Peters50d8d372001-02-28 05:34:27 +00002206/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2207#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002208# error "USE_CASE_OK_BYTES is not correctly defined"
2209#endif
2210}
2211#endif
2212
2213/*
2214 * Check if a filename case matchs the name case. We've already done a
2215 * successful stat() or fopen() on buf, so know that there's some match,
2216 * possibly case-insensitive.
2217 *
2218 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
2219 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
2220 * if envar PYTHONCASEOK exists.
2221 *
2222 * case_ok() is used to implement case-sensitive import semantics even
2223 * on platforms with case-insensitive filesystems. It's trivial to implement
2224 * for case-sensitive filesystems. It's pretty much a cross-platform
2225 * nightmare for systems with case-insensitive filesystems.
2226 */
2227
2228static int
2229case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
2230{
2231#ifdef MS_WINDOWS
2232 WIN32_FIND_DATAW data;
2233 HANDLE h;
2234 int cmp;
2235
2236 if (Py_GETENV("PYTHONCASEOK") != NULL)
2237 return 1;
2238
2239 h = FindFirstFileW(PyUnicode_AS_UNICODE(filename), &data);
2240 if (h == INVALID_HANDLE_VALUE) {
2241 PyErr_Format(PyExc_NameError,
2242 "Can't find file for module %R\n(filename %R)",
2243 name, filename);
2244 return 0;
2245 }
2246 FindClose(h);
2247 cmp = wcsncmp(data.cFileName,
2248 PyUnicode_AS_UNICODE(name),
2249 PyUnicode_GET_SIZE(name));
2250 return cmp == 0;
2251#elif defined(USE_CASE_OK_BYTES)
2252 int match;
2253 PyObject *filebytes, *namebytes;
2254 filebytes = PyUnicode_EncodeFSDefault(filename);
2255 if (filebytes == NULL)
2256 return -1;
2257 namebytes = PyUnicode_EncodeFSDefault(name);
2258 if (namebytes == NULL) {
2259 Py_DECREF(filebytes);
2260 return -1;
2261 }
2262 match = case_bytes(
2263 PyBytes_AS_STRING(filebytes),
2264 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01002265 PyBytes_GET_SIZE(namebytes),
2266 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002267 Py_DECREF(filebytes);
2268 Py_DECREF(namebytes);
2269 return match;
2270#else
2271 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002273
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002274#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002275}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002276
Guido van Rossum197346f1997-10-31 18:38:52 +00002277#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002278
Victor Stinner547a2a62011-03-20 03:07:28 +01002279/* Helper to look for __init__.py or __init__.py[co] in potential package.
2280 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00002281static int
Victor Stinner547a2a62011-03-20 03:07:28 +01002282find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00002283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01002285 PyObject *filename;
2286 int match;
Guido van Rossum197346f1997-10-31 18:38:52 +00002287
Victor Stinner547a2a62011-03-20 03:07:28 +01002288 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
2289 if (filename == NULL)
2290 return -1;
2291 if (_Py_stat(filename, &statbuf) == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002292 /* 3=len(".py") */
2293 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002294 if (match < 0) {
2295 Py_DECREF(filename);
2296 return -1;
2297 }
2298 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002299 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 return 1;
2301 }
2302 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002303 Py_DECREF(filename);
2304
2305 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
2306 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
2307 if (filename == NULL)
2308 return -1;
2309 if (_Py_stat(filename, &statbuf) == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002310 /* 4=len(".pyc") */
2311 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002312 if (match < 0) {
2313 Py_DECREF(filename);
2314 return -1;
2315 }
2316 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002317 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return 1;
2319 }
2320 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002321 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002323}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002324
Guido van Rossum197346f1997-10-31 18:38:52 +00002325#endif /* HAVE_STAT */
2326
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002327
Victor Stinner95872862011-03-07 18:20:56 +01002328static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002329
Victor Stinner44c6c152010-08-09 00:59:10 +00002330static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002331load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002332{
2333 PyObject *m, *modules;
2334 int err;
2335
Victor Stinner44c6c152010-08-09 00:59:10 +00002336 if (type == C_BUILTIN)
2337 err = init_builtin(name);
2338 else
Victor Stinner95872862011-03-07 18:20:56 +01002339 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002340 if (err < 0)
2341 return NULL;
2342 if (err == 0) {
2343 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002344 "Purported %s module %R not found",
2345 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002346 name);
2347 return NULL;
2348 }
2349
2350 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002351 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002352 if (m == NULL) {
2353 PyErr_Format(
2354 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002355 "%s module %R not properly initialized",
2356 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002357 name);
2358 return NULL;
2359 }
2360 Py_INCREF(m);
2361 return m;
2362}
2363
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002364/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002365 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002366
Guido van Rossum79f25d91997-04-29 20:08:16 +00002367static PyObject *
Victor Stinner41c5fec2011-03-13 21:46:30 -04002368load_module(PyObject *name, FILE *fp, PyObject *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* First check that there's an open file (if we need one) */
2373 switch (type) {
2374 case PY_SOURCE:
2375 case PY_COMPILED:
2376 if (fp == NULL) {
2377 PyErr_Format(PyExc_ValueError,
Victor Stinner41c5fec2011-03-13 21:46:30 -04002378 "file object required for import (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 type);
2380 return NULL;
2381 }
2382 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002385
Victor Stinner41c5fec2011-03-13 21:46:30 -04002386 case PY_SOURCE:
2387 m = load_source_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002389
Victor Stinner41c5fec2011-03-13 21:46:30 -04002390 case PY_COMPILED:
2391 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002393
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002394#ifdef HAVE_DYNAMIC_LOADING
Victor Stinner41c5fec2011-03-13 21:46:30 -04002395 case C_EXTENSION:
2396 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002398#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002399
Victor Stinner41c5fec2011-03-13 21:46:30 -04002400 case PKG_DIRECTORY:
2401 m = load_package(name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 case C_BUILTIN:
Victor Stinner41c5fec2011-03-13 21:46:30 -04002405 case PY_FROZEN:
2406 m = load_builtin(name, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 case IMP_HOOK: {
2410 if (loader == NULL) {
2411 PyErr_SetString(PyExc_ImportError,
2412 "import hook without loader");
2413 return NULL;
2414 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04002415 m = PyObject_CallMethod(loader, "load_module", "O", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 break;
2417 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 default:
2420 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002421 "Don't know how to import %R (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 name, type);
2423 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002428}
2429
2430
2431/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002432 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002433 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002434
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002435static int
Victor Stinner95872862011-03-07 18:20:56 +01002436init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002439
Victor Stinner95872862011-03-07 18:20:56 +01002440 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 for (p = PyImport_Inittab; p->name != NULL; p++) {
2444 PyObject *mod;
Victor Stinner95872862011-03-07 18:20:56 +01002445 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 if (p->initfunc == NULL) {
2447 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002448 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 name);
2450 return -1;
2451 }
2452 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002453 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 mod = (*p->initfunc)();
2455 if (mod == 0)
2456 return -1;
Victor Stinner95872862011-03-07 18:20:56 +01002457 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 return -1;
2459 /* FixupExtension has put the module into sys.modules,
2460 so we can release our own reference. */
2461 Py_DECREF(mod);
2462 return 1;
2463 }
2464 }
2465 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002466}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002467
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002468
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002469/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002470
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002471static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002472find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002475
Victor Stinner53dc7352011-03-20 01:50:21 +01002476 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 for (p = PyImport_FrozenModules; ; p++) {
2480 if (p->name == NULL)
2481 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002482 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 break;
2484 }
2485 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002486}
2487
Guido van Rossum79f25d91997-04-29 20:08:16 +00002488static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002489get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 struct _frozen *p = find_frozen(name);
2492 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (p == NULL) {
2495 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002496 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 name);
2498 return NULL;
2499 }
2500 if (p->code == NULL) {
2501 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002502 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 name);
2504 return NULL;
2505 }
2506 size = p->size;
2507 if (size < 0)
2508 size = -size;
2509 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002510}
2511
Brett Cannon8d110132009-03-15 02:20:16 +00002512static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002513is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 struct _frozen *p = find_frozen(name);
2516 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if (p == NULL) {
2519 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002520 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 name);
2522 return NULL;
2523 }
Brett Cannon8d110132009-03-15 02:20:16 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 if (size < 0)
2528 Py_RETURN_TRUE;
2529 else
2530 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002531}
2532
2533
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002534/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002535 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002536 an exception set if the initialization failed.
2537 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002538
2539int
Victor Stinner53dc7352011-03-20 01:50:21 +01002540PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002541{
Victor Stinner53dc7352011-03-20 01:50:21 +01002542 struct _frozen *p;
2543 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 int ispackage;
2545 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002546
Victor Stinner53dc7352011-03-20 01:50:21 +01002547 p = find_frozen(name);
2548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 if (p == NULL)
2550 return 0;
2551 if (p->code == NULL) {
2552 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002553 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 name);
2555 return -1;
2556 }
2557 size = p->size;
2558 ispackage = (size < 0);
2559 if (ispackage)
2560 size = -size;
2561 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002562 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 name, ispackage ? " package" : "");
2564 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2565 if (co == NULL)
2566 return -1;
2567 if (!PyCode_Check(co)) {
2568 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002569 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 name);
2571 goto err_return;
2572 }
2573 if (ispackage) {
2574 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002575 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002577 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (m == NULL)
2579 goto err_return;
2580 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 l = PyList_New(1);
2582 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 goto err_return;
2584 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002585 Py_INCREF(name);
2586 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 err = PyDict_SetItemString(d, "__path__", l);
2588 Py_DECREF(l);
2589 if (err != 0)
2590 goto err_return;
2591 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002592 path = PyUnicode_FromString("<frozen>");
2593 if (path == NULL)
2594 goto err_return;
2595 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2596 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 if (m == NULL)
2598 goto err_return;
2599 Py_DECREF(co);
2600 Py_DECREF(m);
2601 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002602err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 Py_DECREF(co);
2604 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002605}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002606
Victor Stinner53dc7352011-03-20 01:50:21 +01002607int
2608PyImport_ImportFrozenModule(char *name)
2609{
2610 PyObject *nameobj;
2611 int ret;
2612 nameobj = PyUnicode_InternFromString(name);
2613 if (nameobj == NULL)
2614 return -1;
2615 ret = PyImport_ImportFrozenModuleObject(nameobj);
2616 Py_DECREF(nameobj);
2617 return ret;
2618}
2619
Guido van Rossum74e6a111994-08-29 12:54:38 +00002620
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002621/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002622 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002623
Guido van Rossum79f25d91997-04-29 20:08:16 +00002624PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002625PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyObject *pname;
2628 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 pname = PyUnicode_FromString(name);
2631 if (pname == NULL)
2632 return NULL;
2633 result = PyImport_Import(pname);
2634 Py_DECREF(pname);
2635 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002636}
2637
Christian Heimes072c0f12008-01-03 23:01:04 +00002638/* Import a module without blocking
2639 *
2640 * At first it tries to fetch the module from sys.modules. If the module was
2641 * never loaded before it loads it with PyImport_ImportModule() unless another
2642 * thread holds the import lock. In the latter case the function raises an
2643 * ImportError instead of blocking.
2644 *
2645 * Returns the module object with incremented ref count.
2646 */
2647PyObject *
2648PyImport_ImportModuleNoBlock(const char *name)
2649{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002650 PyObject *nameobj, *modules, *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 /* Try to get the module from sys.modules[name] */
2654 modules = PyImport_GetModuleDict();
2655 if (modules == NULL)
2656 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002657
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002658 nameobj = PyUnicode_FromString(name);
2659 if (nameobj == NULL)
2660 return NULL;
2661 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002663 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 Py_INCREF(result);
2665 return result;
2666 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002667 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002668#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 /* check the import lock
2670 * me might be -1 but I ignore the error here, the lock function
2671 * takes care of the problem */
2672 me = PyThread_get_thread_ident();
2673 if (import_lock_thread == -1 || import_lock_thread == me) {
2674 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002675 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 }
2677 else {
2678 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002679 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002681 nameobj);
2682 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002684#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002685 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002686#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002687 Py_DECREF(nameobj);
2688 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002689}
2690
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002691/* Forward declarations for helper routines */
Victor Stinner974389d2011-03-15 09:33:57 +01002692static PyObject *get_parent(PyObject *globals,
2693 PyObject **p_name,
2694 int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002695static PyObject *load_next(PyObject *mod, PyObject *altmod,
Victor Stinner974389d2011-03-15 09:33:57 +01002696 PyObject *inputname, PyObject **p_outputname,
2697 Py_UNICODE *buf, Py_ssize_t *p_buflen,
2698 Py_ssize_t bufsize);
2699static int mark_miss(PyObject *name);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002700static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Victor Stinner974389d2011-03-15 09:33:57 +01002701 PyObject *buf, int recursive);
2702static PyObject * import_submodule(PyObject *mod, PyObject *name,
2703 PyObject *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002704
2705/* The Magnum Opus of dotted-name import :-) */
2706
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002707static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01002708import_module_level(PyObject *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002710{
Victor Stinner974389d2011-03-15 09:33:57 +01002711 Py_UNICODE buf[MAXPATHLEN+1];
2712 Py_ssize_t buflen;
2713 Py_ssize_t bufsize = MAXPATHLEN+1;
2714 PyObject *parent, *head, *next, *tail, *inputname, *outputname;
2715 PyObject *parent_name, *ensure_name;
2716 const Py_UNICODE *nameunicode;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002717
Victor Stinner974389d2011-03-15 09:33:57 +01002718 nameunicode = PyUnicode_AS_UNICODE(name);
2719
2720 if (Py_UNICODE_strchr(nameunicode, SEP) != NULL
2721#ifdef ALTSEP
2722 || Py_UNICODE_strchr(nameunicode, ALTSEP) != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002723#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 ) {
2725 PyErr_SetString(PyExc_ImportError,
2726 "Import by filename is not supported.");
2727 return NULL;
2728 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002729
Victor Stinner974389d2011-03-15 09:33:57 +01002730 parent = get_parent(globals, &parent_name, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (parent == NULL)
2732 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002733
Victor Stinner974389d2011-03-15 09:33:57 +01002734 buflen = PyUnicode_GET_SIZE(parent_name);
2735 if (buflen+1 > bufsize) {
2736 Py_DECREF(parent_name);
2737 PyErr_SetString(PyExc_ValueError,
2738 "Module name too long");
2739 return NULL;
2740 }
2741 Py_UNICODE_strcpy(buf, PyUnicode_AS_UNICODE(parent_name));
2742 Py_DECREF(parent_name);
2743
2744 head = load_next(parent, level < 0 ? Py_None : parent, name, &outputname,
2745 buf, &buflen, bufsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 if (head == NULL)
2747 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 tail = head;
2750 Py_INCREF(tail);
Victor Stinner974389d2011-03-15 09:33:57 +01002751
2752 if (outputname != NULL) {
2753 while (1) {
2754 inputname = outputname;
2755 next = load_next(tail, tail, inputname, &outputname,
2756 buf, &buflen, bufsize);
2757 Py_DECREF(tail);
2758 Py_DECREF(inputname);
2759 if (next == NULL) {
2760 Py_DECREF(head);
2761 return NULL;
2762 }
2763 tail = next;
2764
2765 if (outputname == NULL) {
2766 break;
2767 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 }
2770 if (tail == Py_None) {
2771 /* If tail is Py_None, both get_parent and load_next found
2772 an empty module name: someone called __import__("") or
2773 doctored faulty bytecode */
2774 Py_DECREF(tail);
2775 Py_DECREF(head);
Victor Stinner974389d2011-03-15 09:33:57 +01002776 PyErr_SetString(PyExc_ValueError, "Empty module name");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 return NULL;
2778 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 if (fromlist != NULL) {
2781 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2782 fromlist = NULL;
2783 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 if (fromlist == NULL) {
2786 Py_DECREF(tail);
2787 return head;
2788 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 Py_DECREF(head);
Victor Stinner974389d2011-03-15 09:33:57 +01002791
2792 ensure_name = PyUnicode_FromUnicode(buf, Py_UNICODE_strlen(buf));
2793 if (ensure_name == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 Py_DECREF(tail);
2795 return NULL;
2796 }
Victor Stinner974389d2011-03-15 09:33:57 +01002797 if (!ensure_fromlist(tail, fromlist, ensure_name, 0)) {
2798 Py_DECREF(tail);
2799 Py_DECREF(ensure_name);
2800 return NULL;
2801 }
2802 Py_DECREF(ensure_name);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002805}
2806
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002807PyObject *
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002808PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2809 PyObject *locals, PyObject *fromlist,
2810 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002811{
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002812 PyObject *mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 _PyImport_AcquireLock();
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002814 mod = import_module_level(name, globals, locals, fromlist, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 if (_PyImport_ReleaseLock() < 0) {
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002816 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 PyErr_SetString(PyExc_RuntimeError,
2818 "not holding the import lock");
2819 return NULL;
2820 }
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002821 return mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002822}
2823
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002824PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002825PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002826 PyObject *fromlist, int level)
2827{
2828 PyObject *nameobj, *mod;
2829 nameobj = PyUnicode_FromString(name);
2830 if (nameobj == NULL)
2831 return NULL;
2832 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2833 fromlist, level);
2834 Py_DECREF(nameobj);
2835 return mod;
2836}
2837
2838
Fred Drake87590902004-05-28 20:21:36 +00002839/* Return the package that an import is being performed in. If globals comes
2840 from the module foo.bar.bat (not itself a package), this returns the
2841 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002842 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002843
Victor Stinner974389d2011-03-15 09:33:57 +01002844 The name of the returned package is returned in *p_name.
Fred Drake87590902004-05-28 20:21:36 +00002845
2846 If globals doesn't come from a package or a module in a package, or a
2847 corresponding entry is not found in sys.modules, Py_None is returned.
2848*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002849static PyObject *
Victor Stinner9599de52011-03-13 22:38:38 -04002850get_parent(PyObject *globals, PyObject **p_name, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002851{
Victor Stinner974389d2011-03-15 09:33:57 +01002852 Py_UNICODE name[MAXPATHLEN+1];
2853 const Py_ssize_t bufsize = MAXPATHLEN+1;
2854 PyObject *nameobj;
2855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 static PyObject *namestr = NULL;
2857 static PyObject *pathstr = NULL;
2858 static PyObject *pkgstr = NULL;
2859 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2860 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 if (globals == NULL || !PyDict_Check(globals) || !level)
Victor Stinner974389d2011-03-15 09:33:57 +01002863 goto return_none;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 if (namestr == NULL) {
2866 namestr = PyUnicode_InternFromString("__name__");
2867 if (namestr == NULL)
2868 return NULL;
2869 }
2870 if (pathstr == NULL) {
2871 pathstr = PyUnicode_InternFromString("__path__");
2872 if (pathstr == NULL)
2873 return NULL;
2874 }
2875 if (pkgstr == NULL) {
2876 pkgstr = PyUnicode_InternFromString("__package__");
2877 if (pkgstr == NULL)
2878 return NULL;
2879 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if ((pkgname != NULL) && (pkgname != Py_None)) {
2884 /* __package__ is set, so use it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (!PyUnicode_Check(pkgname)) {
2886 PyErr_SetString(PyExc_ValueError,
2887 "__package__ set to non-string");
2888 return NULL;
2889 }
Victor Stinner974389d2011-03-15 09:33:57 +01002890 if (PyUnicode_GET_SIZE(pkgname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (level > 0) {
2892 PyErr_SetString(PyExc_ValueError,
2893 "Attempted relative import in non-package");
2894 return NULL;
2895 }
Victor Stinner974389d2011-03-15 09:33:57 +01002896 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 }
Victor Stinner974389d2011-03-15 09:33:57 +01002898 if (PyUnicode_GET_SIZE(pkgname)+1 > bufsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 PyErr_SetString(PyExc_ValueError,
2900 "Package name too long");
2901 return NULL;
2902 }
Victor Stinner974389d2011-03-15 09:33:57 +01002903 Py_UNICODE_strcpy(name, PyUnicode_AS_UNICODE(pkgname));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 } else {
2905 /* __package__ not set, so figure it out and set it */
2906 modname = PyDict_GetItem(globals, namestr);
2907 if (modname == NULL || !PyUnicode_Check(modname))
Victor Stinner974389d2011-03-15 09:33:57 +01002908 goto return_none;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 modpath = PyDict_GetItem(globals, pathstr);
2911 if (modpath != NULL) {
2912 /* __path__ is set, so modname is already the package name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002914
Victor Stinner974389d2011-03-15 09:33:57 +01002915 if (PyUnicode_GET_SIZE(modname)+1 > bufsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 PyErr_SetString(PyExc_ValueError,
2917 "Module name too long");
2918 return NULL;
2919 }
Victor Stinner974389d2011-03-15 09:33:57 +01002920 Py_UNICODE_strcpy(name, PyUnicode_AS_UNICODE(modname));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 error = PyDict_SetItem(globals, pkgstr, modname);
2922 if (error) {
2923 PyErr_SetString(PyExc_ValueError,
2924 "Could not set __package__");
2925 return NULL;
2926 }
2927 } else {
2928 /* Normal module, so work out the package name if any */
Victor Stinner974389d2011-03-15 09:33:57 +01002929 Py_UNICODE *start = PyUnicode_AS_UNICODE(modname);
2930 Py_UNICODE *lastdot = Py_UNICODE_strrchr(start, '.');
2931 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 int error;
2933 if (lastdot == NULL && level > 0) {
2934 PyErr_SetString(PyExc_ValueError,
2935 "Attempted relative import in non-package");
2936 return NULL;
2937 }
2938 if (lastdot == NULL) {
2939 error = PyDict_SetItem(globals, pkgstr, Py_None);
2940 if (error) {
2941 PyErr_SetString(PyExc_ValueError,
2942 "Could not set __package__");
2943 return NULL;
2944 }
Victor Stinner974389d2011-03-15 09:33:57 +01002945 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 }
2947 len = lastdot - start;
Victor Stinner974389d2011-03-15 09:33:57 +01002948 if (len+1 > bufsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 PyErr_SetString(PyExc_ValueError,
2950 "Module name too long");
2951 return NULL;
2952 }
Victor Stinner974389d2011-03-15 09:33:57 +01002953 Py_UNICODE_strncpy(name, start, len);
2954 name[len] = '\0';
2955 pkgname = PyUnicode_FromUnicode(name, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 if (pkgname == NULL) {
2957 return NULL;
2958 }
2959 error = PyDict_SetItem(globals, pkgstr, pkgname);
2960 Py_DECREF(pkgname);
2961 if (error) {
2962 PyErr_SetString(PyExc_ValueError,
2963 "Could not set __package__");
2964 return NULL;
2965 }
2966 }
2967 }
2968 while (--level > 0) {
Victor Stinner974389d2011-03-15 09:33:57 +01002969 Py_UNICODE *dot = Py_UNICODE_strrchr(name, '.');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 if (dot == NULL) {
2971 PyErr_SetString(PyExc_ValueError,
2972 "Attempted relative import beyond "
2973 "toplevel package");
2974 return NULL;
2975 }
2976 *dot = '\0';
2977 }
Victor Stinner974389d2011-03-15 09:33:57 +01002978
2979 nameobj = PyUnicode_FromUnicode(name, Py_UNICODE_strlen(name));
2980 if (nameobj == NULL)
2981 return NULL;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01002984 parent = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 if (parent == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01002986 int err;
2987
2988 if (orig_level >= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyErr_Format(PyExc_SystemError,
Victor Stinner974389d2011-03-15 09:33:57 +01002990 "Parent module %R not loaded, "
2991 "cannot perform relative import", nameobj);
2992 Py_DECREF(nameobj);
2993 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 }
Victor Stinner974389d2011-03-15 09:33:57 +01002995
2996 err = PyErr_WarnFormat(
2997 PyExc_RuntimeWarning, 1,
2998 "Parent module %R not found while handling absolute import",
2999 nameobj);
3000 Py_DECREF(nameobj);
3001 if (err)
3002 return NULL;
3003
3004 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 }
Victor Stinner974389d2011-03-15 09:33:57 +01003006 *p_name = nameobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 return parent;
3008 /* We expect, but can't guarantee, if parent != None, that:
Victor Stinner974389d2011-03-15 09:33:57 +01003009 - parent.__name__ == name
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 - parent.__dict__ is globals
3011 If this is violated... Who cares? */
Victor Stinner974389d2011-03-15 09:33:57 +01003012
3013return_none:
3014 nameobj = PyUnicode_FromUnicode(NULL, 0);
3015 if (nameobj == NULL)
3016 return NULL;
3017 *p_name = nameobj;
3018 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003019}
3020
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003021/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003022static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003023load_next(PyObject *mod, PyObject *altmod,
3024 PyObject *inputname, PyObject **p_outputname,
3025 Py_UNICODE *buf, Py_ssize_t *p_buflen, Py_ssize_t bufsize)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003026{
Victor Stinner974389d2011-03-15 09:33:57 +01003027 const Py_UNICODE *dot;
3028 Py_ssize_t len;
3029 Py_UNICODE *p;
3030 PyObject *fullname, *name, *result, *mark_name;
3031 const Py_UNICODE *nameuni;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003032
Victor Stinner974389d2011-03-15 09:33:57 +01003033 *p_outputname = NULL;
3034
3035 if (PyUnicode_GET_SIZE(inputname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 /* completely empty module name should only happen in
3037 'from . import' (or '__import__("")')*/
3038 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 return mod;
3040 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003041
Victor Stinner974389d2011-03-15 09:33:57 +01003042 nameuni = PyUnicode_AS_UNICODE(inputname);
3043 if (nameuni == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003045
Victor Stinner974389d2011-03-15 09:33:57 +01003046 dot = Py_UNICODE_strchr(nameuni, '.');
3047 if (dot != NULL) {
3048 len = dot - nameuni;
3049 if (len == 0) {
3050 PyErr_SetString(PyExc_ValueError,
3051 "Empty module name");
3052 return NULL;
3053 }
3054 }
3055 else
3056 len = PyUnicode_GET_SIZE(inputname);
3057
3058 if (*p_buflen+len+1 >= bufsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 PyErr_SetString(PyExc_ValueError,
3060 "Module name too long");
3061 return NULL;
3062 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003063
Victor Stinner974389d2011-03-15 09:33:57 +01003064 p = buf + *p_buflen;
3065 if (p != buf) {
3066 *p++ = '.';
3067 *p_buflen += 1;
3068 }
3069 Py_UNICODE_strncpy(p, nameuni, len);
3070 p[len] = '\0';
3071 *p_buflen += len;
3072
3073 fullname = PyUnicode_FromUnicode(buf, *p_buflen);
3074 if (fullname == NULL)
3075 return NULL;
3076 name = PyUnicode_FromUnicode(p, len);
3077 if (name == NULL) {
3078 Py_DECREF(fullname);
3079 return NULL;
3080 }
3081 result = import_submodule(mod, name, fullname);
3082 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 if (result == Py_None && altmod != mod) {
3084 Py_DECREF(result);
3085 /* Here, altmod must be None and mod must not be None */
Victor Stinner974389d2011-03-15 09:33:57 +01003086 result = import_submodule(altmod, name, name);
3087 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 if (result != NULL && result != Py_None) {
Victor Stinner974389d2011-03-15 09:33:57 +01003089 mark_name = PyUnicode_FromUnicode(buf, *p_buflen);
3090 if (mark_name == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 Py_DECREF(result);
3092 return NULL;
3093 }
Victor Stinner974389d2011-03-15 09:33:57 +01003094 if (mark_miss(mark_name) != 0) {
3095 Py_DECREF(result);
3096 Py_DECREF(mark_name);
3097 return NULL;
3098 }
3099 Py_DECREF(mark_name);
3100 Py_UNICODE_strncpy(buf, nameuni, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 buf[len] = '\0';
3102 *p_buflen = len;
3103 }
3104 }
Victor Stinner974389d2011-03-15 09:33:57 +01003105 else
3106 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 if (result == NULL)
3108 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 if (result == Py_None) {
3111 Py_DECREF(result);
3112 PyErr_Format(PyExc_ImportError,
Victor Stinner974389d2011-03-15 09:33:57 +01003113 "No module named %R", inputname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 return NULL;
3115 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003116
Victor Stinner974389d2011-03-15 09:33:57 +01003117 if (dot != NULL) {
3118 *p_outputname = PyUnicode_FromUnicode(dot+1, Py_UNICODE_strlen(dot+1));
3119 if (*p_outputname == NULL) {
3120 Py_DECREF(result);
3121 return NULL;
3122 }
3123 }
3124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003126}
3127
3128static int
Victor Stinner974389d2011-03-15 09:33:57 +01003129mark_miss(PyObject *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003132 return PyDict_SetItem(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003133}
3134
3135static int
Victor Stinner974389d2011-03-15 09:33:57 +01003136ensure_fromlist(PyObject *mod, PyObject *fromlist, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 int i;
Victor Stinner974389d2011-03-15 09:33:57 +01003140 PyObject *fullname;
3141 Py_ssize_t fromlist_len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 if (!PyObject_HasAttrString(mod, "__path__"))
3144 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003145
Victor Stinner974389d2011-03-15 09:33:57 +01003146 fromlist_len = PySequence_Size(fromlist);
3147
3148 for (i = 0; i < fromlist_len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 PyObject *item = PySequence_GetItem(fromlist, i);
3150 int hasit;
Victor Stinner974389d2011-03-15 09:33:57 +01003151 if (item == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 if (!PyUnicode_Check(item)) {
3154 PyErr_SetString(PyExc_TypeError,
3155 "Item in ``from list'' not a string");
3156 Py_DECREF(item);
3157 return 0;
3158 }
3159 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
3160 PyObject *all;
3161 Py_DECREF(item);
3162 /* See if the package defines __all__ */
3163 if (recursive)
3164 continue; /* Avoid endless recursion */
3165 all = PyObject_GetAttrString(mod, "__all__");
3166 if (all == NULL)
3167 PyErr_Clear();
3168 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003169 int ret = ensure_fromlist(mod, all, name, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 Py_DECREF(all);
3171 if (!ret)
3172 return 0;
3173 }
3174 continue;
3175 }
3176 hasit = PyObject_HasAttr(mod, item);
3177 if (!hasit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 PyObject *submod;
Victor Stinner974389d2011-03-15 09:33:57 +01003179 fullname = PyUnicode_FromFormat("%U.%U", name, item);
3180 if (fullname != NULL) {
3181 submod = import_submodule(mod, item, fullname);
3182 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 }
Victor Stinner974389d2011-03-15 09:33:57 +01003184 else
3185 submod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 Py_XDECREF(submod);
3187 if (submod == NULL) {
3188 Py_DECREF(item);
3189 return 0;
3190 }
3191 }
3192 Py_DECREF(item);
3193 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003194
Victor Stinner974389d2011-03-15 09:33:57 +01003195 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003196}
3197
Neil Schemenauer00b09662003-06-16 21:03:07 +00003198static int
Victor Stinner974389d2011-03-15 09:33:57 +01003199add_submodule(PyObject *mod, PyObject *submod, PyObject *fullname,
3200 PyObject *subname, PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00003201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 if (mod == Py_None)
3203 return 1;
3204 /* Irrespective of the success of this load, make a
3205 reference to it in the parent package module. A copy gets
3206 saved in the modules dictionary under the full name, so get a
3207 reference from there, if need be. (The exception is when the
3208 load failed with a SyntaxError -- then there's no trace in
3209 sys.modules. In that case, of course, do nothing extra.) */
3210 if (submod == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003211 submod = PyDict_GetItem(modules, fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (submod == NULL)
3213 return 1;
3214 }
3215 if (PyModule_Check(mod)) {
3216 /* We can't use setattr here since it can give a
3217 * spurious warning if the submodule name shadows a
3218 * builtin name */
3219 PyObject *dict = PyModule_GetDict(mod);
3220 if (!dict)
3221 return 0;
Victor Stinner974389d2011-03-15 09:33:57 +01003222 if (PyDict_SetItem(dict, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 return 0;
3224 }
3225 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003226 if (PyObject_SetAttr(mod, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 return 0;
3228 }
3229 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00003230}
3231
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003232static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003233import_submodule(PyObject *mod, PyObject *subname, PyObject *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003236 PyObject *m = NULL, *bufobj, *path_list, *loader;
Victor Stinner9599de52011-03-13 22:38:38 -04003237 struct filedescr *fdp;
3238 FILE *fp;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 /* Require:
3241 if mod == None: subname == fullname
3242 else: mod.__name__ + "." + subname == fullname
3243 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003244
Victor Stinner974389d2011-03-15 09:33:57 +01003245 if ((m = PyDict_GetItem(modules, fullname)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 Py_INCREF(m);
Victor Stinner9599de52011-03-13 22:38:38 -04003247 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 }
Victor Stinner9599de52011-03-13 22:38:38 -04003249
3250 if (mod == Py_None)
Victor Stinner533d7832011-03-14 13:22:54 -04003251 path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 else {
Victor Stinner533d7832011-03-14 13:22:54 -04003253 path_list = PyObject_GetAttrString(mod, "__path__");
3254 if (path_list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 PyErr_Clear();
3256 Py_INCREF(Py_None);
3257 return Py_None;
3258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003260
Victor Stinner533d7832011-03-14 13:22:54 -04003261 fdp = find_module(fullname, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003262 &bufobj, &fp, &loader);
Victor Stinner533d7832011-03-14 13:22:54 -04003263 Py_XDECREF(path_list);
Victor Stinner9599de52011-03-13 22:38:38 -04003264 if (fdp == NULL) {
3265 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3266 return NULL;
3267 PyErr_Clear();
3268 Py_INCREF(Py_None);
3269 return Py_None;
3270 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003271 m = load_module(fullname, fp, bufobj, fdp->type, loader);
3272 Py_XDECREF(bufobj);
Victor Stinner9599de52011-03-13 22:38:38 -04003273 Py_XDECREF(loader);
3274 if (fp)
3275 fclose(fp);
3276 if (m == NULL)
3277 return NULL;
3278 if (!add_submodule(mod, m, fullname, subname, modules)) {
3279 Py_XDECREF(m);
3280 return NULL;
3281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003283}
3284
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003285
3286/* Re-import a module of any kind and return its module object, WITH
3287 INCREMENTED REFERENCE COUNT */
3288
Guido van Rossum79f25d91997-04-29 20:08:16 +00003289PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003290PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 PyInterpreterState *interp = PyThreadState_Get()->interp;
3293 PyObject *modules_reloading = interp->modules_reloading;
3294 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003295 PyObject *path_list = NULL, *loader = NULL, *existing_m = NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003296 PyObject *nameobj, *bufobj, *subnameobj;
3297 Py_UNICODE *name, *subname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 struct filedescr *fdp;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003299 FILE *fp = NULL;
3300 PyObject *newm = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 if (modules_reloading == NULL) {
3303 Py_FatalError("PyImport_ReloadModule: "
3304 "no modules_reloading dictionary!");
3305 return NULL;
3306 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 if (m == NULL || !PyModule_Check(m)) {
3309 PyErr_SetString(PyExc_TypeError,
3310 "reload() argument must be module");
3311 return NULL;
3312 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003313 nameobj = PyModule_GetNameObject(m);
3314 if (nameobj == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003316 if (m != PyDict_GetItem(modules, nameobj)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003318 "reload(): module %R not in sys.modules",
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003319 nameobj);
3320 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 return NULL;
3322 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003323 existing_m = PyDict_GetItem(modules_reloading, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 if (existing_m != NULL) {
3325 /* Due to a recursive reload, this module is already
3326 being reloaded. */
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003327 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 Py_INCREF(existing_m);
3329 return existing_m;
3330 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003331 if (PyDict_SetItem(modules_reloading, nameobj, m) < 0) {
3332 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003334 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003335
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003336 name = PyUnicode_AS_UNICODE(nameobj);
3337 subname = Py_UNICODE_strrchr(name, '.');
3338 if (subname == NULL) {
3339 Py_INCREF(nameobj);
3340 subnameobj = nameobj;
3341 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 else {
3343 PyObject *parentname, *parent;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003344 Py_ssize_t len;
3345 len = subname - name;
3346 parentname = PyUnicode_FromUnicode(name, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003348 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 }
3350 parent = PyDict_GetItem(modules, parentname);
3351 if (parent == NULL) {
3352 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003353 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 parentname);
3355 Py_DECREF(parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003356 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 }
3358 Py_DECREF(parentname);
Victor Stinner533d7832011-03-14 13:22:54 -04003359 path_list = PyObject_GetAttrString(parent, "__path__");
3360 if (path_list == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 PyErr_Clear();
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003362 subname++;
3363 len = PyUnicode_GET_SIZE(nameobj) - (len + 1);
3364 subnameobj = PyUnicode_FromUnicode(subname, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003366 if (subnameobj == NULL)
3367 goto error;
Victor Stinner533d7832011-03-14 13:22:54 -04003368 fdp = find_module(nameobj, subnameobj, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003369 &bufobj, &fp, &loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003370 Py_DECREF(subnameobj);
Victor Stinner533d7832011-03-14 13:22:54 -04003371 Py_XDECREF(path_list);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 if (fdp == NULL) {
3374 Py_XDECREF(loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003375 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003377
Victor Stinner2fd76e42011-03-14 15:19:39 -04003378 newm = load_module(nameobj, fp, bufobj, fdp->type, loader);
3379 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 if (fp)
3383 fclose(fp);
3384 if (newm == NULL) {
3385 /* load_module probably removed name from modules because of
3386 * the error. Put back the original module object. We're
3387 * going to return NULL in this case regardless of whether
3388 * replacing name succeeds, so the return value is ignored.
3389 */
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003390 PyDict_SetItem(modules, nameobj, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003392
3393error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 imp_modules_reloading_clear();
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003395 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003397}
3398
3399
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003400/* Higher-level import emulator which emulates the "import" statement
3401 more accurately -- it invokes the __import__() function from the
3402 builtins of the current globals. This means that the import is
3403 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003404 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003405 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003406 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003407 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003408
3409PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003410PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 static PyObject *silly_list = NULL;
3413 static PyObject *builtins_str = NULL;
3414 static PyObject *import_str = NULL;
3415 PyObject *globals = NULL;
3416 PyObject *import = NULL;
3417 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003418 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 /* Initialize constant string objects */
3422 if (silly_list == NULL) {
3423 import_str = PyUnicode_InternFromString("__import__");
3424 if (import_str == NULL)
3425 return NULL;
3426 builtins_str = PyUnicode_InternFromString("__builtins__");
3427 if (builtins_str == NULL)
3428 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003429 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 if (silly_list == NULL)
3431 return NULL;
3432 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 /* Get the builtins from current globals */
3435 globals = PyEval_GetGlobals();
3436 if (globals != NULL) {
3437 Py_INCREF(globals);
3438 builtins = PyObject_GetItem(globals, builtins_str);
3439 if (builtins == NULL)
3440 goto err;
3441 }
3442 else {
3443 /* No globals -- use standard builtins, and fake globals */
3444 builtins = PyImport_ImportModuleLevel("builtins",
3445 NULL, NULL, NULL, 0);
3446 if (builtins == NULL)
3447 return NULL;
3448 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3449 if (globals == NULL)
3450 goto err;
3451 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 /* Get the __import__ function from the builtins */
3454 if (PyDict_Check(builtins)) {
3455 import = PyObject_GetItem(builtins, import_str);
3456 if (import == NULL)
3457 PyErr_SetObject(PyExc_KeyError, import_str);
3458 }
3459 else
3460 import = PyObject_GetAttr(builtins, import_str);
3461 if (import == NULL)
3462 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003465 Always use absolute import here.
3466 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3468 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003469 if (r == NULL)
3470 goto err;
3471 Py_DECREF(r);
3472
3473 modules = PyImport_GetModuleDict();
3474 r = PyDict_GetItem(modules, module_name);
3475 if (r != NULL)
3476 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003477
3478 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 Py_XDECREF(globals);
3480 Py_XDECREF(builtins);
3481 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003484}
3485
3486
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003487/* Module 'imp' provides Python access to the primitives used for
3488 importing modules.
3489*/
3490
Guido van Rossum79f25d91997-04-29 20:08:16 +00003491static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003492imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 buf[0] = (char) ((magic >> 0) & 0xff);
3497 buf[1] = (char) ((magic >> 8) & 0xff);
3498 buf[2] = (char) ((magic >> 16) & 0xff);
3499 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003502}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003503
3504static PyObject *
3505imp_get_magic(PyObject *self, PyObject *noargs)
3506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003508}
3509
3510static PyObject *
3511imp_get_tag(PyObject *self, PyObject *noargs)
3512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003514}
3515
Guido van Rossum79f25d91997-04-29 20:08:16 +00003516static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003517imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 PyObject *list;
3520 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 list = PyList_New(0);
3523 if (list == NULL)
3524 return NULL;
3525 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3526 PyObject *item = Py_BuildValue("ssi",
3527 fdp->suffix, fdp->mode, fdp->type);
3528 if (item == NULL) {
3529 Py_DECREF(list);
3530 return NULL;
3531 }
3532 if (PyList_Append(list, item) < 0) {
3533 Py_DECREF(list);
3534 Py_DECREF(item);
3535 return NULL;
3536 }
3537 Py_DECREF(item);
3538 }
3539 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003540}
3541
Guido van Rossum79f25d91997-04-29 20:08:16 +00003542static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003543call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 extern int fclose(FILE *);
3546 PyObject *fob, *ret;
3547 PyObject *pathobj;
3548 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003549 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 int fd = -1;
3551 char *found_encoding = NULL;
3552 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003553
Victor Stinner533d7832011-03-14 13:22:54 -04003554 if (path_list == Py_None)
3555 path_list = NULL;
3556 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003557 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 if (fdp == NULL)
3559 return NULL;
3560 if (fp != NULL) {
3561 fd = fileno(fp);
3562 if (fd != -1)
3563 fd = dup(fd);
3564 fclose(fp);
3565 fp = NULL;
3566 }
3567 if (fd != -1) {
3568 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003569 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003571 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003573 if (found_encoding == NULL && PyErr_Occurred()) {
3574 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 encoding = (found_encoding != NULL) ? found_encoding :
3578 (char*)PyUnicode_GetDefaultEncoding();
3579 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003580 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 (char*)encoding, NULL, NULL, 1);
3582 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003583 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 close(fd);
3585 PyMem_FREE(found_encoding);
3586 return NULL;
3587 }
3588 }
3589 else {
3590 fob = Py_None;
3591 Py_INCREF(fob);
3592 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003593 if (pathobj == NULL) {
3594 Py_INCREF(Py_None);
3595 pathobj = Py_None;
3596 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 ret = Py_BuildValue("NN(ssi)",
3598 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3599 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003602}
3603
Guido van Rossum79f25d91997-04-29 20:08:16 +00003604static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003605imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003606{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003607 PyObject *name, *path_list = NULL;
3608 if (!PyArg_ParseTuple(args, "U|O:find_module",
3609 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003611 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003612}
3613
3614static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003615imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003616{
Victor Stinner95872862011-03-07 18:20:56 +01003617 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 int ret;
3619 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003620 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 return NULL;
3622 ret = init_builtin(name);
3623 if (ret < 0)
3624 return NULL;
3625 if (ret == 0) {
3626 Py_INCREF(Py_None);
3627 return Py_None;
3628 }
Victor Stinner95872862011-03-07 18:20:56 +01003629 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 Py_XINCREF(m);
3631 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003632}
3633
Guido van Rossum79f25d91997-04-29 20:08:16 +00003634static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003635imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003636{
Victor Stinner53dc7352011-03-20 01:50:21 +01003637 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 int ret;
3639 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003640 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003642 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 if (ret < 0)
3644 return NULL;
3645 if (ret == 0) {
3646 Py_INCREF(Py_None);
3647 return Py_None;
3648 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003649 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 Py_XINCREF(m);
3651 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003652}
3653
Guido van Rossum79f25d91997-04-29 20:08:16 +00003654static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003655imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003656{
Victor Stinner53dc7352011-03-20 01:50:21 +01003657 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003658
Victor Stinner53dc7352011-03-20 01:50:21 +01003659 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 return NULL;
3661 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003662}
3663
Guido van Rossum79f25d91997-04-29 20:08:16 +00003664static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003665imp_is_frozen_package(PyObject *self, PyObject *args)
3666{
Victor Stinner53dc7352011-03-20 01:50:21 +01003667 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003668
Victor Stinner53dc7352011-03-20 01:50:21 +01003669 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 return NULL;
3671 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003672}
3673
3674static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003675imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003676{
Victor Stinner95872862011-03-07 18:20:56 +01003677 PyObject *name;
3678 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 return NULL;
3680 return PyLong_FromLong(is_builtin(name));
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_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003685{
Victor Stinner53dc7352011-03-20 01:50:21 +01003686 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003688 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 return NULL;
3690 p = find_frozen(name);
3691 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003692}
3693
3694static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003695get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 FILE *fp;
3698 if (mode[0] == 'U')
3699 mode = "r" PY_STDIOTEXTMODE;
3700 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003701 fp = _Py_fopen(pathname, mode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 }
3703 else {
3704 int fd = PyObject_AsFileDescriptor(fob);
3705 if (fd == -1)
3706 return NULL;
3707 if (!_PyVerify_fd(fd))
3708 goto error;
3709 /* the FILE struct gets a new fd, so that it can be closed
3710 * independently of the file descriptor given
3711 */
3712 fd = dup(fd);
3713 if (fd == -1)
3714 goto error;
3715 fp = fdopen(fd, mode);
3716 }
3717 if (fp)
3718 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003719error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 PyErr_SetFromErrno(PyExc_IOError);
3721 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003722}
3723
Guido van Rossum79f25d91997-04-29 20:08:16 +00003724static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003725imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003726{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003727 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 PyObject *fob = NULL;
3729 PyObject *m;
3730 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003731 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003733 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 &fob))
3735 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003736 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003738 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 return NULL;
3740 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003741 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003743 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003745}
3746
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003747#ifdef HAVE_DYNAMIC_LOADING
3748
Guido van Rossum79f25d91997-04-29 20:08:16 +00003749static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003750imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003751{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003752 PyObject *name, *pathname, *fob = NULL, *mod;
3753 FILE *fp;
3754
3755 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3756 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003758 if (fob != NULL) {
3759 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003760 if (fp == NULL) {
3761 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003763 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003765 else
3766 fp = NULL;
3767 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003768 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 if (fp)
3770 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003771 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003772}
3773
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003774#endif /* HAVE_DYNAMIC_LOADING */
3775
Guido van Rossum79f25d91997-04-29 20:08:16 +00003776static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003777imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003778{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003779 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 PyObject *fob = NULL;
3781 PyObject *m;
3782 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003783 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003785 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 &fob))
3787 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003788 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003790 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 return NULL;
3792 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003793 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003794 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 fclose(fp);
3796 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003797}
3798
Guido van Rossum79f25d91997-04-29 20:08:16 +00003799static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003800imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003801{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003802 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 char *suffix; /* Unused */
3804 char *mode;
3805 int type;
3806 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003807
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003808 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3809 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003811 if (pathname_obj != Py_None) {
3812 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3813 return NULL;
3814 }
3815 else
3816 pathname = NULL;
3817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 if (*mode) {
3819 /* Mode must start with 'r' or 'U' and must not contain '+'.
3820 Implicit in this test is the assumption that the mode
3821 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3824 PyErr_Format(PyExc_ValueError,
3825 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003826 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 return NULL;
3828 }
3829 }
3830 if (fob == Py_None)
3831 fp = NULL;
3832 else {
3833 fp = get_file(NULL, fob, mode);
3834 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003835 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 return NULL;
3837 }
3838 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003839 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003840 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 if (fp)
3842 fclose(fp);
3843 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003844}
3845
3846static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003847imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003848{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003849 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003851 if (!PyArg_ParseTuple(args, "UO&:load_package",
3852 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003854 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003855 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003857}
3858
3859static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003860imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003861{
Victor Stinnerfe19d212011-03-14 14:53:28 -04003862 PyObject *name;
3863 if (!PyArg_ParseTuple(args, "U:new_module", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 return NULL;
Victor Stinnerfe19d212011-03-14 14:53:28 -04003865 return PyModule_NewObject(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003866}
3867
Christian Heimes13a7a212008-01-07 17:13:09 +00003868static PyObject *
3869imp_reload(PyObject *self, PyObject *v)
3870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003872}
3873
3874PyDoc_STRVAR(doc_reload,
3875"reload(module) -> module\n\
3876\n\
3877Reload the module. The module must have been successfully imported before.");
3878
Barry Warsaw28a691b2010-04-17 00:19:56 +00003879static PyObject *
3880imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003883
Victor Stinner2f42ae52011-03-20 00:41:24 +01003884 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003885 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003889 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003890 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003892
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003893 if (debug_override != NULL &&
3894 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003895 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003896 return NULL;
3897 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003898
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003899 cpathname = make_compiled_pathname(
Victor Stinner2f42ae52011-03-20 00:41:24 +01003900 PyUnicode_AS_UNICODE(pathname),
3901 debug);
3902 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (cpathname == NULL) {
3905 PyErr_Format(PyExc_SystemError, "path buffer too short");
3906 return NULL;
3907 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003908 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003909}
3910
3911PyDoc_STRVAR(doc_cache_from_source,
3912"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3913\n\
3914The .py file does not need to exist; this simply returns the path to the\n\
3915.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3916will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3917\n\
3918If debug_override is not None, then it must be a boolean and is taken as\n\
3919the value of __debug__ instead.");
3920
3921static PyObject *
3922imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04003925 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003928 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04003929 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003931
Victor Stinnerc9abda02011-03-14 13:33:46 -04003932 source = make_source_pathname(pathname);
3933 if (source == NULL) {
3934 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04003936 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 return NULL;
3938 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04003939 Py_DECREF(pathname);
3940 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003941}
3942
3943PyDoc_STRVAR(doc_source_from_cache,
3944"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3945\n\
3946The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3947the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3948does not conform to PEP 3147 format, ValueError will be raised.");
3949
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003950/* Doc strings */
3951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003952PyDoc_STRVAR(doc_imp,
3953"This module provides the components needed to build your own\n\
3954__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003955
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003956PyDoc_STRVAR(doc_find_module,
3957"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003958Search for a module. If path is omitted or None, search for a\n\
3959built-in, frozen or special module and continue search in sys.path.\n\
3960The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003961package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003962
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003963PyDoc_STRVAR(doc_load_module,
3964"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003965Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003966The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003967
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003968PyDoc_STRVAR(doc_get_magic,
3969"get_magic() -> string\n\
3970Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003971
Barry Warsaw28a691b2010-04-17 00:19:56 +00003972PyDoc_STRVAR(doc_get_tag,
3973"get_tag() -> string\n\
3974Return the magic tag for .pyc or .pyo files.");
3975
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003976PyDoc_STRVAR(doc_get_suffixes,
3977"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003978Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003979that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003981PyDoc_STRVAR(doc_new_module,
3982"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003983Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003984The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003986PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003987"lock_held() -> boolean\n\
3988Return True if the import lock is currently held, else False.\n\
3989On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003990
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003991PyDoc_STRVAR(doc_acquire_lock,
3992"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003993Acquires the interpreter's import lock for the current thread.\n\
3994This lock should be used by import hooks to ensure thread-safety\n\
3995when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003996On platforms without threads, this function does nothing.");
3997
3998PyDoc_STRVAR(doc_release_lock,
3999"release_lock() -> None\n\
4000Release the interpreter's import lock.\n\
4001On platforms without threads, this function does nothing.");
4002
Guido van Rossum79f25d91997-04-29 20:08:16 +00004003static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
4005 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
4006 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
4007 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
4008 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
4009 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
4010 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
4011 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
4012 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
4013 {"reload", imp_reload, METH_O, doc_reload},
4014 {"cache_from_source", (PyCFunction)imp_cache_from_source,
4015 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
4016 {"source_from_cache", (PyCFunction)imp_source_from_cache,
4017 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
4018 /* The rest are obsolete */
4019 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
4020 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
4021 {"init_builtin", imp_init_builtin, METH_VARARGS},
4022 {"init_frozen", imp_init_frozen, METH_VARARGS},
4023 {"is_builtin", imp_is_builtin, METH_VARARGS},
4024 {"is_frozen", imp_is_frozen, METH_VARARGS},
4025 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004026#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004028#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 {"load_package", imp_load_package, METH_VARARGS},
4030 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07004031 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004033};
4034
Guido van Rossum1a8791e1998-08-04 22:46:29 +00004035static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004036setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004038 PyObject *v;
4039 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 v = PyLong_FromLong((long)value);
4042 err = PyDict_SetItemString(d, name, v);
4043 Py_XDECREF(v);
4044 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004045}
4046
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004047typedef struct {
4048 PyObject_HEAD
4049} NullImporter;
4050
4051static int
4052NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
4053{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004054#ifndef MS_WINDOWS
4055 PyObject *path;
4056 struct stat statbuf;
4057 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4060 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004061
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004062 if (!PyArg_ParseTuple(args, "O&:NullImporter",
4063 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004065
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004066 if (PyBytes_GET_SIZE(path) == 0) {
4067 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 PyErr_SetString(PyExc_ImportError, "empty pathname");
4069 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004071
4072 rv = stat(PyBytes_AS_STRING(path), &statbuf);
4073 Py_DECREF(path);
4074 if (rv == 0) {
4075 /* it exists */
4076 if (S_ISDIR(statbuf.st_mode)) {
4077 /* it's a directory */
4078 PyErr_SetString(PyExc_ImportError, "existing directory");
4079 return -1;
4080 }
4081 }
4082#else /* MS_WINDOWS */
4083 PyObject *pathobj;
4084 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00004085 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004086
4087 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4088 return -1;
4089
4090 if (!PyArg_ParseTuple(args, "U:NullImporter",
4091 &pathobj))
4092 return -1;
4093
4094 if (PyUnicode_GET_SIZE(pathobj) == 0) {
4095 PyErr_SetString(PyExc_ImportError, "empty pathname");
4096 return -1;
4097 }
4098
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00004099 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004100 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004101 return -1;
4102 /* see issue1293 and issue3677:
4103 * stat() on Windows doesn't recognise paths like
4104 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
4105 */
4106 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004107 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004108 if (rv != INVALID_FILE_ATTRIBUTES) {
4109 /* it exists */
4110 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
4111 /* it's a directory */
4112 PyErr_SetString(PyExc_ImportError, "existing directory");
4113 return -1;
4114 }
4115 }
4116#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004118}
4119
4120static PyObject *
4121NullImporter_find_module(NullImporter *self, PyObject *args)
4122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004124}
4125
4126static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
4128 "Always return None"
4129 },
4130 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004131};
4132
4133
Christian Heimes9cd17752007-11-18 19:35:23 +00004134PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 PyVarObject_HEAD_INIT(NULL, 0)
4136 "imp.NullImporter", /*tp_name*/
4137 sizeof(NullImporter), /*tp_basicsize*/
4138 0, /*tp_itemsize*/
4139 0, /*tp_dealloc*/
4140 0, /*tp_print*/
4141 0, /*tp_getattr*/
4142 0, /*tp_setattr*/
4143 0, /*tp_reserved*/
4144 0, /*tp_repr*/
4145 0, /*tp_as_number*/
4146 0, /*tp_as_sequence*/
4147 0, /*tp_as_mapping*/
4148 0, /*tp_hash */
4149 0, /*tp_call*/
4150 0, /*tp_str*/
4151 0, /*tp_getattro*/
4152 0, /*tp_setattro*/
4153 0, /*tp_as_buffer*/
4154 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4155 "Null importer object", /* tp_doc */
4156 0, /* tp_traverse */
4157 0, /* tp_clear */
4158 0, /* tp_richcompare */
4159 0, /* tp_weaklistoffset */
4160 0, /* tp_iter */
4161 0, /* tp_iternext */
4162 NullImporter_methods, /* tp_methods */
4163 0, /* tp_members */
4164 0, /* tp_getset */
4165 0, /* tp_base */
4166 0, /* tp_dict */
4167 0, /* tp_descr_get */
4168 0, /* tp_descr_set */
4169 0, /* tp_dictoffset */
4170 (initproc)NullImporter_init, /* tp_init */
4171 0, /* tp_alloc */
4172 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004173};
4174
Martin v. Löwis1a214512008-06-11 05:26:20 +00004175static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 PyModuleDef_HEAD_INIT,
4177 "imp",
4178 doc_imp,
4179 0,
4180 imp_methods,
4181 NULL,
4182 NULL,
4183 NULL,
4184 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004185};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004186
Jason Tishler6bc06ec2003-09-04 11:59:50 +00004187PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004188PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 if (PyType_Ready(&PyNullImporter_Type) < 0)
4193 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 m = PyModule_Create(&impmodule);
4196 if (m == NULL)
4197 goto failure;
4198 d = PyModule_GetDict(m);
4199 if (d == NULL)
4200 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
4203 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
4204 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
4205 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
4206 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
4207 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
4208 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4209 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4210 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4211 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 Py_INCREF(&PyNullImporter_Type);
4214 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4215 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004216 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 Py_XDECREF(m);
4218 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004219}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004220
4221
Guido van Rossumb18618d2000-05-03 23:44:39 +00004222/* API for embedding applications that want to add their own entries
4223 to the table of built-in modules. This should normally be called
4224 *before* Py_Initialize(). When the table resize fails, -1 is
4225 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004226
4227 After a similar function by Just van Rossum. */
4228
4229int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004230PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 static struct _inittab *our_copy = NULL;
4233 struct _inittab *p;
4234 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 /* Count the number of entries in both tables */
4237 for (n = 0; newtab[n].name != NULL; n++)
4238 ;
4239 if (n == 0)
4240 return 0; /* Nothing to do */
4241 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4242 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 /* Allocate new memory for the combined table */
4245 p = our_copy;
4246 PyMem_RESIZE(p, struct _inittab, i+n+1);
4247 if (p == NULL)
4248 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 /* Copy the tables into the new memory */
4251 if (our_copy != PyImport_Inittab)
4252 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4253 PyImport_Inittab = our_copy = p;
4254 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004257}
4258
4259/* Shorthand to add a single entry given a name and a function */
4260
4261int
Brett Cannona826f322009-04-02 03:41:46 +00004262PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 newtab[0].name = (char *)name;
4269 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004272}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004273
4274#ifdef __cplusplus
4275}
4276#endif