blob: 4871b99a9378a46f3859dd295e0bc5c114a36fe0 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000011#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000012#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013
Guido van Rossum55a83382000-09-20 20:31:38 +000014#ifdef HAVE_FCNTL_H
15#include <fcntl.h>
16#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000018extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000020
Christian Heimesd3eb5a152008-02-24 00:38:49 +000021#ifdef MS_WINDOWS
22/* for stat.st_mode */
23typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000024/* for _mkdir */
25#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000026#endif
27
Guido van Rossum21d335e1993-10-15 13:01:11 +000028
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000029/* Magic word to reject .pyc files generated by other Python versions.
30 It should change for each incompatible change to the bytecode.
31
32 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000033 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000034 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000035
Guido van Rossum45aecf42006-03-15 04:58:47 +000036 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000037 -U interpeter flag will cause MAGIC+1 being used. They have been
38 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000040 There were a variety of old schemes for setting the magic number.
41 The current working scheme is to increment the previous value by
42 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000043
Barry Warsaw28a691b2010-04-17 00:19:56 +000044 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
45 number also includes a new "magic tag", i.e. a human readable string used
46 to represent the magic number in __pycache__ directories. When you change
47 the magic number, you must also set a new unique magic tag. Generally this
48 can be named after the Python major version of the magic number bump, but
49 it can really be anything, as long as it's different than anything else
50 that's come before. The tags are included in the following table, starting
51 with Python 3.2a0.
52
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Known values:
54 Python 1.5: 20121
55 Python 1.5.1: 20121
56 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000058 Python 2.0: 50823
59 Python 2.0.1: 50823
60 Python 2.1: 60202
61 Python 2.1.1: 60202
62 Python 2.1.2: 60202
63 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000064 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000065 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000066 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000067 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000068 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000069 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000070 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000071 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000072 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000073 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
75 Python 2.5b3: 62111 (fix wrong code: x += yield)
76 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000078 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000079 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000081 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 3010 (removed UNARY_CONVERT)
83 3020 (added BUILD_SET)
84 3030 (added keyword-only parameters)
85 3040 (added signature annotations)
86 3050 (print becomes a function)
87 3060 (PEP 3115 metaclass syntax)
88 3061 (string literals become unicode)
89 3071 (PEP 3109 raise changes)
90 3081 (PEP 3137 make __file__ and __name__ unicode)
91 3091 (kill str8 interning)
92 3101 (merge from 2.6a0, see 62151)
93 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000094 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
95 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
96 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000100 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000102 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
103 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000104 Python 3.2a2 3180 (add DELETE_DEREF)
Benjamin Petersone7c15fa2011-06-19 19:54:45 -0500105 Python 3.3a0 3190 __class__ super closure changed
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 Python 3.3a0 3200 (__qualname__ added)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100107 3210 (added size modulo 2**32 to the pyc header)
Tim Peters36515e22001-11-18 04:06:29 +0000108*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000109
Nick Coghlancd419ab2010-09-11 00:39:25 +0000110/* MAGIC must change whenever the bytecode emitted by the compiler may no
111 longer be understood by older implementations of the eval loop (usually
112 due to the addition of new opcodes)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200113 TAG must change for each major Python release. The magic number will take
114 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000115*/
Benjamin Peterson48deae12011-06-03 17:50:16 -0500116#define QUOTE(arg) #arg
117#define STRIFY(name) QUOTE(name)
118#define MAJOR STRIFY(PY_MAJOR_VERSION)
119#define MINOR STRIFY(PY_MINOR_VERSION)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100120#define MAGIC (3210 | ((long)'\r'<<16) | ((long)'\n'<<24))
Benjamin Peterson48deae12011-06-03 17:50:16 -0500121#define TAG "cpython-" MAJOR MINOR;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122#define CACHEDIR "__pycache__"
123/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000124static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000125static const char *pyc_tag = TAG;
Benjamin Peterson48deae12011-06-03 17:50:16 -0500126#undef QUOTE
127#undef STRIFY
128#undef MAJOR
129#undef MINOR
Guido van Rossum96774c12000-05-01 20:19:08 +0000130
Victor Stinner95872862011-03-07 18:20:56 +0100131/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000133
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200134/* Function from Parser/tokenizer.c */
135extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
136
Guido van Rossum771c6c81997-10-31 18:37:24 +0000137/* This table is defined in config.c: */
138extern struct _inittab _PyImport_Inittab[];
139
140struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000141
Guido van Rossumed1170e1999-12-20 21:23:41 +0000142/* these tables define the module suffixes that Python recognizes */
143struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000144
Guido van Rossumed1170e1999-12-20 21:23:41 +0000145static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000147#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000149#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 {".pyc", "rb", PY_COMPILED},
151 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000152};
153
Victor Stinnerd0296212011-03-14 14:04:10 -0400154static PyObject *initstr = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200155_Py_IDENTIFIER(__path__);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000157/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158
159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 const struct filedescr *scan;
163 struct filedescr *filetab;
164 int countD = 0;
165 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000166
Victor Stinnerd0296212011-03-14 14:04:10 -0400167 initstr = PyUnicode_InternFromString("__init__");
168 if (initstr == NULL)
169 Py_FatalError("Can't initialize import variables");
170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* prepare _PyImport_Filetab: copy entries from
172 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
173 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000174#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
176 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
179 ++countS;
180 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
181 if (filetab == NULL)
182 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000183#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 memcpy(filetab, _PyImport_DynLoadFiletab,
185 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000186#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 memcpy(filetab + countD, _PyImport_StandardFiletab,
188 countS * sizeof(struct filedescr));
189 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (Py_OptimizeFlag) {
194 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
195 for (; filetab->suffix != NULL; filetab++) {
196 if (strcmp(filetab->suffix, ".pyc") == 0)
197 filetab->suffix = ".pyo";
198 }
199 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202void
Just van Rossum52e14d62002-12-30 22:08:05 +0000203_PyImportHooks_Init(void)
204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyObject *v, *path_hooks = NULL, *zimpimport;
206 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* adding sys.path_hooks and sys.path_importer_cache, setting up
209 zipimport */
210 if (PyType_Ready(&PyNullImporter_Type) < 0)
211 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (Py_VerboseFlag)
214 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 v = PyList_New(0);
217 if (v == NULL)
218 goto error;
219 err = PySys_SetObject("meta_path", v);
220 Py_DECREF(v);
221 if (err)
222 goto error;
223 v = PyDict_New();
224 if (v == NULL)
225 goto error;
226 err = PySys_SetObject("path_importer_cache", v);
227 Py_DECREF(v);
228 if (err)
229 goto error;
230 path_hooks = PyList_New(0);
231 if (path_hooks == NULL)
232 goto error;
233 err = PySys_SetObject("path_hooks", path_hooks);
234 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000235 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyErr_Print();
237 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
238 "path_importer_cache, or NullImporter failed"
239 );
240 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 zimpimport = PyImport_ImportModule("zipimport");
243 if (zimpimport == NULL) {
244 PyErr_Clear(); /* No zip import module -- okay */
245 if (Py_VerboseFlag)
246 PySys_WriteStderr("# can't import zipimport\n");
247 }
248 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200249 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200250 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
251 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_DECREF(zimpimport);
253 if (zipimporter == NULL) {
254 PyErr_Clear(); /* No zipimporter object -- okay */
255 if (Py_VerboseFlag)
256 PySys_WriteStderr(
257 "# can't import zipimport.zipimporter\n");
258 }
259 else {
260 /* sys.path_hooks.append(zipimporter) */
261 err = PyList_Append(path_hooks, zipimporter);
262 Py_DECREF(zipimporter);
263 if (err)
264 goto error;
265 if (Py_VerboseFlag)
266 PySys_WriteStderr(
267 "# installed zipimport hook\n");
268 }
269 }
270 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000271}
272
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000273/* Locking primitives to prevent parallel imports of the same module
274 in different threads to return with a partially loaded module.
275 These calls are serialized by the global interpreter lock. */
276
277#ifdef WITH_THREAD
278
Guido van Rossum49b56061998-10-01 20:42:43 +0000279#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280
Guido van Rossum65d5b571998-12-21 19:32:43 +0000281static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000282static long import_lock_thread = -1;
283static int import_lock_level = 0;
284
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000285void
286_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 long me = PyThread_get_thread_ident();
289 if (me == -1)
290 return; /* Too bad */
291 if (import_lock == NULL) {
292 import_lock = PyThread_allocate_lock();
293 if (import_lock == NULL)
294 return; /* Nothing much we can do. */
295 }
296 if (import_lock_thread == me) {
297 import_lock_level++;
298 return;
299 }
300 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
301 {
302 PyThreadState *tstate = PyEval_SaveThread();
303 PyThread_acquire_lock(import_lock, 1);
304 PyEval_RestoreThread(tstate);
305 }
306 import_lock_thread = me;
307 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000308}
309
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000310int
311_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 long me = PyThread_get_thread_ident();
314 if (me == -1 || import_lock == NULL)
315 return 0; /* Too bad */
316 if (import_lock_thread != me)
317 return -1;
318 import_lock_level--;
319 if (import_lock_level == 0) {
320 import_lock_thread = -1;
321 PyThread_release_lock(import_lock);
322 }
323 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000324}
325
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000326/* This function is called from PyOS_AfterFork to ensure that newly
327 created child processes do not share locks with the parent.
328 We now acquire the import lock around fork() calls but on some platforms
329 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000330
331void
332_PyImport_ReInitLock(void)
333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (import_lock != NULL)
335 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000336 if (import_lock_level > 1) {
337 /* Forked as a side effect of import */
338 long me = PyThread_get_thread_ident();
339 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100340 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000341 import_lock_thread = me;
342 import_lock_level--;
343 } else {
344 import_lock_thread = -1;
345 import_lock_level = 0;
346 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000347}
348
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000349#endif
350
Tim Peters69232342001-08-30 05:16:13 +0000351static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000352imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000353{
Tim Peters69232342001-08-30 05:16:13 +0000354#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000356#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000358#endif
359}
360
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000362imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000363{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000364#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000366#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 Py_INCREF(Py_None);
368 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000369}
370
371static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000372imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000373{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000374#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (_PyImport_ReleaseLock() < 0) {
376 PyErr_SetString(PyExc_RuntimeError,
377 "not holding the import lock");
378 return NULL;
379 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000380#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 Py_INCREF(Py_None);
382 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000383}
384
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100385void
386_PyImport_Fini(void)
387{
388 Py_XDECREF(extensions);
389 extensions = NULL;
390 PyMem_DEL(_PyImport_Filetab);
391 _PyImport_Filetab = NULL;
392#ifdef WITH_THREAD
393 if (import_lock != NULL) {
394 PyThread_free_lock(import_lock);
395 import_lock = NULL;
396 }
397#endif
398}
399
Guido van Rossumd8faa362007-04-27 19:54:29 +0000400static void
401imp_modules_reloading_clear(void)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyInterpreterState *interp = PyThreadState_Get()->interp;
404 if (interp->modules_reloading != NULL)
405 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406}
407
Guido van Rossum25ce5661997-08-02 03:10:38 +0000408/* Helper for sys */
409
410PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000411PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 PyInterpreterState *interp = PyThreadState_GET()->interp;
414 if (interp->modules == NULL)
415 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
416 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000417}
418
Guido van Rossum3f5da241990-12-20 15:06:42 +0000419
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000420/* List of names to clear in sys */
421static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 "path", "argv", "ps1", "ps2",
423 "last_type", "last_value", "last_traceback",
424 "path_hooks", "path_importer_cache", "meta_path",
425 /* misc stuff */
426 "flags", "float_info",
427 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000428};
429
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 "stdin", "__stdin__",
432 "stdout", "__stdout__",
433 "stderr", "__stderr__",
434 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435};
436
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000438/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000439
Guido van Rossum3f5da241990-12-20 15:06:42 +0000440void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000441PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *key, *value, *dict;
445 PyInterpreterState *interp = PyThreadState_GET()->interp;
446 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (modules == NULL)
449 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* Delete some special variables first. These are common
452 places where user values hide and people complain when their
453 destructors fail. Since the modules containing them are
454 deleted *last* of all, they would come too late in the normal
455 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 value = PyDict_GetItemString(modules, "builtins");
458 if (value != NULL && PyModule_Check(value)) {
459 dict = PyModule_GetDict(value);
460 if (Py_VerboseFlag)
461 PySys_WriteStderr("# clear builtins._\n");
462 PyDict_SetItemString(dict, "_", Py_None);
463 }
464 value = PyDict_GetItemString(modules, "sys");
465 if (value != NULL && PyModule_Check(value)) {
466 char **p;
467 PyObject *v;
468 dict = PyModule_GetDict(value);
469 for (p = sys_deletes; *p != NULL; p++) {
470 if (Py_VerboseFlag)
471 PySys_WriteStderr("# clear sys.%s\n", *p);
472 PyDict_SetItemString(dict, *p, Py_None);
473 }
474 for (p = sys_files; *p != NULL; p+=2) {
475 if (Py_VerboseFlag)
476 PySys_WriteStderr("# restore sys.%s\n", *p);
477 v = PyDict_GetItemString(dict, *(p+1));
478 if (v == NULL)
479 v = Py_None;
480 PyDict_SetItemString(dict, *p, v);
481 }
482 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* First, delete __main__ */
485 value = PyDict_GetItemString(modules, "__main__");
486 if (value != NULL && PyModule_Check(value)) {
487 if (Py_VerboseFlag)
488 PySys_WriteStderr("# cleanup __main__\n");
489 _PyModule_Clear(value);
490 PyDict_SetItemString(modules, "__main__", Py_None);
491 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* The special treatment of "builtins" here is because even
494 when it's not referenced as a module, its dictionary is
495 referenced by almost every module's __builtins__. Since
496 deleting a module clears its dictionary (even if there are
497 references left to it), we need to delete the "builtins"
498 module last. Likewise, we don't delete sys until the very
499 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 Also note that we 'delete' modules by replacing their entry
502 in the modules dict with None, rather than really deleting
503 them; this avoids a rehash of the modules dictionary and
504 also marks them as "non existent" so they won't be
505 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Next, repeatedly delete modules with a reference count of
508 one (skipping builtins and sys) and delete them */
509 do {
510 ndone = 0;
511 pos = 0;
512 while (PyDict_Next(modules, &pos, &key, &value)) {
513 if (value->ob_refcnt != 1)
514 continue;
515 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100516 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100518 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 continue;
520 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100521 PySys_FormatStderr(
522 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 _PyModule_Clear(value);
524 PyDict_SetItem(modules, key, Py_None);
525 ndone++;
526 }
527 }
528 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* Next, delete all modules (still skipping builtins and sys) */
531 pos = 0;
532 while (PyDict_Next(modules, &pos, &key, &value)) {
533 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100534 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100536 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 continue;
538 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100539 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 _PyModule_Clear(value);
541 PyDict_SetItem(modules, key, Py_None);
542 }
543 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* Next, delete sys and builtins (in that order) */
546 value = PyDict_GetItemString(modules, "sys");
547 if (value != NULL && PyModule_Check(value)) {
548 if (Py_VerboseFlag)
549 PySys_WriteStderr("# cleanup sys\n");
550 _PyModule_Clear(value);
551 PyDict_SetItemString(modules, "sys", Py_None);
552 }
553 value = PyDict_GetItemString(modules, "builtins");
554 if (value != NULL && PyModule_Check(value)) {
555 if (Py_VerboseFlag)
556 PySys_WriteStderr("# cleanup builtins\n");
557 _PyModule_Clear(value);
558 PyDict_SetItemString(modules, "builtins", Py_None);
559 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* Finally, clear and delete the modules directory */
562 PyDict_Clear(modules);
563 interp->modules = NULL;
564 Py_DECREF(modules);
565 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000566}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000567
568
Barry Warsaw28a691b2010-04-17 00:19:56 +0000569/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570
571long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000575}
576
577
Barry Warsaw28a691b2010-04-17 00:19:56 +0000578const char *
579PyImport_GetMagicTag(void)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000582}
583
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584/* Magic for extension modules (built-in as well as dynamically
585 loaded). To prevent initializing an extension module more than
586 once, we keep a static dictionary 'extensions' keyed by module name
587 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000588 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100589 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 immediately after the module initialization function succeeds. A
591 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100592 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000593
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000594 Modules which do support multiple initialization set their m_size
595 field to a non-negative number (indicating the size of the
596 module-specific state). They are still recorded in the extensions
597 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000598*/
599
600int
Victor Stinner95872862011-03-07 18:20:56 +0100601_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
602 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyObject *modules, *dict;
605 struct PyModuleDef *def;
606 if (extensions == NULL) {
607 extensions = PyDict_New();
608 if (extensions == NULL)
609 return -1;
610 }
611 if (mod == NULL || !PyModule_Check(mod)) {
612 PyErr_BadInternalCall();
613 return -1;
614 }
615 def = PyModule_GetDef(mod);
616 if (!def) {
617 PyErr_BadInternalCall();
618 return -1;
619 }
620 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100621 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return -1;
623 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100624 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return -1;
626 }
627 if (def->m_size == -1) {
628 if (def->m_base.m_copy) {
629 /* Somebody already imported the module,
630 likely under a different name.
631 XXX this should really not happen. */
632 Py_DECREF(def->m_base.m_copy);
633 def->m_base.m_copy = NULL;
634 }
635 dict = PyModule_GetDict(mod);
636 if (dict == NULL)
637 return -1;
638 def->m_base.m_copy = PyDict_Copy(dict);
639 if (def->m_base.m_copy == NULL)
640 return -1;
641 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000642 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644}
645
Victor Stinner49d3f252010-10-17 01:24:53 +0000646int
647_PyImport_FixupBuiltin(PyObject *mod, char *name)
648{
649 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100650 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100651 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100652 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000653 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100654 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
655 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000656 return res;
657}
658
Guido van Rossum25ce5661997-08-02 03:10:38 +0000659PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100660_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyObject *mod, *mdict;
663 PyModuleDef* def;
664 if (extensions == NULL)
665 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000666 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (def == NULL)
668 return NULL;
669 if (def->m_size == -1) {
670 /* Module does not support repeated initialization */
671 if (def->m_base.m_copy == NULL)
672 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100673 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (mod == NULL)
675 return NULL;
676 mdict = PyModule_GetDict(mod);
677 if (mdict == NULL)
678 return NULL;
679 if (PyDict_Update(mdict, def->m_base.m_copy))
680 return NULL;
681 }
682 else {
683 if (def->m_base.m_init == NULL)
684 return NULL;
685 mod = def->m_base.m_init();
686 if (mod == NULL)
687 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100688 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_DECREF(mod);
690 }
691 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100692 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_DECREF(mod);
694 return NULL;
695 }
696 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100697 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 name, filename);
699 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000700
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000701}
702
Victor Stinner49d3f252010-10-17 01:24:53 +0000703PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000704_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000705{
Victor Stinner95872862011-03-07 18:20:56 +0100706 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100707 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100708 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000709 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100710 res = _PyImport_FindExtensionObject(nameobj, nameobj);
711 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000712 return res;
713}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
715/* Get the module object corresponding to a module name.
716 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000717 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000718 Because the former action is most common, THIS DOES NOT RETURN A
719 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000720
Guido van Rossum79f25d91997-04-29 20:08:16 +0000721PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000722PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyObject *modules = PyImport_GetModuleDict();
725 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000726
Victor Stinner27ee0892011-03-04 12:57:09 +0000727 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyModule_Check(m))
729 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000730 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (m == NULL)
732 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000733 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 Py_DECREF(m);
735 return NULL;
736 }
737 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740}
741
Victor Stinner27ee0892011-03-04 12:57:09 +0000742PyObject *
743PyImport_AddModule(const char *name)
744{
745 PyObject *nameobj, *module;
746 nameobj = PyUnicode_FromString(name);
747 if (nameobj == NULL)
748 return NULL;
749 module = PyImport_AddModuleObject(nameobj);
750 Py_DECREF(nameobj);
751 return module;
752}
753
754
Tim Peters1cd70172004-08-02 03:52:12 +0000755/* Remove name from sys.modules, if it's there. */
756static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000757remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000760 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000762 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 Py_FatalError("import: deleting existing key in"
764 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000765}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000766
Victor Stinnerc9abda02011-03-14 13:33:46 -0400767static PyObject * get_sourcefile(PyObject *filename);
768static PyObject *make_source_pathname(PyObject *pathname);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200769static PyObject* make_compiled_pathname(PyObject *pathname, int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000770
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000771/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000772 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
773 * removed from sys.modules, to avoid leaving damaged module objects
774 * in sys.modules. The caller may wish to restore the original
775 * module object (if any) in this case; PyImport_ReloadModule is an
776 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000777 *
778 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
779 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000780 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000781PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000782PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 return PyImport_ExecCodeModuleWithPathnames(
785 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000786}
787
788PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000789PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return PyImport_ExecCodeModuleWithPathnames(
792 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000793}
794
795PyObject *
796PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000798{
Victor Stinner27ee0892011-03-04 12:57:09 +0000799 PyObject *m = NULL;
800 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
801
802 nameobj = PyUnicode_FromString(name);
803 if (nameobj == NULL)
804 return NULL;
805
806 if (pathname != NULL) {
807 pathobj = PyUnicode_DecodeFSDefault(pathname);
808 if (pathobj == NULL)
809 goto error;
810 } else
811 pathobj = NULL;
812 if (cpathname != NULL) {
813 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
814 if (cpathobj == NULL)
815 goto error;
816 } else
817 cpathobj = NULL;
818 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
819error:
820 Py_DECREF(nameobj);
821 Py_XDECREF(pathobj);
822 Py_XDECREF(cpathobj);
823 return m;
824}
825
826PyObject*
827PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
828 PyObject *cpathname)
829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *modules = PyImport_GetModuleDict();
831 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000832
Victor Stinner27ee0892011-03-04 12:57:09 +0000833 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (m == NULL)
835 return NULL;
836 /* If the module is being reloaded, we get the old module back
837 and re-use its dict to exec the new code. */
838 d = PyModule_GetDict(m);
839 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
840 if (PyDict_SetItemString(d, "__builtins__",
841 PyEval_GetBuiltins()) != 0)
842 goto error;
843 }
844 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400846 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (v == NULL)
848 PyErr_Clear();
849 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000850 else
851 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (v == NULL) {
853 v = ((PyCodeObject *)co)->co_filename;
854 Py_INCREF(v);
855 }
856 if (PyDict_SetItemString(d, "__file__", v) != 0)
857 PyErr_Clear(); /* Not important enough to report */
858 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000861 if (cpathname != NULL)
862 v = cpathname;
863 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (PyDict_SetItemString(d, "__cached__", v) != 0)
866 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000867
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000868 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (v == NULL)
870 goto error;
871 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000872
Victor Stinner27ee0892011-03-04 12:57:09 +0000873 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000875 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 name);
877 return NULL;
878 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000883
884 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 remove_module(name);
886 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887}
888
889
Barry Warsaw28a691b2010-04-17 00:19:56 +0000890/* Like strrchr(string, '/') but searches for the rightmost of either SEP
891 or ALTSEP, if the latter is defined.
892*/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200893static Py_UCS4*
894rightmost_sep(Py_UCS4 *s)
Victor Stinnerc9abda02011-03-14 13:33:46 -0400895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 Py_UCS4 *found, c;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400897 for (found = NULL; (c = *s); s++) {
898 if (c == SEP
899#ifdef ALTSEP
900 || c == ALTSEP
901#endif
902 )
903 {
904 found = s;
905 }
906 }
907 return found;
908}
909
Martin v. Löwis2db72862011-10-23 17:29:08 +0200910/* Like rightmost_sep, but operate on unicode objects. */
911static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200912rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200913{
914 Py_ssize_t found, i;
915 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200916 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200917 c = PyUnicode_READ_CHAR(o, i);
918 if (c == SEP
919#ifdef ALTSEP
920 || c == ALTSEP
921#endif
922 )
923 {
924 found = i;
925 }
926 }
927 return found;
928}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400929
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000930/* Given a pathname for a Python source file, fill a buffer with the
931 pathname for the corresponding compiled file. Return the pathname
932 for the compiled file, or NULL if there's no space in the buffer.
Victor Stinner2f42ae52011-03-20 00:41:24 +0100933 Doesn't set an exception.
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000934
Martin v. Löwis30260a72011-10-23 17:35:46 +0200935 foo.py -> __pycache__/foo.<tag>.pyc
936
937 pathstr is assumed to be "ready".
938*/
Victor Stinner2f42ae52011-03-20 00:41:24 +0100939
940static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200941make_compiled_pathname(PyObject *pathstr, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000942{
Martin v. Löwis2db72862011-10-23 17:29:08 +0200943 PyObject *result;
944 Py_ssize_t fname, ext, len, i, pos, taglen;
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200945 Py_ssize_t pycache_len = sizeof(CACHEDIR) - 1;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200946 int kind;
947 void *data;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200948 Py_UCS4 lastsep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000949
Martin v. Löwis2db72862011-10-23 17:29:08 +0200950 /* Compute the output string size. */
951 len = PyUnicode_GET_LENGTH(pathstr);
952 /* If there is no separator, this returns -1, so
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200953 fname will be 0. */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200954 fname = rightmost_sep_obj(pathstr, 0, len) + 1;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200955 /* Windows: re-use the last separator character (/ or \\) when
956 appending the __pycache__ path. */
957 if (fname > 0)
958 lastsep = PyUnicode_READ_CHAR(pathstr, fname -1);
959 else
960 lastsep = SEP;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200961 ext = fname - 1;
962 for(i = fname; i < len; i++)
963 if (PyUnicode_READ_CHAR(pathstr, i) == '.')
964 ext = i + 1;
965 if (ext < fname)
966 /* No dot in filename; use entire filename */
967 ext = len;
968
969 /* result = pathstr[:fname] + "__pycache__" + SEP +
970 pathstr[fname:ext] + tag + ".py[co]" */
971 taglen = strlen(pyc_tag);
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200972 result = PyUnicode_New(ext + pycache_len + 1 + taglen + 4,
Martin v. Löwis2db72862011-10-23 17:29:08 +0200973 PyUnicode_MAX_CHAR_VALUE(pathstr));
974 if (!result)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 return NULL;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200976 kind = PyUnicode_KIND(result);
977 data = PyUnicode_DATA(result);
978 PyUnicode_CopyCharacters(result, 0, pathstr, 0, fname);
979 pos = fname;
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200980 for (i = 0; i < pycache_len; i++)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200981 PyUnicode_WRITE(kind, data, pos++, CACHEDIR[i]);
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200982 PyUnicode_WRITE(kind, data, pos++, lastsep);
Martin v. Löwis2db72862011-10-23 17:29:08 +0200983 PyUnicode_CopyCharacters(result, pos, pathstr,
984 fname, ext - fname);
985 pos += ext - fname;
986 for (i = 0; pyc_tag[i]; i++)
987 PyUnicode_WRITE(kind, data, pos++, pyc_tag[i]);
988 PyUnicode_WRITE(kind, data, pos++, '.');
989 PyUnicode_WRITE(kind, data, pos++, 'p');
990 PyUnicode_WRITE(kind, data, pos++, 'y');
991 PyUnicode_WRITE(kind, data, pos++, debug ? 'c' : 'o');
992 return result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000993}
994
995
Barry Warsaw28a691b2010-04-17 00:19:56 +0000996/* Given a pathname to a Python byte compiled file, return the path to the
997 source file, if the path matches the PEP 3147 format. This does not check
998 for any file existence, however, if the pyc file name does not match PEP
999 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001000 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001
Victor Stinnerc9abda02011-03-14 13:33:46 -04001002 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
1003
1004static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001005make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +00001006{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001007 Py_ssize_t left, right, dot0, dot1, len;
1008 Py_ssize_t i, j;
1009 PyObject *result;
1010 int kind;
1011 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001012
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001013 len = PyUnicode_GET_LENGTH(path);
1014 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Look back two slashes from the end. In between these two slashes
1018 must be the string __pycache__ or this is not a PEP 3147 style
1019 path. It's possible for there to be only one slash.
1020 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001021 right = rightmost_sep_obj(path, 0, len);
1022 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001024 left = rightmost_sep_obj(path, 0, right);
1025 if (left == -1)
1026 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 else
1028 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001029 if (right-left != sizeof(CACHEDIR)-1)
1030 return NULL;
1031 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
1032 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
1033 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Now verify that the path component to the right of the last slash
1036 has two dots in it.
1037 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001038 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
1039 if (dot0 < 0)
1040 return NULL;
1041 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
1042 if (dot1 < 0)
1043 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001045 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
1046 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* This is a PEP 3147 path. Start by copying everything from the
1049 start of pathname up to and including the leftmost slash. Then
1050 copy the file's basename, removing the magic tag and adding a .py
1051 suffix.
1052 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001053 result = PyUnicode_New(left + (dot0-right) + 2,
1054 PyUnicode_MAX_CHAR_VALUE(path));
1055 if (!result)
1056 return NULL;
1057 kind = PyUnicode_KIND(result);
1058 data = PyUnicode_DATA(result);
1059 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
1060 PyUnicode_CopyCharacters(result, left, path, right+1,
1061 (j = dot0-right));
1062 PyUnicode_WRITE(kind, data, i+j, 'p');
1063 PyUnicode_WRITE(kind, data, i+j+1, 'y');
1064 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001065}
1066
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001067/* Given a pathname for a Python source file, its time of last
1068 modification, and a pathname for a compiled file, check whether the
1069 compiled file represents the same version of the source. If so,
1070 return a FILE pointer for the compiled file, positioned just after
1071 the header; if not, return NULL.
1072 Doesn't set an exception. */
1073
1074static FILE *
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001075check_compiled_module(PyObject *pathname, struct stat *srcstat, PyObject *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 FILE *fp;
1078 long magic;
1079 long pyc_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001080 long pyc_size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001081
Victor Stinner2f42ae52011-03-20 00:41:24 +01001082 fp = _Py_fopen(cpathname, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 if (fp == NULL)
1084 return NULL;
1085 magic = PyMarshal_ReadLongFromFile(fp);
1086 if (magic != pyc_magic) {
1087 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001088 PySys_FormatStderr("# %R has bad magic\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 fclose(fp);
1090 return NULL;
1091 }
1092 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001093 if (pyc_mtime != srcstat->st_mtime) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001095 PySys_FormatStderr("# %R has bad mtime\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 fclose(fp);
1097 return NULL;
1098 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001099 pyc_size = PyMarshal_ReadLongFromFile(fp);
1100 if (pyc_size != (srcstat->st_size & 0xFFFFFFFF)) {
1101 if (Py_VerboseFlag)
1102 PySys_FormatStderr("# %R has bad size\n", cpathname);
1103 fclose(fp);
1104 return NULL;
1105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001107 PySys_FormatStderr("# %R matches %R\n", cpathname, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001109}
1110
1111
1112/* Read a code object from a file and check it for validity */
1113
Guido van Rossum79f25d91997-04-29 20:08:16 +00001114static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001115read_compiled_module(PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 co = PyMarshal_ReadLastObjectFromFile(fp);
1120 if (co == NULL)
1121 return NULL;
1122 if (!PyCode_Check(co)) {
1123 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001124 "Non-code object in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 Py_DECREF(co);
1126 return NULL;
1127 }
1128 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001129}
1130
1131
1132/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001133 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001134
Guido van Rossum79f25d91997-04-29 20:08:16 +00001135static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001136load_compiled_module(PyObject *name, PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 long magic;
1139 PyCodeObject *co;
1140 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 magic = PyMarshal_ReadLongFromFile(fp);
1143 if (magic != pyc_magic) {
1144 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001145 "Bad magic number in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return NULL;
1147 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001148 /* Skip mtime and size */
1149 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 (void) PyMarshal_ReadLongFromFile(fp);
1151 co = read_compiled_module(cpathname, fp);
1152 if (co == NULL)
1153 return NULL;
1154 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001155 PySys_FormatStderr("import %U # precompiled from %R\n",
1156 name, cpathname);
1157 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1158 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001162}
1163
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001164/* Parse a source file and return the corresponding code object */
1165
Guido van Rossum79f25d91997-04-29 20:08:16 +00001166static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001167parse_source_module(PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001168{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001169 PyCodeObject *co;
1170 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 mod_ty mod;
1172 PyCompilerFlags flags;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001173 PyArena *arena;
1174
1175 pathbytes = PyUnicode_EncodeFSDefault(pathname);
1176 if (pathbytes == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001178
Victor Stinner2f42ae52011-03-20 00:41:24 +01001179 arena = PyArena_New();
1180 if (arena == NULL) {
1181 Py_DECREF(pathbytes);
1182 return NULL;
1183 }
1184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 flags.cf_flags = 0;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001186 mod = PyParser_ASTFromFile(fp, PyBytes_AS_STRING(pathbytes), NULL,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_file_input, 0, 0, &flags,
1188 NULL, arena);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001189 if (mod != NULL)
1190 co = PyAST_Compile(mod, PyBytes_AS_STRING(pathbytes), NULL, arena);
1191 else
1192 co = NULL;
1193 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyArena_Free(arena);
1195 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001196}
1197
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001198/* Write a compiled module to a file, placing the time of last
1199 modification of its source into the header.
1200 Errors are ignored, if a write error occurs an attempt is made to
1201 remove the file. */
1202
1203static void
Victor Stinner2f42ae52011-03-20 00:41:24 +01001204write_compiled_module(PyCodeObject *co, PyObject *cpathname,
1205 struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001206{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207 Py_UCS4 *cpathname_ucs4;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 time_t mtime = srcstat->st_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001210 long size = srcstat->st_size & 0xFFFFFFFF;
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001211 PyObject *cpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001212#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Victor Stinner1f795172011-11-17 00:45:54 +01001214 wchar_t *wdirname, *wpathname, *wpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001215#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 mode_t dirmode = (srcstat->st_mode |
1217 S_IXUSR | S_IXGRP | S_IXOTH |
1218 S_IWUSR | S_IWGRP | S_IWOTH);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001219 PyObject *dirbytes;
Antoine Pitrou707033a2011-10-17 19:28:44 +02001220 PyObject *cpathbytes, *cpathbytes_tmp;
Victor Stinner783c82c2011-04-20 03:27:51 +02001221#endif
Charles-François Natali0c929d92011-11-10 19:12:29 +01001222 int fd;
Victor Stinner783c82c2011-04-20 03:27:51 +02001223 PyObject *dirname;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 Py_UCS4 *dirsep;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001225 int res, ok;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 /* Ensure that the __pycache__ directory exists. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 cpathname_ucs4 = PyUnicode_AsUCS4Copy(cpathname);
1229 if (!cpathname_ucs4)
1230 return;
1231 dirsep = rightmost_sep(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001232 if (dirsep == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001234 PySys_FormatStderr("# no %s path found %R\n", CACHEDIR, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return;
1236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001237 dirname = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
1238 cpathname_ucs4,
1239 dirsep - cpathname_ucs4);
1240 PyMem_Free(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001241 if (dirname == NULL) {
1242 PyErr_Clear();
1243 return;
1244 }
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001245
1246#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001247 wdirname = PyUnicode_AsUnicode(dirname);
1248 if (wdirname == NULL) {
1249 PyErr_Clear();
1250 return;
1251 }
1252 res = CreateDirectoryW(wdirname, NULL);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001253 ok = (res != 0);
1254 if (!ok && GetLastError() == ERROR_ALREADY_EXISTS)
1255 ok = 1;
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001256#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001257 dirbytes = PyUnicode_EncodeFSDefault(dirname);
1258 if (dirbytes == NULL) {
1259 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return;
1261 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001262 res = mkdir(PyBytes_AS_STRING(dirbytes), dirmode);
1263 Py_DECREF(dirbytes);
1264 if (0 <= res)
1265 ok = 1;
1266 else
1267 ok = (errno == EEXIST);
1268#endif
1269 if (!ok) {
1270 if (Py_VerboseFlag)
1271 PySys_FormatStderr("# cannot create cache dir %R\n", dirname);
1272 Py_DECREF(dirname);
1273 return;
1274 }
1275 Py_DECREF(dirname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001276
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001277 /* We first write to a tmp file and then take advantage
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001278 of atomic renaming (which *should* be true even under Windows).
1279 As in importlib, we use id(something) to generate a pseudo-random
1280 filename. mkstemp() can't be used since it doesn't allow specifying
1281 the file access permissions.
1282 */
1283 cpathname_tmp = PyUnicode_FromFormat("%U.%zd",
1284 cpathname, (Py_ssize_t) co);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001285 if (cpathname_tmp == NULL) {
1286 PyErr_Clear();
1287 return;
1288 }
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001289#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001290 wpathname = PyUnicode_AsUnicode(cpathname);
1291 if (wpathname == NULL) {
1292 PyErr_Clear();
1293 return;
1294 }
1295 wpathname_tmp = PyUnicode_AsUnicode(cpathname_tmp);
1296 if (wpathname_tmp == NULL) {
1297 PyErr_Clear();
1298 return;
1299 }
1300
1301 (void)DeleteFileW(wpathname_tmp);
1302 fd = _wopen(wpathname_tmp,
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001303 O_EXCL | O_CREAT | O_WRONLY | O_BINARY,
1304 mode);
Victor Stinner783c82c2011-04-20 03:27:51 +02001305 if (0 <= fd)
1306 fp = fdopen(fd, "wb");
1307 else
1308 fp = NULL;
1309#else
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001310 cpathbytes_tmp = PyUnicode_EncodeFSDefault(cpathname_tmp);
1311 Py_DECREF(cpathname_tmp);
1312 if (cpathbytes_tmp == NULL) {
1313 PyErr_Clear();
1314 return;
1315 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001316 cpathbytes = PyUnicode_EncodeFSDefault(cpathname);
1317 if (cpathbytes == NULL) {
1318 PyErr_Clear();
1319 return;
1320 }
Charles-François Natali0c929d92011-11-10 19:12:29 +01001321 fd = open(PyBytes_AS_STRING(cpathbytes_tmp),
1322 O_CREAT | O_EXCL | O_WRONLY, 0666);
Charles-François Natalie695eec2011-10-31 20:47:31 +01001323 if (0 <= fd)
1324 fp = fdopen(fd, "wb");
1325 else
1326 fp = NULL;
Victor Stinner783c82c2011-04-20 03:27:51 +02001327#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (fp == NULL) {
1329 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001330 PySys_FormatStderr(
1331 "# can't create %R\n", cpathname);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001332#ifdef MS_WINDOWS
1333 Py_DECREF(cpathname_tmp);
1334#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001335 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001336 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001337#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 return;
1339 }
1340 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001341 /* First write a 0 for mtime and size */
1342 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1344 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001345 fflush(fp);
Antoine Pitrou58161662012-01-25 18:06:07 +01001346 /* Now write the true mtime and size (as 32-bit fields) */
Antoine Pitrou707033a2011-10-17 19:28:44 +02001347 fseek(fp, 4L, 0);
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001348 assert(mtime <= 0xFFFFFFFF);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001349 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001350 PyMarshal_WriteLongToFile(size, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (fflush(fp) != 0 || ferror(fp)) {
1352 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001353 PySys_FormatStderr("# can't write %R\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 /* Don't keep partial file */
1355 fclose(fp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001356#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001357 (void)DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001358 Py_DECREF(cpathname_tmp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001359#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001360 (void) unlink(PyBytes_AS_STRING(cpathbytes_tmp));
Victor Stinner2f42ae52011-03-20 00:41:24 +01001361 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001362 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001363#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 return;
1365 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 fclose(fp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001367 /* Do a (hopefully) atomic rename */
1368#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001369 if (!MoveFileExW(wpathname_tmp, wpathname, MOVEFILE_REPLACE_EXISTING)) {
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001370 if (Py_VerboseFlag)
1371 PySys_FormatStderr("# can't write %R\n", cpathname);
1372 /* Don't keep tmp file */
Victor Stinner1f795172011-11-17 00:45:54 +01001373 (void) DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001374 Py_DECREF(cpathname_tmp);
1375 return;
1376 }
1377 Py_DECREF(cpathname_tmp);
1378#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001379 if (rename(PyBytes_AS_STRING(cpathbytes_tmp),
1380 PyBytes_AS_STRING(cpathbytes))) {
1381 if (Py_VerboseFlag)
1382 PySys_FormatStderr("# can't write %R\n", cpathname);
1383 /* Don't keep tmp file */
1384 unlink(PyBytes_AS_STRING(cpathbytes_tmp));
1385 Py_DECREF(cpathbytes);
1386 Py_DECREF(cpathbytes_tmp);
1387 return;
1388 }
1389 Py_DECREF(cpathbytes);
1390 Py_DECREF(cpathbytes_tmp);
1391#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001393 PySys_FormatStderr("# wrote %R\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001394}
1395
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001396static void
1397update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PyObject *constants, *tmp;
1400 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (PyUnicode_Compare(co->co_filename, oldname))
1403 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 tmp = co->co_filename;
1406 co->co_filename = newname;
1407 Py_INCREF(co->co_filename);
1408 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 constants = co->co_consts;
1411 n = PyTuple_GET_SIZE(constants);
1412 for (i = 0; i < n; i++) {
1413 tmp = PyTuple_GET_ITEM(constants, i);
1414 if (PyCode_Check(tmp))
1415 update_code_filenames((PyCodeObject *)tmp,
1416 oldname, newname);
1417 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001418}
1419
Victor Stinner2f42ae52011-03-20 00:41:24 +01001420static void
1421update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001422{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001423 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001424
Victor Stinner2f42ae52011-03-20 00:41:24 +01001425 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1426 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 oldname = co->co_filename;
1429 Py_INCREF(oldname);
1430 update_code_filenames(co, oldname, newname);
1431 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001432}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001433
Brett Cannon442c9b92011-03-23 16:14:42 -07001434static PyObject *
1435imp_fix_co_filename(PyObject *self, PyObject *args)
1436{
1437 PyObject *co;
1438 PyObject *file_path;
1439
1440 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1441 return NULL;
1442
1443 if (!PyCode_Check(co)) {
1444 PyErr_SetString(PyExc_TypeError,
1445 "first argument must be a code object");
1446 return NULL;
1447 }
1448
1449 if (!PyUnicode_Check(file_path)) {
1450 PyErr_SetString(PyExc_TypeError,
1451 "second argument must be a string");
1452 return NULL;
1453 }
1454
1455 update_compiled_module((PyCodeObject*)co, file_path);
1456
1457 Py_RETURN_NONE;
1458}
1459
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001460/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001461 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1462 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001463
Guido van Rossum79f25d91997-04-29 20:08:16 +00001464static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001465load_source_module(PyObject *name, PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 struct stat st;
1468 FILE *fpc;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001469 PyObject *cpathname = NULL, *cpathbytes = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyCodeObject *co;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001471 PyObject *m = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (fstat(fileno(fp), &st) != 0) {
1474 PyErr_Format(PyExc_RuntimeError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001475 "unable to get file status from %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001477 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 }
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001479 if (sizeof st.st_mtime > 4) {
1480 /* Python's .pyc timestamp handling presumes that the timestamp fits
1481 in 4 bytes. Since the code only does an equality comparison,
1482 ordering is not important and we can safely ignore the higher bits
1483 (collisions are extremely unlikely).
1484 */
1485 st.st_mtime &= 0xFFFFFFFF;
1486 }
Martin v. Löwis30260a72011-10-23 17:35:46 +02001487 if (PyUnicode_READY(pathname) < 0)
1488 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001489 cpathname = make_compiled_pathname(pathname, !Py_OptimizeFlag);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001490
1491 if (cpathname != NULL)
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001492 fpc = check_compiled_module(pathname, &st, cpathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001493 else
1494 fpc = NULL;
1495
1496 if (fpc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 co = read_compiled_module(cpathname, fpc);
1498 fclose(fpc);
1499 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001500 goto error;
1501 update_compiled_module(co, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001503 PySys_FormatStderr("import %U # precompiled from %R\n",
1504 name, cpathname);
1505 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1506 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 }
1508 else {
1509 co = parse_source_module(pathname, fp);
1510 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001511 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001513 PySys_FormatStderr("import %U # from %R\n",
Victor Stinner98dbba52011-03-14 15:15:47 -04001514 name, pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001515 if (cpathname != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1517 if (ro == NULL || !PyObject_IsTrue(ro))
1518 write_compiled_module(co, cpathname, &st);
1519 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001520 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1521 pathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001524
Victor Stinner2f42ae52011-03-20 00:41:24 +01001525error:
1526 Py_XDECREF(cpathbytes);
1527 Py_XDECREF(cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001529}
1530
Christian Heimes3b06e532008-01-07 20:12:44 +00001531/* Get source file -> unicode or None
1532 * Returns the path to the py file if available, else the given path
1533 */
1534static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001535get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001538 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001539 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001541 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001544 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001546
Victor Stinnerc9abda02011-03-14 13:33:46 -04001547 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001548 fileuni = PyUnicode_AsUCS4Copy(filename);
1549 if (!fileuni)
1550 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001551 if (len < 5
1552 || fileuni[len-4] != '.'
1553 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1554 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1555 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* Start by trying to turn PEP 3147 path into source path. If that
1558 * fails, just chop off the trailing character, i.e. legacy pyc path
1559 * to py.
1560 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001561 py = make_source_pathname(filename);
1562 if (py == NULL) {
1563 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001566 if (py == NULL)
1567 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001568
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001569 err = _Py_stat(py, &statbuf);
1570 if (err == -2)
1571 goto error;
1572 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001573 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001574 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001575 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001576 Py_DECREF(py);
1577 goto unchanged;
1578
1579error:
1580 PyErr_Clear();
1581unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001582 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001583 Py_INCREF(filename);
1584 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001585}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001586
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001587/* Forward */
Victor Stinner41c5fec2011-03-13 21:46:30 -04001588static PyObject *load_module(PyObject *, FILE *, PyObject *, int, PyObject *);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001589static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001590 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001591static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001592
1593/* Load a package and return its module object WITH INCREMENTED
1594 REFERENCE COUNT */
1595
1596static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001597load_package(PyObject *name, PyObject *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001598{
Victor Stinner41c5fec2011-03-13 21:46:30 -04001599 PyObject *m, *d, *bufobj;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001600 PyObject *file = NULL, *path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 int err;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001602 FILE *fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001604
Victor Stinnerc9abda02011-03-14 13:33:46 -04001605 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (m == NULL)
1607 return NULL;
1608 if (Py_VerboseFlag)
Victor Stinner98dbba52011-03-14 15:15:47 -04001609 PySys_FormatStderr("import %U # directory %R\n",
1610 name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 file = get_sourcefile(pathname);
1612 if (file == NULL)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001613 return NULL;
1614 path_list = Py_BuildValue("[O]", file);
1615 if (path_list == NULL) {
1616 Py_DECREF(file);
1617 return NULL;
1618 }
1619 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 err = PyDict_SetItemString(d, "__file__", file);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001621 Py_DECREF(file);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (err == 0)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001623 err = PyDict_SetItemString(d, "__path__", path_list);
1624 if (err != 0) {
1625 Py_DECREF(path_list);
1626 return NULL;
1627 }
Victor Stinner533d7832011-03-14 13:22:54 -04001628 fdp = find_module(name, initstr, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001629 &bufobj, &fp, NULL);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001630 Py_DECREF(path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (fdp == NULL) {
1632 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1633 PyErr_Clear();
1634 Py_INCREF(m);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001635 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 }
1637 else
Victor Stinnerc9abda02011-03-14 13:33:46 -04001638 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001640 m = load_module(name, fp, bufobj, fdp->type, NULL);
1641 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (fp != NULL)
1643 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001645}
1646
1647
1648/* Helper to test for built-in module */
1649
1650static int
Victor Stinner95872862011-03-07 18:20:56 +01001651is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001652{
Victor Stinner95872862011-03-07 18:20:56 +01001653 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001655 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1656 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (PyImport_Inittab[i].initfunc == NULL)
1658 return -1;
1659 else
1660 return 1;
1661 }
1662 }
1663 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001664}
1665
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001666
Just van Rossum52e14d62002-12-30 22:08:05 +00001667/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1668 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001669 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001670 that can handle the path item. Return None if no hook could;
1671 this tells our caller it should fall back to the builtin
1672 import mechanism. Cache the result in path_importer_cache.
1673 Returns a borrowed reference. */
1674
1675static PyObject *
1676get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyObject *importer;
1680 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* These conditions are the caller's responsibility: */
1683 assert(PyList_Check(path_hooks));
1684 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 nhooks = PyList_Size(path_hooks);
1687 if (nhooks < 0)
1688 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 importer = PyDict_GetItem(path_importer_cache, p);
1691 if (importer != NULL)
1692 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* set path_importer_cache[p] to None to avoid recursion */
1695 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1696 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 for (j = 0; j < nhooks; j++) {
1699 PyObject *hook = PyList_GetItem(path_hooks, j);
1700 if (hook == NULL)
1701 return NULL;
1702 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1703 if (importer != NULL)
1704 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1707 return NULL;
1708 }
1709 PyErr_Clear();
1710 }
1711 if (importer == NULL) {
1712 importer = PyObject_CallFunctionObjArgs(
1713 (PyObject *)&PyNullImporter_Type, p, NULL
1714 );
1715 if (importer == NULL) {
1716 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1717 PyErr_Clear();
1718 return Py_None;
1719 }
1720 }
1721 }
1722 if (importer != NULL) {
1723 int err = PyDict_SetItem(path_importer_cache, p, importer);
1724 Py_DECREF(importer);
1725 if (err != 0)
1726 return NULL;
1727 }
1728 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001729}
1730
Christian Heimes9cd17752007-11-18 19:35:23 +00001731PyAPI_FUNC(PyObject *)
1732PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1736 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1737 importer = get_path_importer(path_importer_cache,
1738 path_hooks, path);
1739 }
1740 }
1741 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1742 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001743}
1744
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001745/* Search the path (default sys.path) for a module. Return the
1746 corresponding filedescr struct, and (via return arguments) the
1747 pathname and an open file. Return NULL if the module is not found. */
1748
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001749#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001750extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1751 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001752#endif
1753
Victor Stinner547a2a62011-03-20 03:07:28 +01001754/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001755static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001756static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001757static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001758
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001759/* Get the path of a module: get its importer and call importer.find_module()
1760 hook, or check if the module if a package (if path/__init__.py exists).
1761
1762 -1: error: a Python error occurred
1763 0: ignore: an error occurred because of invalid data, but the error is not
1764 important enough to be reported.
1765 1: get path: module not found, but *buf contains its path
1766 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1767 and *buf is the path */
1768
1769static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001770find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001771 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001772 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001773{
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001774 PyObject *path_unicode, *filename = NULL;
1775 Py_ssize_t len, pos;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001776 struct stat statbuf;
1777 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001778 int err, result, addsep;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001779
1780 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001781 Py_INCREF(path);
1782 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001783 }
1784 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001785 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1786 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1787 if (path_unicode == NULL)
1788 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001789 }
1790 else
1791 return 0;
1792
Victor Stinner46084ba2011-10-06 02:39:42 +02001793 if (PyUnicode_READY(path_unicode))
1794 return -1;
1795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 len = PyUnicode_GET_LENGTH(path_unicode);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001797 if (PyUnicode_FindChar(path_unicode, 0, 0, len, 1) != -1) {
1798 result = 0;
1799 goto out; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001800 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001801
1802 /* sys.path_hooks import hook */
1803 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001804 _Py_IDENTIFIER(find_module);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001805 PyObject *importer;
1806
1807 importer = get_path_importer(path_importer_cache,
1808 path_hooks, path);
1809 if (importer == NULL) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001810 result = -1;
1811 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001812 }
1813 /* Note: importer is a borrowed reference */
1814 if (importer != Py_None) {
1815 PyObject *loader;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001816 loader = _PyObject_CallMethodId(importer,
1817 &PyId_find_module, "O", fullname);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001818 if (loader == NULL) {
1819 result = -1; /* error */
1820 goto out;
1821 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001822 if (loader != Py_None) {
1823 /* a loader was found */
1824 *p_loader = loader;
1825 *p_fd = &importhookdescr;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001826 result = 2;
1827 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001828 }
1829 Py_DECREF(loader);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001830 result = 0;
1831 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001832 }
1833 }
1834 /* no hook was found, use builtin import */
1835
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001836 addsep = 0;
1837 if (len > 0 && PyUnicode_READ_CHAR(path_unicode, len-1) != SEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001838#ifdef ALTSEP
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001839 && PyUnicode_READ_CHAR(path_unicode, len-1) != ALTSEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001840#endif
1841 )
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001842 addsep = 1;
1843 filename = PyUnicode_New(len + PyUnicode_GET_LENGTH(name) + addsep,
1844 Py_MAX(PyUnicode_MAX_CHAR_VALUE(path_unicode),
1845 PyUnicode_MAX_CHAR_VALUE(name)));
1846 if (filename == NULL) {
1847 result = -1;
1848 goto out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 }
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001850 PyUnicode_CopyCharacters(filename, 0, path_unicode, 0, len);
1851 pos = len;
1852 if (addsep)
Victor Stinner1f795172011-11-17 00:45:54 +01001853 PyUnicode_WRITE(PyUnicode_KIND(filename),
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001854 PyUnicode_DATA(filename),
1855 pos++, SEP);
Victor Stinner1f795172011-11-17 00:45:54 +01001856 PyUnicode_CopyCharacters(filename, pos, name, 0,
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001857 PyUnicode_GET_LENGTH(name));
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001858
1859 /* Check for package import (buf holds a directory name,
1860 and there's an __init__ module in that directory */
1861#ifdef HAVE_STAT
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001862 err = _Py_stat(filename, &statbuf);
1863 if (err == -2) {
1864 result = -1;
1865 goto out;
1866 }
1867 if (err == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001868 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1869 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001870 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001871
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001872 match = case_ok(filename, 0, name);
1873 if (match < 0) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001874 result = -1;
1875 goto out;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001876 }
1877 if (match) { /* case matches */
1878 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001879 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001880 filename = NULL;
Victor Stinnerd0296212011-03-14 14:04:10 -04001881 *p_fd = &fd_package;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001882 result = 2;
1883 goto out;
Victor Stinnerd0296212011-03-14 14:04:10 -04001884 }
1885 else {
1886 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001887 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001888 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001889 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001890 if (err) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001891 result = -1;
1892 goto out;
Victor Stinner547a2a62011-03-20 03:07:28 +01001893 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001894 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001895 }
1896 }
1897#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001898 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001899 filename = NULL;
1900 result = 1;
1901 out:
1902 Py_DECREF(path_unicode);
1903 Py_XDECREF(filename);
1904 return result;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001905}
1906
1907/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001908 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001909
1910 If the module is found, return a file descriptor, write the path in
1911 *p_filename, write the pointer to the file object into *p_fp, and (if
1912 p_loader is not NULL) the loader into *p_loader.
1913
1914 Otherwise, raise an exception and return NULL. */
1915
Victor Stinner37580282011-03-20 01:34:43 +01001916static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001917find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001918 PyObject *search_path_list, PyObject *path_hooks,
1919 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001920 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 struct filedescr *fdp = NULL;
1924 char *filemode;
1925 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001926 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001927 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001928 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001929
Victor Stinner37580282011-03-20 01:34:43 +01001930 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001932 PyObject *path;
1933 int ok;
1934
1935 path = PyList_GetItem(search_path_list, i);
1936 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001938
Victor Stinner2fd76e42011-03-14 15:19:39 -04001939 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001940 ok = find_module_path(fullname, name, path,
1941 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001942 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001943 if (ok < 0)
1944 return NULL;
1945 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001947 if (ok == 2) {
1948 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001949 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001950 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001953 struct stat statbuf;
1954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 filemode = fdp->mode;
1956 if (filemode[0] == 'U')
1957 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001958
Victor Stinner2fd76e42011-03-14 15:19:39 -04001959 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1960 if (filename == NULL) {
1961 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001962 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001963 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001964
1965 if (Py_VerboseFlag > 1)
1966 PySys_FormatStderr("# trying %R\n", filename);
1967
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001968 err = _Py_stat(filename, &statbuf);
1969 if (err == -2) {
1970 Py_DECREF(prefix);
1971 Py_DECREF(filename);
1972 return NULL;
1973 }
1974 if (err != 0 || S_ISDIR(statbuf.st_mode)) {
Charles-François Natali1659b832011-12-07 23:17:58 +01001975 /* it doesn't exist, or it's a directory */
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001976 Py_DECREF(filename);
1977 continue;
1978 }
1979
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001980 fp = _Py_fopen(filename, filemode);
1981 if (fp == NULL) {
1982 Py_DECREF(filename);
Victor Stinner925ef392011-06-20 15:01:10 +02001983 if (PyErr_Occurred()) {
1984 Py_DECREF(prefix);
1985 return NULL;
1986 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001987 continue;
1988 }
1989 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
1990 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001991 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001992 Py_DECREF(filename);
1993 return NULL;
1994 }
1995 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001996 Py_DECREF(prefix);
1997 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04001998 *p_fp = fp;
1999 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002001 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04002002
2003 fclose(fp);
2004 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002006 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 }
Victor Stinnerd0296212011-03-14 14:04:10 -04002008 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002009 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04002010 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002011}
2012
Victor Stinner37580282011-03-20 01:34:43 +01002013/* Find a module:
2014
2015 - try find_module() of each sys.meta_path hook
2016 - try find_frozen()
2017 - try is_builtin()
2018 - try _PyWin_FindRegisteredModule() (Windows only)
2019 - otherwise, call find_module_path_list() with search_path_list (if not
2020 NULL) or sys.path
2021
Victor Stinner2fd76e42011-03-14 15:19:39 -04002022 fullname can be NULL, but only if p_loader is NULL.
2023
Victor Stinner37580282011-03-20 01:34:43 +01002024 Return:
2025
2026 - &fd_builtin (C_BUILTIN) if it is a builtin
2027 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04002028 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01002029 if it is a package
2030 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
2031 importer loader was found
2032 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
2033 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04002034 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01002035 - NULL on error
2036
Victor Stinner2fd76e42011-03-14 15:19:39 -04002037 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
2038 Eg. *p_path is set to NULL for a builtin package.
2039*/
Victor Stinner37580282011-03-20 01:34:43 +01002040
2041static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002042find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002043 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01002044{
2045 Py_ssize_t i, npath;
2046 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
2047 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
2048 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01002049
Victor Stinner2fd76e42011-03-14 15:19:39 -04002050 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01002051 *p_fp = NULL;
2052 if (p_loader != NULL)
2053 *p_loader = NULL;
2054
Victor Stinner37580282011-03-20 01:34:43 +01002055 /* sys.meta_path import hook */
2056 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002057 _Py_IDENTIFIER(find_module);
Victor Stinner37580282011-03-20 01:34:43 +01002058 PyObject *meta_path;
2059
2060 meta_path = PySys_GetObject("meta_path");
2061 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02002062 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002063 "sys.meta_path must be a list of "
2064 "import hooks");
2065 return NULL;
2066 }
2067 Py_INCREF(meta_path); /* zap guard */
2068 npath = PyList_Size(meta_path);
2069 for (i = 0; i < npath; i++) {
2070 PyObject *loader;
2071 PyObject *hook = PyList_GetItem(meta_path, i);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002072 loader = _PyObject_CallMethodId(hook, &PyId_find_module,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002073 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01002074 search_path_list != NULL ?
2075 search_path_list : Py_None);
2076 if (loader == NULL) {
2077 Py_DECREF(meta_path);
2078 return NULL; /* true error */
2079 }
2080 if (loader != Py_None) {
2081 /* a loader was found */
2082 *p_loader = loader;
2083 Py_DECREF(meta_path);
2084 return &importhookdescr;
2085 }
2086 Py_DECREF(loader);
2087 }
2088 Py_DECREF(meta_path);
2089 }
2090
Victor Stinnerdf75a022011-03-14 13:40:04 -04002091 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002092 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01002093
2094 if (search_path_list == NULL) {
2095#ifdef MS_COREDLL
2096 FILE *fp;
2097 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01002098#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04002099 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01002100 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01002101#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04002102 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01002103 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01002104 *p_fp = fp;
2105 return fdp;
2106 }
2107 else if (PyErr_Occurred())
2108 return NULL;
2109#endif
Victor Stinner37580282011-03-20 01:34:43 +01002110 search_path_list = PySys_GetObject("path");
2111 }
2112
2113 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
Victor Stinner16191322011-09-15 19:28:05 +02002114 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002115 "sys.path must be a list of directory names");
2116 return NULL;
2117 }
2118
2119 path_hooks = PySys_GetObject("path_hooks");
2120 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02002121 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002122 "sys.path_hooks must be a list of "
2123 "import hooks");
2124 return NULL;
2125 }
2126 path_importer_cache = PySys_GetObject("path_importer_cache");
2127 if (path_importer_cache == NULL ||
2128 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02002129 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002130 "sys.path_importer_cache must be a dict");
2131 return NULL;
2132 }
2133
2134 return find_module_path_list(fullname, name,
2135 search_path_list, path_hooks,
2136 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002137 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01002138}
2139
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002140/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00002141 * The arguments here are tricky, best shown by example:
2142 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2143 * ^ ^ ^ ^
2144 * |--------------------- buf ---------------------|
2145 * |------------------- len ------------------|
2146 * |------ name -------|
2147 * |----- namelen -----|
2148 * buf is the full path, but len only counts up to (& exclusive of) the
2149 * extension. name is the module name, also exclusive of extension.
2150 *
2151 * We've already done a successful stat() or fopen() on buf, so know that
2152 * there's some match, possibly case-insensitive.
2153 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002154 * case_bytes() is to return 1 if there's a case-sensitive match for
2155 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00002156 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00002157 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002158 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00002159 * on platforms with case-insensitive filesystems. It's trivial to implement
2160 * for case-sensitive filesystems. It's pretty much a cross-platform
2161 * nightmare for systems with case-insensitive filesystems.
2162 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00002163
Tim Peters50d8d372001-02-28 05:34:27 +00002164/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002165 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00002166 */
Jason Tishler7961aa62005-05-20 00:56:54 +00002167#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002168#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00002169
Tim Peters50d8d372001-02-28 05:34:27 +00002170#elif defined(DJGPP)
2171#include <dir.h>
2172
Jason Tishler7961aa62005-05-20 00:56:54 +00002173#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00002174#include <sys/types.h>
2175#include <dirent.h>
2176
Andrew MacIntyred9400542002-02-26 11:41:34 +00002177#elif defined(PYOS_OS2)
2178#define INCL_DOS
2179#define INCL_DOSERRORS
2180#define INCL_NOPMAPI
2181#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00002182#endif
2183
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002184#if defined(DJGPP) \
2185 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
2186 && defined(HAVE_DIRENT_H)) \
2187 || defined(PYOS_OS2)
2188# define USE_CASE_OK_BYTES
2189#endif
2190
2191
2192#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00002193static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002194case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002195{
Tim Peters50d8d372001-02-28 05:34:27 +00002196/* Pick a platform-specific implementation; the sequence of #if's here should
2197 * match the sequence just above.
2198 */
2199
Tim Peters50d8d372001-02-28 05:34:27 +00002200/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002201#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 struct ffblk ffblk;
2203 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (Py_GETENV("PYTHONCASEOK") != NULL)
2206 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2209 if (done) {
2210 PyErr_Format(PyExc_NameError,
2211 "Can't find file for module %.100s\n(filename %.300s)",
2212 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01002213 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 }
2215 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002216
Jason Tishler7961aa62005-05-20 00:56:54 +00002217/* new-fangled macintosh (macosx) or Cygwin */
2218#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 DIR *dirp;
2220 struct dirent *dp;
2221 char dirname[MAXPATHLEN + 1];
2222 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (Py_GETENV("PYTHONCASEOK") != NULL)
2225 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Copy the dir component into dirname; substitute "." if empty */
2228 if (dirlen <= 0) {
2229 dirname[0] = '.';
2230 dirname[1] = '\0';
2231 }
2232 else {
2233 assert(dirlen <= MAXPATHLEN);
2234 memcpy(dirname, buf, dirlen);
2235 dirname[dirlen] = '\0';
2236 }
2237 /* Open the directory and search the entries for an exact match. */
2238 dirp = opendir(dirname);
2239 if (dirp) {
2240 char *nameWithExt = buf + len - namelen;
2241 while ((dp = readdir(dirp)) != NULL) {
2242 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002243#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002245#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002247#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (thislen >= namelen &&
2249 strcmp(dp->d_name, nameWithExt) == 0) {
2250 (void)closedir(dirp);
2251 return 1; /* Found */
2252 }
2253 }
2254 (void)closedir(dirp);
2255 }
2256 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002257
Andrew MacIntyred9400542002-02-26 11:41:34 +00002258/* OS/2 */
2259#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 HDIR hdir = 1;
2261 ULONG srchcnt = 1;
2262 FILEFINDBUF3 ffbuf;
2263 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (Py_GETENV("PYTHONCASEOK") != NULL)
2266 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 rc = DosFindFirst(buf,
2269 &hdir,
2270 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2271 &ffbuf, sizeof(ffbuf),
2272 &srchcnt,
2273 FIL_STANDARD);
2274 if (rc != NO_ERROR)
2275 return 0;
2276 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002277
Tim Peters50d8d372001-02-28 05:34:27 +00002278/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2279#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002280# error "USE_CASE_OK_BYTES is not correctly defined"
2281#endif
2282}
2283#endif
2284
2285/*
2286 * Check if a filename case matchs the name case. We've already done a
2287 * successful stat() or fopen() on buf, so know that there's some match,
2288 * possibly case-insensitive.
2289 *
2290 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
2291 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
2292 * if envar PYTHONCASEOK exists.
2293 *
2294 * case_ok() is used to implement case-sensitive import semantics even
2295 * on platforms with case-insensitive filesystems. It's trivial to implement
2296 * for case-sensitive filesystems. It's pretty much a cross-platform
2297 * nightmare for systems with case-insensitive filesystems.
2298 */
2299
2300static int
2301case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
2302{
2303#ifdef MS_WINDOWS
2304 WIN32_FIND_DATAW data;
2305 HANDLE h;
2306 int cmp;
Victor Stinner1f795172011-11-17 00:45:54 +01002307 wchar_t *wfilename, *wname;
Victor Stinner8c981892011-10-11 22:27:13 +02002308 Py_ssize_t wname_len;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002309
2310 if (Py_GETENV("PYTHONCASEOK") != NULL)
2311 return 1;
2312
Victor Stinner1f795172011-11-17 00:45:54 +01002313 wfilename = PyUnicode_AsUnicode(filename);
2314 if (wfilename == NULL)
2315 return -1;
2316
2317 h = FindFirstFileW(wfilename, &data);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002318 if (h == INVALID_HANDLE_VALUE) {
2319 PyErr_Format(PyExc_NameError,
2320 "Can't find file for module %R\n(filename %R)",
2321 name, filename);
Victor Stinner1f795172011-11-17 00:45:54 +01002322 return -1;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002323 }
2324 FindClose(h);
Victor Stinnerbeac78b2011-10-11 21:55:01 +02002325
2326 wname = PyUnicode_AsUnicodeAndSize(name, &wname_len);
2327 if (wname == NULL)
2328 return -1;
2329
2330 cmp = wcsncmp(data.cFileName, wname, wname_len);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002331 return cmp == 0;
2332#elif defined(USE_CASE_OK_BYTES)
2333 int match;
2334 PyObject *filebytes, *namebytes;
2335 filebytes = PyUnicode_EncodeFSDefault(filename);
2336 if (filebytes == NULL)
2337 return -1;
2338 namebytes = PyUnicode_EncodeFSDefault(name);
2339 if (namebytes == NULL) {
2340 Py_DECREF(filebytes);
2341 return -1;
2342 }
2343 match = case_bytes(
2344 PyBytes_AS_STRING(filebytes),
2345 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01002346 PyBytes_GET_SIZE(namebytes),
2347 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002348 Py_DECREF(filebytes);
2349 Py_DECREF(namebytes);
2350 return match;
2351#else
2352 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002354
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002355#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002356}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002357
Guido van Rossum197346f1997-10-31 18:38:52 +00002358#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002359
Victor Stinner547a2a62011-03-20 03:07:28 +01002360/* Helper to look for __init__.py or __init__.py[co] in potential package.
2361 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00002362static int
Victor Stinner547a2a62011-03-20 03:07:28 +01002363find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00002364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01002366 PyObject *filename;
2367 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002368 int err;
Guido van Rossum197346f1997-10-31 18:38:52 +00002369
Victor Stinner547a2a62011-03-20 03:07:28 +01002370 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
2371 if (filename == NULL)
2372 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002373 err = _Py_stat(filename, &statbuf);
2374 if (err == -2)
2375 return -1;
2376 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002377 /* 3=len(".py") */
2378 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002379 if (match < 0) {
2380 Py_DECREF(filename);
2381 return -1;
2382 }
2383 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002384 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 return 1;
2386 }
2387 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002388 Py_DECREF(filename);
2389
2390 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
2391 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
2392 if (filename == NULL)
2393 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002394 err = _Py_stat(filename, &statbuf);
2395 if (err == -2) {
2396 Py_DECREF(filename);
2397 return -1;
2398 }
2399 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002400 /* 4=len(".pyc") */
2401 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002402 if (match < 0) {
2403 Py_DECREF(filename);
2404 return -1;
2405 }
2406 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002407 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return 1;
2409 }
2410 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002411 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002413}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002414
Guido van Rossum197346f1997-10-31 18:38:52 +00002415#endif /* HAVE_STAT */
2416
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002417
Victor Stinner95872862011-03-07 18:20:56 +01002418static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002419
Victor Stinner44c6c152010-08-09 00:59:10 +00002420static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002421load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002422{
2423 PyObject *m, *modules;
2424 int err;
2425
Victor Stinner44c6c152010-08-09 00:59:10 +00002426 if (type == C_BUILTIN)
2427 err = init_builtin(name);
2428 else
Victor Stinner95872862011-03-07 18:20:56 +01002429 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002430 if (err < 0)
2431 return NULL;
2432 if (err == 0) {
2433 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002434 "Purported %s module %R not found",
2435 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002436 name);
2437 return NULL;
2438 }
2439
2440 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002441 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002442 if (m == NULL) {
2443 PyErr_Format(
2444 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002445 "%s module %R not properly initialized",
2446 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002447 name);
2448 return NULL;
2449 }
2450 Py_INCREF(m);
2451 return m;
2452}
2453
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002454/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002455 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002456
Guido van Rossum79f25d91997-04-29 20:08:16 +00002457static PyObject *
Victor Stinner41c5fec2011-03-13 21:46:30 -04002458load_module(PyObject *name, FILE *fp, PyObject *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* First check that there's an open file (if we need one) */
2463 switch (type) {
2464 case PY_SOURCE:
2465 case PY_COMPILED:
2466 if (fp == NULL) {
2467 PyErr_Format(PyExc_ValueError,
Victor Stinner41c5fec2011-03-13 21:46:30 -04002468 "file object required for import (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 type);
2470 return NULL;
2471 }
2472 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002475
Victor Stinner41c5fec2011-03-13 21:46:30 -04002476 case PY_SOURCE:
2477 m = load_source_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002479
Victor Stinner41c5fec2011-03-13 21:46:30 -04002480 case PY_COMPILED:
2481 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002483
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002484#ifdef HAVE_DYNAMIC_LOADING
Victor Stinner41c5fec2011-03-13 21:46:30 -04002485 case C_EXTENSION:
2486 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002488#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002489
Victor Stinner41c5fec2011-03-13 21:46:30 -04002490 case PKG_DIRECTORY:
2491 m = load_package(name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 case C_BUILTIN:
Victor Stinner41c5fec2011-03-13 21:46:30 -04002495 case PY_FROZEN:
2496 m = load_builtin(name, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 case IMP_HOOK: {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002500 _Py_IDENTIFIER(load_module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 if (loader == NULL) {
2502 PyErr_SetString(PyExc_ImportError,
2503 "import hook without loader");
2504 return NULL;
2505 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002506 m = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 break;
2508 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 default:
2511 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002512 "Don't know how to import %R (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 name, type);
2514 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002519}
2520
2521
2522/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002523 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002524 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002525
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002526static int
Victor Stinner95872862011-03-07 18:20:56 +01002527init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002530
Victor Stinner95872862011-03-07 18:20:56 +01002531 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 for (p = PyImport_Inittab; p->name != NULL; p++) {
2535 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002536 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01002537 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 if (p->initfunc == NULL) {
2539 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002540 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 name);
2542 return -1;
2543 }
2544 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002545 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 mod = (*p->initfunc)();
2547 if (mod == 0)
2548 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002549 /* Remember pointer to module init function. */
2550 def = PyModule_GetDef(mod);
2551 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01002552 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 return -1;
2554 /* FixupExtension has put the module into sys.modules,
2555 so we can release our own reference. */
2556 Py_DECREF(mod);
2557 return 1;
2558 }
2559 }
2560 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002561}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002562
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002563
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002564/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002565
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002566static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002567find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002570
Victor Stinner53dc7352011-03-20 01:50:21 +01002571 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 for (p = PyImport_FrozenModules; ; p++) {
2575 if (p->name == NULL)
2576 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002577 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 break;
2579 }
2580 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002581}
2582
Guido van Rossum79f25d91997-04-29 20:08:16 +00002583static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002584get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 struct _frozen *p = find_frozen(name);
2587 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 if (p == NULL) {
2590 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002591 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 name);
2593 return NULL;
2594 }
2595 if (p->code == NULL) {
2596 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002597 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 name);
2599 return NULL;
2600 }
2601 size = p->size;
2602 if (size < 0)
2603 size = -size;
2604 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002605}
2606
Brett Cannon8d110132009-03-15 02:20:16 +00002607static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002608is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 struct _frozen *p = find_frozen(name);
2611 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (p == NULL) {
2614 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002615 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 name);
2617 return NULL;
2618 }
Brett Cannon8d110132009-03-15 02:20:16 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 if (size < 0)
2623 Py_RETURN_TRUE;
2624 else
2625 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002626}
2627
2628
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002629/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002630 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002631 an exception set if the initialization failed.
2632 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002633
2634int
Victor Stinner53dc7352011-03-20 01:50:21 +01002635PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002636{
Victor Stinner53dc7352011-03-20 01:50:21 +01002637 struct _frozen *p;
2638 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 int ispackage;
2640 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002641
Victor Stinner53dc7352011-03-20 01:50:21 +01002642 p = find_frozen(name);
2643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 if (p == NULL)
2645 return 0;
2646 if (p->code == NULL) {
2647 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002648 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 name);
2650 return -1;
2651 }
2652 size = p->size;
2653 ispackage = (size < 0);
2654 if (ispackage)
2655 size = -size;
2656 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002657 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 name, ispackage ? " package" : "");
2659 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2660 if (co == NULL)
2661 return -1;
2662 if (!PyCode_Check(co)) {
2663 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002664 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 name);
2666 goto err_return;
2667 }
2668 if (ispackage) {
2669 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002670 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002672 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (m == NULL)
2674 goto err_return;
2675 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 l = PyList_New(1);
2677 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 goto err_return;
2679 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002680 Py_INCREF(name);
2681 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 err = PyDict_SetItemString(d, "__path__", l);
2683 Py_DECREF(l);
2684 if (err != 0)
2685 goto err_return;
2686 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002687 path = PyUnicode_FromString("<frozen>");
2688 if (path == NULL)
2689 goto err_return;
2690 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2691 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 if (m == NULL)
2693 goto err_return;
2694 Py_DECREF(co);
2695 Py_DECREF(m);
2696 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002697err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 Py_DECREF(co);
2699 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002700}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002701
Victor Stinner53dc7352011-03-20 01:50:21 +01002702int
2703PyImport_ImportFrozenModule(char *name)
2704{
2705 PyObject *nameobj;
2706 int ret;
2707 nameobj = PyUnicode_InternFromString(name);
2708 if (nameobj == NULL)
2709 return -1;
2710 ret = PyImport_ImportFrozenModuleObject(nameobj);
2711 Py_DECREF(nameobj);
2712 return ret;
2713}
2714
Guido van Rossum74e6a111994-08-29 12:54:38 +00002715
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002716/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002717 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002718
Guido van Rossum79f25d91997-04-29 20:08:16 +00002719PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002720PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 PyObject *pname;
2723 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 pname = PyUnicode_FromString(name);
2726 if (pname == NULL)
2727 return NULL;
2728 result = PyImport_Import(pname);
2729 Py_DECREF(pname);
2730 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002731}
2732
Christian Heimes072c0f12008-01-03 23:01:04 +00002733/* Import a module without blocking
2734 *
2735 * At first it tries to fetch the module from sys.modules. If the module was
2736 * never loaded before it loads it with PyImport_ImportModule() unless another
2737 * thread holds the import lock. In the latter case the function raises an
2738 * ImportError instead of blocking.
2739 *
2740 * Returns the module object with incremented ref count.
2741 */
2742PyObject *
2743PyImport_ImportModuleNoBlock(const char *name)
2744{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002745 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002746#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002748#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 /* Try to get the module from sys.modules[name] */
2751 modules = PyImport_GetModuleDict();
2752 if (modules == NULL)
2753 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002754
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002755 nameobj = PyUnicode_FromString(name);
2756 if (nameobj == NULL)
2757 return NULL;
2758 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002760 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 Py_INCREF(result);
2762 return result;
2763 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002764 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002765#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 /* check the import lock
2767 * me might be -1 but I ignore the error here, the lock function
2768 * takes care of the problem */
2769 me = PyThread_get_thread_ident();
2770 if (import_lock_thread == -1 || import_lock_thread == me) {
2771 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002772 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 }
2774 else {
2775 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002776 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002778 nameobj);
2779 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002781#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002782 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002783#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002784 Py_DECREF(nameobj);
2785 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002786}
2787
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002788/* Forward declarations for helper routines */
Victor Stinner974389d2011-03-15 09:33:57 +01002789static PyObject *get_parent(PyObject *globals,
2790 PyObject **p_name,
2791 int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002792static PyObject *load_next(PyObject *mod, PyObject *altmod,
Victor Stinner974389d2011-03-15 09:33:57 +01002793 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002794 PyObject **p_prefix);
Victor Stinner974389d2011-03-15 09:33:57 +01002795static int mark_miss(PyObject *name);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002796static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Victor Stinner974389d2011-03-15 09:33:57 +01002797 PyObject *buf, int recursive);
2798static PyObject * import_submodule(PyObject *mod, PyObject *name,
2799 PyObject *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002800
2801/* The Magnum Opus of dotted-name import :-) */
2802
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002803static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01002804import_module_level(PyObject *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002806{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002807 PyObject *parent, *next, *inputname, *outputname;
2808 PyObject *head = NULL;
2809 PyObject *tail = NULL;
2810 PyObject *prefix = NULL;
2811 PyObject *result = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002812 Py_ssize_t sep, altsep;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002814 if (PyUnicode_READY(name))
2815 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002817 sep = PyUnicode_FindChar(name, SEP, 0, PyUnicode_GET_LENGTH(name), 1);
2818 if (sep == -2)
2819 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002820#ifdef ALTSEP
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002821 altsep = PyUnicode_FindChar(name, ALTSEP, 0, PyUnicode_GET_LENGTH(name), 1);
2822 if (altsep == -2)
2823 return NULL;
2824#else
2825 altsep = -1;
Christian Heimes454f37b2008-01-10 00:10:02 +00002826#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002827 if (sep != -1 || altsep != -1)
2828 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 PyErr_SetString(PyExc_ImportError,
2830 "Import by filename is not supported.");
2831 return NULL;
2832 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002833
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002834 parent = get_parent(globals, &prefix, level);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002835 if (parent == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002837 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002838
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002839 if (PyUnicode_READY(prefix))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002840 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002841
2842 head = load_next(parent, level < 0 ? Py_None : parent, name, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002843 &prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (head == NULL)
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002845 goto out;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 tail = head;
2848 Py_INCREF(tail);
Victor Stinner974389d2011-03-15 09:33:57 +01002849
2850 if (outputname != NULL) {
2851 while (1) {
2852 inputname = outputname;
2853 next = load_next(tail, tail, inputname, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002854 &prefix);
2855 Py_CLEAR(tail);
2856 Py_CLEAR(inputname);
2857 if (next == NULL)
2858 goto out;
Victor Stinner974389d2011-03-15 09:33:57 +01002859 tail = next;
2860
2861 if (outputname == NULL) {
2862 break;
2863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 }
2866 if (tail == Py_None) {
2867 /* If tail is Py_None, both get_parent and load_next found
2868 an empty module name: someone called __import__("") or
2869 doctored faulty bytecode */
Victor Stinner974389d2011-03-15 09:33:57 +01002870 PyErr_SetString(PyExc_ValueError, "Empty module name");
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002871 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 if (fromlist != NULL) {
2875 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2876 fromlist = NULL;
2877 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 if (fromlist == NULL) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002880 result = head;
2881 Py_INCREF(result);
2882 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002884
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002885 if (!ensure_fromlist(tail, fromlist, prefix, 0))
2886 goto out;
Victor Stinner1f795172011-11-17 00:45:54 +01002887
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002888 result = tail;
2889 Py_INCREF(result);
2890 out:
2891 Py_XDECREF(head);
2892 Py_XDECREF(tail);
2893 Py_XDECREF(prefix);
2894 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002895}
2896
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002897PyObject *
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002898PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2899 PyObject *locals, PyObject *fromlist,
2900 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002901{
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002902 PyObject *mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 _PyImport_AcquireLock();
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002904 mod = import_module_level(name, globals, locals, fromlist, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 if (_PyImport_ReleaseLock() < 0) {
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002906 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 PyErr_SetString(PyExc_RuntimeError,
2908 "not holding the import lock");
2909 return NULL;
2910 }
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002911 return mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002912}
2913
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002914PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002915PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002916 PyObject *fromlist, int level)
2917{
2918 PyObject *nameobj, *mod;
2919 nameobj = PyUnicode_FromString(name);
2920 if (nameobj == NULL)
2921 return NULL;
2922 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2923 fromlist, level);
2924 Py_DECREF(nameobj);
2925 return mod;
2926}
2927
2928
Fred Drake87590902004-05-28 20:21:36 +00002929/* Return the package that an import is being performed in. If globals comes
2930 from the module foo.bar.bat (not itself a package), this returns the
2931 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002932 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002933
Victor Stinner974389d2011-03-15 09:33:57 +01002934 The name of the returned package is returned in *p_name.
Fred Drake87590902004-05-28 20:21:36 +00002935
2936 If globals doesn't come from a package or a module in a package, or a
2937 corresponding entry is not found in sys.modules, Py_None is returned.
2938*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002939static PyObject *
Victor Stinner9599de52011-03-13 22:38:38 -04002940get_parent(PyObject *globals, PyObject **p_name, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002941{
Victor Stinner974389d2011-03-15 09:33:57 +01002942 PyObject *nameobj;
2943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 static PyObject *namestr = NULL;
2945 static PyObject *pathstr = NULL;
2946 static PyObject *pkgstr = NULL;
2947 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2948 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 if (globals == NULL || !PyDict_Check(globals) || !level)
Victor Stinner974389d2011-03-15 09:33:57 +01002951 goto return_none;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 if (namestr == NULL) {
2954 namestr = PyUnicode_InternFromString("__name__");
2955 if (namestr == NULL)
2956 return NULL;
2957 }
2958 if (pathstr == NULL) {
2959 pathstr = PyUnicode_InternFromString("__path__");
2960 if (pathstr == NULL)
2961 return NULL;
2962 }
2963 if (pkgstr == NULL) {
2964 pkgstr = PyUnicode_InternFromString("__package__");
2965 if (pkgstr == NULL)
2966 return NULL;
2967 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 if ((pkgname != NULL) && (pkgname != Py_None)) {
2972 /* __package__ is set, so use it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 if (!PyUnicode_Check(pkgname)) {
2974 PyErr_SetString(PyExc_ValueError,
2975 "__package__ set to non-string");
2976 return NULL;
2977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002978 if (PyUnicode_GET_LENGTH(pkgname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 if (level > 0) {
2980 PyErr_SetString(PyExc_ValueError,
2981 "Attempted relative import in non-package");
2982 return NULL;
2983 }
Victor Stinner974389d2011-03-15 09:33:57 +01002984 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002986 Py_INCREF(pkgname);
2987 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 } else {
2989 /* __package__ not set, so figure it out and set it */
2990 modname = PyDict_GetItem(globals, namestr);
2991 if (modname == NULL || !PyUnicode_Check(modname))
Victor Stinner974389d2011-03-15 09:33:57 +01002992 goto return_none;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 modpath = PyDict_GetItem(globals, pathstr);
2995 if (modpath != NULL) {
2996 /* __path__ is set, so modname is already the package name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 error = PyDict_SetItem(globals, pkgstr, modname);
3000 if (error) {
3001 PyErr_SetString(PyExc_ValueError,
3002 "Could not set __package__");
3003 return NULL;
3004 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003005 Py_INCREF(modname);
3006 nameobj = modname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 } else {
3008 /* Normal module, so work out the package name if any */
Victor Stinner974389d2011-03-15 09:33:57 +01003009 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003010 len = PyUnicode_FindChar(modname, '.',
3011 0, PyUnicode_GET_LENGTH(modname), -1);
3012 if (len == -2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003014 if (len < 0) {
3015 if (level > 0) {
3016 PyErr_SetString(PyExc_ValueError,
3017 "Attempted relative import in non-package");
3018 return NULL;
3019 }
3020 if (PyDict_SetItem(globals, pkgstr, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 PyErr_SetString(PyExc_ValueError,
3022 "Could not set __package__");
3023 return NULL;
3024 }
Victor Stinner974389d2011-03-15 09:33:57 +01003025 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003027 pkgname = PyUnicode_Substring(modname, 0, len);
3028 if (pkgname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003030 if (PyDict_SetItem(globals, pkgstr, pkgname)) {
3031 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 PyErr_SetString(PyExc_ValueError,
3033 "Could not set __package__");
3034 return NULL;
3035 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003036 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 }
3038 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003039 if (level > 1) {
3040 Py_ssize_t dot, end = PyUnicode_GET_LENGTH(nameobj);
3041 PyObject *newname;
3042 while (--level > 0) {
3043 dot = PyUnicode_FindChar(nameobj, '.', 0, end, -1);
3044 if (dot == -2) {
3045 Py_DECREF(nameobj);
3046 return NULL;
3047 }
3048 if (dot < 0) {
3049 Py_DECREF(nameobj);
3050 PyErr_SetString(PyExc_ValueError,
3051 "Attempted relative import beyond "
3052 "toplevel package");
3053 return NULL;
3054 }
3055 end = dot;
3056 }
3057 newname = PyUnicode_Substring(nameobj, 0, end);
3058 Py_DECREF(nameobj);
3059 if (newname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003061 nameobj = newname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 }
Victor Stinner974389d2011-03-15 09:33:57 +01003063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003065 parent = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 if (parent == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003067 int err;
3068
3069 if (orig_level >= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 PyErr_Format(PyExc_SystemError,
Victor Stinner974389d2011-03-15 09:33:57 +01003071 "Parent module %R not loaded, "
3072 "cannot perform relative import", nameobj);
3073 Py_DECREF(nameobj);
3074 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 }
Victor Stinner974389d2011-03-15 09:33:57 +01003076
3077 err = PyErr_WarnFormat(
3078 PyExc_RuntimeWarning, 1,
3079 "Parent module %R not found while handling absolute import",
3080 nameobj);
3081 Py_DECREF(nameobj);
3082 if (err)
3083 return NULL;
3084
3085 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
Victor Stinner974389d2011-03-15 09:33:57 +01003087 *p_name = nameobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 return parent;
3089 /* We expect, but can't guarantee, if parent != None, that:
Victor Stinner974389d2011-03-15 09:33:57 +01003090 - parent.__name__ == name
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 - parent.__dict__ is globals
3092 If this is violated... Who cares? */
Victor Stinner974389d2011-03-15 09:33:57 +01003093
3094return_none:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003095 nameobj = PyUnicode_New(0, 0);
Victor Stinner974389d2011-03-15 09:33:57 +01003096 if (nameobj == NULL)
3097 return NULL;
3098 *p_name = nameobj;
3099 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003100}
3101
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003102/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003103static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003104load_next(PyObject *mod, PyObject *altmod,
3105 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003106 PyObject **p_prefix)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003107{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003108 Py_ssize_t dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003109 Py_ssize_t len;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003110 PyObject *fullname, *name = NULL, *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003111
Victor Stinner974389d2011-03-15 09:33:57 +01003112 *p_outputname = NULL;
3113
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003114 len = PyUnicode_GET_LENGTH(inputname);
3115 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 /* completely empty module name should only happen in
3117 'from . import' (or '__import__("")')*/
3118 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 return mod;
3120 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003121
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003122
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003123 dot = PyUnicode_FindChar(inputname, '.', 0, len, 1);
3124 if (dot >= 0) {
3125 len = dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003126 if (len == 0) {
3127 PyErr_SetString(PyExc_ValueError,
3128 "Empty module name");
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003129 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003130 }
3131 }
Victor Stinner974389d2011-03-15 09:33:57 +01003132
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003133 /* name = inputname[:len] */
3134 name = PyUnicode_Substring(inputname, 0, len);
3135 if (name == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003136 goto error;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003137
3138 if (PyUnicode_GET_LENGTH(*p_prefix)) {
3139 /* fullname = prefix + "." + name */
3140 fullname = PyUnicode_FromFormat("%U.%U", *p_prefix, name);
3141 if (fullname == NULL)
3142 goto error;
3143 }
3144 else {
3145 fullname = name;
3146 Py_INCREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003148
Victor Stinner974389d2011-03-15 09:33:57 +01003149 result = import_submodule(mod, name, fullname);
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003150 Py_DECREF(*p_prefix);
3151 /* Transfer reference. */
3152 *p_prefix = fullname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 if (result == Py_None && altmod != mod) {
3154 Py_DECREF(result);
3155 /* Here, altmod must be None and mod must not be None */
Victor Stinner974389d2011-03-15 09:33:57 +01003156 result = import_submodule(altmod, name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 if (result != NULL && result != Py_None) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003158 if (mark_miss(*p_prefix) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003160 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 }
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003162 Py_DECREF(*p_prefix);
3163 *p_prefix = name;
3164 Py_INCREF(*p_prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 }
3166 }
3167 if (result == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003168 goto error;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 if (result == Py_None) {
3171 Py_DECREF(result);
3172 PyErr_Format(PyExc_ImportError,
Victor Stinner974389d2011-03-15 09:33:57 +01003173 "No module named %R", inputname);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003174 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003176
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003177 if (dot >= 0) {
3178 *p_outputname = PyUnicode_Substring(inputname, dot+1,
3179 PyUnicode_GET_LENGTH(inputname));
Victor Stinner974389d2011-03-15 09:33:57 +01003180 if (*p_outputname == NULL) {
3181 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003182 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003183 }
3184 }
3185
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003186 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 return result;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003188
3189error:
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003190 Py_XDECREF(name);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003191 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003192}
3193
3194static int
Victor Stinner974389d2011-03-15 09:33:57 +01003195mark_miss(PyObject *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003198 return PyDict_SetItem(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003199}
3200
3201static int
Victor Stinner974389d2011-03-15 09:33:57 +01003202ensure_fromlist(PyObject *mod, PyObject *fromlist, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 int i;
Victor Stinner974389d2011-03-15 09:33:57 +01003206 PyObject *fullname;
3207 Py_ssize_t fromlist_len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003208
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003209 if (!_PyObject_HasAttrId(mod, &PyId___path__))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003211
Victor Stinner974389d2011-03-15 09:33:57 +01003212 fromlist_len = PySequence_Size(fromlist);
3213
3214 for (i = 0; i < fromlist_len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 PyObject *item = PySequence_GetItem(fromlist, i);
3216 int hasit;
Victor Stinner974389d2011-03-15 09:33:57 +01003217 if (item == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 if (!PyUnicode_Check(item)) {
3220 PyErr_SetString(PyExc_TypeError,
3221 "Item in ``from list'' not a string");
3222 Py_DECREF(item);
3223 return 0;
3224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003225 if (PyUnicode_READ_CHAR(item, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 PyObject *all;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003227 _Py_IDENTIFIER(__all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 Py_DECREF(item);
3229 /* See if the package defines __all__ */
3230 if (recursive)
3231 continue; /* Avoid endless recursion */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003232 all = _PyObject_GetAttrId(mod, &PyId___all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 if (all == NULL)
3234 PyErr_Clear();
3235 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003236 int ret = ensure_fromlist(mod, all, name, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 Py_DECREF(all);
3238 if (!ret)
3239 return 0;
3240 }
3241 continue;
3242 }
3243 hasit = PyObject_HasAttr(mod, item);
3244 if (!hasit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 PyObject *submod;
Victor Stinner974389d2011-03-15 09:33:57 +01003246 fullname = PyUnicode_FromFormat("%U.%U", name, item);
3247 if (fullname != NULL) {
3248 submod = import_submodule(mod, item, fullname);
3249 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 }
Victor Stinner974389d2011-03-15 09:33:57 +01003251 else
3252 submod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 Py_XDECREF(submod);
3254 if (submod == NULL) {
3255 Py_DECREF(item);
3256 return 0;
3257 }
3258 }
3259 Py_DECREF(item);
3260 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003261
Victor Stinner974389d2011-03-15 09:33:57 +01003262 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003263}
3264
Neil Schemenauer00b09662003-06-16 21:03:07 +00003265static int
Victor Stinner974389d2011-03-15 09:33:57 +01003266add_submodule(PyObject *mod, PyObject *submod, PyObject *fullname,
3267 PyObject *subname, PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00003268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 if (mod == Py_None)
3270 return 1;
3271 /* Irrespective of the success of this load, make a
3272 reference to it in the parent package module. A copy gets
3273 saved in the modules dictionary under the full name, so get a
3274 reference from there, if need be. (The exception is when the
3275 load failed with a SyntaxError -- then there's no trace in
3276 sys.modules. In that case, of course, do nothing extra.) */
3277 if (submod == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003278 submod = PyDict_GetItem(modules, fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 if (submod == NULL)
3280 return 1;
3281 }
3282 if (PyModule_Check(mod)) {
3283 /* We can't use setattr here since it can give a
3284 * spurious warning if the submodule name shadows a
3285 * builtin name */
3286 PyObject *dict = PyModule_GetDict(mod);
3287 if (!dict)
3288 return 0;
Victor Stinner974389d2011-03-15 09:33:57 +01003289 if (PyDict_SetItem(dict, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 return 0;
3291 }
3292 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003293 if (PyObject_SetAttr(mod, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 return 0;
3295 }
3296 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00003297}
3298
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003299static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003300import_submodule(PyObject *mod, PyObject *subname, PyObject *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003303 PyObject *m = NULL, *bufobj, *path_list, *loader;
Victor Stinner9599de52011-03-13 22:38:38 -04003304 struct filedescr *fdp;
3305 FILE *fp;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 /* Require:
3308 if mod == None: subname == fullname
3309 else: mod.__name__ + "." + subname == fullname
3310 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003311
Victor Stinner974389d2011-03-15 09:33:57 +01003312 if ((m = PyDict_GetItem(modules, fullname)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 Py_INCREF(m);
Victor Stinner9599de52011-03-13 22:38:38 -04003314 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 }
Victor Stinner9599de52011-03-13 22:38:38 -04003316
3317 if (mod == Py_None)
Victor Stinner533d7832011-03-14 13:22:54 -04003318 path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003320 path_list = _PyObject_GetAttrId(mod, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003321 if (path_list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 PyErr_Clear();
3323 Py_INCREF(Py_None);
3324 return Py_None;
3325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003327
Victor Stinner533d7832011-03-14 13:22:54 -04003328 fdp = find_module(fullname, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003329 &bufobj, &fp, &loader);
Victor Stinner533d7832011-03-14 13:22:54 -04003330 Py_XDECREF(path_list);
Victor Stinner9599de52011-03-13 22:38:38 -04003331 if (fdp == NULL) {
3332 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3333 return NULL;
3334 PyErr_Clear();
3335 Py_INCREF(Py_None);
3336 return Py_None;
3337 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003338 m = load_module(fullname, fp, bufobj, fdp->type, loader);
3339 Py_XDECREF(bufobj);
Victor Stinner9599de52011-03-13 22:38:38 -04003340 Py_XDECREF(loader);
3341 if (fp)
3342 fclose(fp);
3343 if (m == NULL)
3344 return NULL;
3345 if (!add_submodule(mod, m, fullname, subname, modules)) {
3346 Py_XDECREF(m);
3347 return NULL;
3348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003350}
3351
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003352
3353/* Re-import a module of any kind and return its module object, WITH
3354 INCREMENTED REFERENCE COUNT */
3355
Guido van Rossum79f25d91997-04-29 20:08:16 +00003356PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003357PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 PyInterpreterState *interp = PyThreadState_Get()->interp;
3360 PyObject *modules_reloading = interp->modules_reloading;
3361 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003362 PyObject *path_list = NULL, *loader = NULL, *existing_m = NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003363 PyObject *name, *bufobj, *subname;
3364 Py_ssize_t subname_start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 struct filedescr *fdp;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003366 FILE *fp = NULL;
3367 PyObject *newm = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 if (modules_reloading == NULL) {
3370 Py_FatalError("PyImport_ReloadModule: "
3371 "no modules_reloading dictionary!");
3372 return NULL;
3373 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 if (m == NULL || !PyModule_Check(m)) {
3376 PyErr_SetString(PyExc_TypeError,
3377 "reload() argument must be module");
3378 return NULL;
3379 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003380 name = PyModule_GetNameObject(m);
3381 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003383 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003385 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01003386 name);
3387 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 return NULL;
3389 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003390 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 if (existing_m != NULL) {
3392 /* Due to a recursive reload, this module is already
3393 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003394 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 Py_INCREF(existing_m);
3396 return existing_m;
3397 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003398 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
3399 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003401 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003402
Martin v. Löwis796ea532011-10-30 09:07:07 +01003403 subname_start = PyUnicode_FindChar(name, '.', 0,
3404 PyUnicode_GET_LENGTH(name), -1);
3405 if (subname_start == -1) {
3406 Py_INCREF(name);
3407 subname = name;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 else {
3410 PyObject *parentname, *parent;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003411 Py_ssize_t len;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003412 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003414 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 }
3416 parent = PyDict_GetItem(modules, parentname);
3417 if (parent == NULL) {
3418 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003419 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 parentname);
3421 Py_DECREF(parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003422 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 }
3424 Py_DECREF(parentname);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003425 path_list = _PyObject_GetAttrId(parent, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003426 if (path_list == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 PyErr_Clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003428 subname_start++;
3429 len = PyUnicode_GET_LENGTH(name) - (subname_start + 1);
3430 subname = PyUnicode_Substring(name, subname_start, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003432 if (subname == NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003433 goto error;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003434 fdp = find_module(name, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003435 &bufobj, &fp, &loader);
Martin v. Löwis796ea532011-10-30 09:07:07 +01003436 Py_DECREF(subname);
Victor Stinner533d7832011-03-14 13:22:54 -04003437 Py_XDECREF(path_list);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 if (fdp == NULL) {
3440 Py_XDECREF(loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003441 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003443
Martin v. Löwis796ea532011-10-30 09:07:07 +01003444 newm = load_module(name, fp, bufobj, fdp->type, loader);
Victor Stinner2fd76e42011-03-14 15:19:39 -04003445 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 if (fp)
3449 fclose(fp);
3450 if (newm == NULL) {
3451 /* load_module probably removed name from modules because of
3452 * the error. Put back the original module object. We're
3453 * going to return NULL in this case regardless of whether
3454 * replacing name succeeds, so the return value is ignored.
3455 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003456 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003458
3459error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003461 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003463}
3464
3465
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003466/* Higher-level import emulator which emulates the "import" statement
3467 more accurately -- it invokes the __import__() function from the
3468 builtins of the current globals. This means that the import is
3469 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003470 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003471 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003472 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003473 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003474
3475PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003476PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 static PyObject *silly_list = NULL;
3479 static PyObject *builtins_str = NULL;
3480 static PyObject *import_str = NULL;
3481 PyObject *globals = NULL;
3482 PyObject *import = NULL;
3483 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003484 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 /* Initialize constant string objects */
3488 if (silly_list == NULL) {
3489 import_str = PyUnicode_InternFromString("__import__");
3490 if (import_str == NULL)
3491 return NULL;
3492 builtins_str = PyUnicode_InternFromString("__builtins__");
3493 if (builtins_str == NULL)
3494 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003495 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 if (silly_list == NULL)
3497 return NULL;
3498 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 /* Get the builtins from current globals */
3501 globals = PyEval_GetGlobals();
3502 if (globals != NULL) {
3503 Py_INCREF(globals);
3504 builtins = PyObject_GetItem(globals, builtins_str);
3505 if (builtins == NULL)
3506 goto err;
3507 }
3508 else {
3509 /* No globals -- use standard builtins, and fake globals */
3510 builtins = PyImport_ImportModuleLevel("builtins",
3511 NULL, NULL, NULL, 0);
3512 if (builtins == NULL)
3513 return NULL;
3514 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3515 if (globals == NULL)
3516 goto err;
3517 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 /* Get the __import__ function from the builtins */
3520 if (PyDict_Check(builtins)) {
3521 import = PyObject_GetItem(builtins, import_str);
3522 if (import == NULL)
3523 PyErr_SetObject(PyExc_KeyError, import_str);
3524 }
3525 else
3526 import = PyObject_GetAttr(builtins, import_str);
3527 if (import == NULL)
3528 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003531 Always use absolute import here.
3532 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3534 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003535 if (r == NULL)
3536 goto err;
3537 Py_DECREF(r);
3538
3539 modules = PyImport_GetModuleDict();
3540 r = PyDict_GetItem(modules, module_name);
3541 if (r != NULL)
3542 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003543
3544 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 Py_XDECREF(globals);
3546 Py_XDECREF(builtins);
3547 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003550}
3551
3552
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003553/* Module 'imp' provides Python access to the primitives used for
3554 importing modules.
3555*/
3556
Guido van Rossum79f25d91997-04-29 20:08:16 +00003557static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003558imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 buf[0] = (char) ((magic >> 0) & 0xff);
3563 buf[1] = (char) ((magic >> 8) & 0xff);
3564 buf[2] = (char) ((magic >> 16) & 0xff);
3565 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003568}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003569
3570static PyObject *
3571imp_get_magic(PyObject *self, PyObject *noargs)
3572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003574}
3575
3576static PyObject *
3577imp_get_tag(PyObject *self, PyObject *noargs)
3578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003580}
3581
Guido van Rossum79f25d91997-04-29 20:08:16 +00003582static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003583imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 PyObject *list;
3586 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 list = PyList_New(0);
3589 if (list == NULL)
3590 return NULL;
3591 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3592 PyObject *item = Py_BuildValue("ssi",
3593 fdp->suffix, fdp->mode, fdp->type);
3594 if (item == NULL) {
3595 Py_DECREF(list);
3596 return NULL;
3597 }
3598 if (PyList_Append(list, item) < 0) {
3599 Py_DECREF(list);
3600 Py_DECREF(item);
3601 return NULL;
3602 }
3603 Py_DECREF(item);
3604 }
3605 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003606}
3607
Guido van Rossum79f25d91997-04-29 20:08:16 +00003608static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003609call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 extern int fclose(FILE *);
3612 PyObject *fob, *ret;
3613 PyObject *pathobj;
3614 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003615 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 int fd = -1;
3617 char *found_encoding = NULL;
3618 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003619
Victor Stinner533d7832011-03-14 13:22:54 -04003620 if (path_list == Py_None)
3621 path_list = NULL;
3622 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003623 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 if (fdp == NULL)
3625 return NULL;
3626 if (fp != NULL) {
3627 fd = fileno(fp);
3628 if (fd != -1)
3629 fd = dup(fd);
3630 fclose(fp);
3631 fp = NULL;
Antoine Pitrou72146122012-02-22 18:03:04 +01003632 if (fd == -1)
3633 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 }
3635 if (fd != -1) {
3636 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003637 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003639 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003641 if (found_encoding == NULL && PyErr_Occurred()) {
3642 Py_XDECREF(pathobj);
Antoine Pitrou4f22a8d2012-02-22 18:05:43 +01003643 close(fd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 encoding = (found_encoding != NULL) ? found_encoding :
3647 (char*)PyUnicode_GetDefaultEncoding();
3648 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003649 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 (char*)encoding, NULL, NULL, 1);
3651 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003652 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 close(fd);
3654 PyMem_FREE(found_encoding);
3655 return NULL;
3656 }
3657 }
3658 else {
3659 fob = Py_None;
3660 Py_INCREF(fob);
3661 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003662 if (pathobj == NULL) {
3663 Py_INCREF(Py_None);
3664 pathobj = Py_None;
3665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 ret = Py_BuildValue("NN(ssi)",
3667 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3668 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003671}
3672
Guido van Rossum79f25d91997-04-29 20:08:16 +00003673static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003674imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003675{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003676 PyObject *name, *path_list = NULL;
3677 if (!PyArg_ParseTuple(args, "U|O:find_module",
3678 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003680 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003681}
3682
3683static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003684imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003685{
Victor Stinner95872862011-03-07 18:20:56 +01003686 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 int ret;
3688 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003689 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 return NULL;
3691 ret = init_builtin(name);
3692 if (ret < 0)
3693 return NULL;
3694 if (ret == 0) {
3695 Py_INCREF(Py_None);
3696 return Py_None;
3697 }
Victor Stinner95872862011-03-07 18:20:56 +01003698 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 Py_XINCREF(m);
3700 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003701}
3702
Guido van Rossum79f25d91997-04-29 20:08:16 +00003703static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003704imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003705{
Victor Stinner53dc7352011-03-20 01:50:21 +01003706 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 int ret;
3708 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003709 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003710 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003711 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 if (ret < 0)
3713 return NULL;
3714 if (ret == 0) {
3715 Py_INCREF(Py_None);
3716 return Py_None;
3717 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003718 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 Py_XINCREF(m);
3720 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003721}
3722
Guido van Rossum79f25d91997-04-29 20:08:16 +00003723static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003724imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003725{
Victor Stinner53dc7352011-03-20 01:50:21 +01003726 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003727
Victor Stinner53dc7352011-03-20 01:50:21 +01003728 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 return NULL;
3730 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003731}
3732
Guido van Rossum79f25d91997-04-29 20:08:16 +00003733static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003734imp_is_frozen_package(PyObject *self, PyObject *args)
3735{
Victor Stinner53dc7352011-03-20 01:50:21 +01003736 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003737
Victor Stinner53dc7352011-03-20 01:50:21 +01003738 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 return NULL;
3740 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003741}
3742
3743static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003744imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003745{
Victor Stinner95872862011-03-07 18:20:56 +01003746 PyObject *name;
3747 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 return NULL;
3749 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003750}
3751
Guido van Rossum79f25d91997-04-29 20:08:16 +00003752static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003753imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003754{
Victor Stinner53dc7352011-03-20 01:50:21 +01003755 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003757 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 return NULL;
3759 p = find_frozen(name);
3760 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003761}
3762
3763static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003764get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 FILE *fp;
3767 if (mode[0] == 'U')
3768 mode = "r" PY_STDIOTEXTMODE;
3769 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003770 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003771 if (!fp) {
3772 if (!PyErr_Occurred())
3773 PyErr_SetFromErrno(PyExc_IOError);
3774 return NULL;
3775 }
3776 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 }
3778 else {
3779 int fd = PyObject_AsFileDescriptor(fob);
3780 if (fd == -1)
3781 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01003782 if (!_PyVerify_fd(fd)) {
3783 PyErr_SetFromErrno(PyExc_IOError);
3784 return NULL;
3785 }
3786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 /* the FILE struct gets a new fd, so that it can be closed
3788 * independently of the file descriptor given
3789 */
3790 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01003791 if (fd == -1) {
3792 PyErr_SetFromErrno(PyExc_IOError);
3793 return NULL;
3794 }
3795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003797 if (!fp) {
3798 PyErr_SetFromErrno(PyExc_IOError);
3799 return NULL;
3800 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003802 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003803}
3804
Guido van Rossum79f25d91997-04-29 20:08:16 +00003805static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003806imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003807{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003808 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 PyObject *fob = NULL;
3810 PyObject *m;
3811 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003812 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003814 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 &fob))
3816 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003817 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003819 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 return NULL;
3821 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003822 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003824 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003826}
3827
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003828#ifdef HAVE_DYNAMIC_LOADING
3829
Guido van Rossum79f25d91997-04-29 20:08:16 +00003830static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003831imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003832{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003833 PyObject *name, *pathname, *fob = NULL, *mod;
3834 FILE *fp;
3835
3836 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3837 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003839 if (fob != NULL) {
3840 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003841 if (fp == NULL) {
3842 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003846 else
3847 fp = NULL;
3848 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003849 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if (fp)
3851 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003852 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003853}
3854
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003855#endif /* HAVE_DYNAMIC_LOADING */
3856
Guido van Rossum79f25d91997-04-29 20:08:16 +00003857static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003858imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003859{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003860 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 PyObject *fob = NULL;
3862 PyObject *m;
3863 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003864 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003866 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 &fob))
3868 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003869 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003871 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 return NULL;
3873 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003874 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003875 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 fclose(fp);
3877 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003878}
3879
Guido van Rossum79f25d91997-04-29 20:08:16 +00003880static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003881imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003882{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003883 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003884 char *suffix; /* Unused */
3885 char *mode;
3886 int type;
3887 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003888
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003889 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3890 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003892 if (pathname_obj != Py_None) {
3893 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3894 return NULL;
3895 }
3896 else
3897 pathname = NULL;
3898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 if (*mode) {
3900 /* Mode must start with 'r' or 'U' and must not contain '+'.
3901 Implicit in this test is the assumption that the mode
3902 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3905 PyErr_Format(PyExc_ValueError,
3906 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003907 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 return NULL;
3909 }
3910 }
3911 if (fob == Py_None)
3912 fp = NULL;
3913 else {
3914 fp = get_file(NULL, fob, mode);
3915 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003916 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 return NULL;
3918 }
3919 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003920 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003921 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 if (fp)
3923 fclose(fp);
3924 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003925}
3926
3927static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003928imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003929{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003930 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003932 if (!PyArg_ParseTuple(args, "UO&:load_package",
3933 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003935 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003936 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003938}
3939
3940static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003941imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003942{
Victor Stinnerfe19d212011-03-14 14:53:28 -04003943 PyObject *name;
3944 if (!PyArg_ParseTuple(args, "U:new_module", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 return NULL;
Victor Stinnerfe19d212011-03-14 14:53:28 -04003946 return PyModule_NewObject(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003947}
3948
Christian Heimes13a7a212008-01-07 17:13:09 +00003949static PyObject *
3950imp_reload(PyObject *self, PyObject *v)
3951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003953}
3954
3955PyDoc_STRVAR(doc_reload,
3956"reload(module) -> module\n\
3957\n\
3958Reload the module. The module must have been successfully imported before.");
3959
Barry Warsaw28a691b2010-04-17 00:19:56 +00003960static PyObject *
3961imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003964
Victor Stinner2f42ae52011-03-20 00:41:24 +01003965 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003966 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003970 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003971 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003973
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003974 if (debug_override != NULL &&
3975 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003976 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003977 return NULL;
3978 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003979
Martin v. Löwis30260a72011-10-23 17:35:46 +02003980 if (PyUnicode_READY(pathname) < 0)
3981 return NULL;
3982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003983 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003984 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 if (cpathname == NULL) {
3987 PyErr_Format(PyExc_SystemError, "path buffer too short");
3988 return NULL;
3989 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003990 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003991}
3992
3993PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01003994"cache_from_source(path, [debug_override]) -> path\n\
3995Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003996\n\
3997The .py file does not need to exist; this simply returns the path to the\n\
3998.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3999will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
4000\n\
4001If debug_override is not None, then it must be a boolean and is taken as\n\
4002the value of __debug__ instead.");
4003
4004static PyObject *
4005imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
4006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04004008 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00004011 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04004012 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004014
Victor Stinnerc9abda02011-03-14 13:33:46 -04004015 source = make_source_pathname(pathname);
4016 if (source == NULL) {
4017 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04004019 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 return NULL;
4021 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04004022 Py_DECREF(pathname);
4023 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004024}
4025
4026PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01004027"source_from_cache(path) -> path\n\
4028Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004029\n\
4030The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
4031the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
4032does not conform to PEP 3147 format, ValueError will be raised.");
4033
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004034/* Doc strings */
4035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004036PyDoc_STRVAR(doc_imp,
4037"This module provides the components needed to build your own\n\
4038__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004040PyDoc_STRVAR(doc_find_module,
4041"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004042Search for a module. If path is omitted or None, search for a\n\
4043built-in, frozen or special module and continue search in sys.path.\n\
4044The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004045package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004047PyDoc_STRVAR(doc_load_module,
4048"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004049Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004050The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004052PyDoc_STRVAR(doc_get_magic,
4053"get_magic() -> string\n\
4054Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004055
Barry Warsaw28a691b2010-04-17 00:19:56 +00004056PyDoc_STRVAR(doc_get_tag,
4057"get_tag() -> string\n\
4058Return the magic tag for .pyc or .pyo files.");
4059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004060PyDoc_STRVAR(doc_get_suffixes,
4061"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004062Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004063that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004065PyDoc_STRVAR(doc_new_module,
4066"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004067Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004068The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004069
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004070PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00004071"lock_held() -> boolean\n\
4072Return True if the import lock is currently held, else False.\n\
4073On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00004074
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004075PyDoc_STRVAR(doc_acquire_lock,
4076"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00004077Acquires the interpreter's import lock for the current thread.\n\
4078This lock should be used by import hooks to ensure thread-safety\n\
4079when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004080On platforms without threads, this function does nothing.");
4081
4082PyDoc_STRVAR(doc_release_lock,
4083"release_lock() -> None\n\
4084Release the interpreter's import lock.\n\
4085On platforms without threads, this function does nothing.");
4086
Guido van Rossum79f25d91997-04-29 20:08:16 +00004087static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
4089 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
4090 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
4091 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
4092 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
4093 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
4094 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
4095 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
4096 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
4097 {"reload", imp_reload, METH_O, doc_reload},
4098 {"cache_from_source", (PyCFunction)imp_cache_from_source,
4099 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
4100 {"source_from_cache", (PyCFunction)imp_source_from_cache,
4101 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
4102 /* The rest are obsolete */
4103 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
4104 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
4105 {"init_builtin", imp_init_builtin, METH_VARARGS},
4106 {"init_frozen", imp_init_frozen, METH_VARARGS},
4107 {"is_builtin", imp_is_builtin, METH_VARARGS},
4108 {"is_frozen", imp_is_frozen, METH_VARARGS},
4109 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004110#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004112#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 {"load_package", imp_load_package, METH_VARARGS},
4114 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07004115 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004117};
4118
Guido van Rossum1a8791e1998-08-04 22:46:29 +00004119static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004120setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 PyObject *v;
4123 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 v = PyLong_FromLong((long)value);
4126 err = PyDict_SetItemString(d, name, v);
4127 Py_XDECREF(v);
4128 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004129}
4130
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004131typedef struct {
4132 PyObject_HEAD
4133} NullImporter;
4134
4135static int
4136NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
4137{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004138#ifndef MS_WINDOWS
4139 PyObject *path;
4140 struct stat statbuf;
4141 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4144 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004145
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004146 if (!PyArg_ParseTuple(args, "O&:NullImporter",
4147 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004149
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004150 if (PyBytes_GET_SIZE(path) == 0) {
4151 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 PyErr_SetString(PyExc_ImportError, "empty pathname");
4153 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004155
4156 rv = stat(PyBytes_AS_STRING(path), &statbuf);
4157 Py_DECREF(path);
4158 if (rv == 0) {
4159 /* it exists */
4160 if (S_ISDIR(statbuf.st_mode)) {
4161 /* it's a directory */
4162 PyErr_SetString(PyExc_ImportError, "existing directory");
4163 return -1;
4164 }
4165 }
4166#else /* MS_WINDOWS */
4167 PyObject *pathobj;
4168 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00004169 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004170
4171 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4172 return -1;
4173
4174 if (!PyArg_ParseTuple(args, "U:NullImporter",
4175 &pathobj))
4176 return -1;
4177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004178 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004179 PyErr_SetString(PyExc_ImportError, "empty pathname");
4180 return -1;
4181 }
4182
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00004183 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004184 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004185 return -1;
4186 /* see issue1293 and issue3677:
4187 * stat() on Windows doesn't recognise paths like
4188 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
4189 */
4190 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004191 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004192 if (rv != INVALID_FILE_ATTRIBUTES) {
4193 /* it exists */
4194 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
4195 /* it's a directory */
4196 PyErr_SetString(PyExc_ImportError, "existing directory");
4197 return -1;
4198 }
4199 }
4200#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004202}
4203
4204static PyObject *
4205NullImporter_find_module(NullImporter *self, PyObject *args)
4206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004208}
4209
4210static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
4212 "Always return None"
4213 },
4214 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004215};
4216
4217
Christian Heimes9cd17752007-11-18 19:35:23 +00004218PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 PyVarObject_HEAD_INIT(NULL, 0)
4220 "imp.NullImporter", /*tp_name*/
4221 sizeof(NullImporter), /*tp_basicsize*/
4222 0, /*tp_itemsize*/
4223 0, /*tp_dealloc*/
4224 0, /*tp_print*/
4225 0, /*tp_getattr*/
4226 0, /*tp_setattr*/
4227 0, /*tp_reserved*/
4228 0, /*tp_repr*/
4229 0, /*tp_as_number*/
4230 0, /*tp_as_sequence*/
4231 0, /*tp_as_mapping*/
4232 0, /*tp_hash */
4233 0, /*tp_call*/
4234 0, /*tp_str*/
4235 0, /*tp_getattro*/
4236 0, /*tp_setattro*/
4237 0, /*tp_as_buffer*/
4238 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4239 "Null importer object", /* tp_doc */
4240 0, /* tp_traverse */
4241 0, /* tp_clear */
4242 0, /* tp_richcompare */
4243 0, /* tp_weaklistoffset */
4244 0, /* tp_iter */
4245 0, /* tp_iternext */
4246 NullImporter_methods, /* tp_methods */
4247 0, /* tp_members */
4248 0, /* tp_getset */
4249 0, /* tp_base */
4250 0, /* tp_dict */
4251 0, /* tp_descr_get */
4252 0, /* tp_descr_set */
4253 0, /* tp_dictoffset */
4254 (initproc)NullImporter_init, /* tp_init */
4255 0, /* tp_alloc */
4256 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004257};
4258
Martin v. Löwis1a214512008-06-11 05:26:20 +00004259static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 PyModuleDef_HEAD_INIT,
4261 "imp",
4262 doc_imp,
4263 0,
4264 imp_methods,
4265 NULL,
4266 NULL,
4267 NULL,
4268 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004269};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004270
Jason Tishler6bc06ec2003-09-04 11:59:50 +00004271PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004272PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 if (PyType_Ready(&PyNullImporter_Type) < 0)
4277 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 m = PyModule_Create(&impmodule);
4280 if (m == NULL)
4281 goto failure;
4282 d = PyModule_GetDict(m);
4283 if (d == NULL)
4284 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004286 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
4287 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
4288 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
4289 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
4290 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
4291 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
4292 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4293 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4294 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4295 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 Py_INCREF(&PyNullImporter_Type);
4298 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4299 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004300 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 Py_XDECREF(m);
4302 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004303}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004304
4305
Guido van Rossumb18618d2000-05-03 23:44:39 +00004306/* API for embedding applications that want to add their own entries
4307 to the table of built-in modules. This should normally be called
4308 *before* Py_Initialize(). When the table resize fails, -1 is
4309 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004310
4311 After a similar function by Just van Rossum. */
4312
4313int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004314PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 static struct _inittab *our_copy = NULL;
4317 struct _inittab *p;
4318 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 /* Count the number of entries in both tables */
4321 for (n = 0; newtab[n].name != NULL; n++)
4322 ;
4323 if (n == 0)
4324 return 0; /* Nothing to do */
4325 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4326 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 /* Allocate new memory for the combined table */
4329 p = our_copy;
4330 PyMem_RESIZE(p, struct _inittab, i+n+1);
4331 if (p == NULL)
4332 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 /* Copy the tables into the new memory */
4335 if (our_copy != PyImport_Inittab)
4336 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4337 PyImport_Inittab = our_copy = p;
4338 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004341}
4342
4343/* Shorthand to add a single entry given a name and a function */
4344
4345int
Brett Cannona826f322009-04-02 03:41:46 +00004346PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 newtab[0].name = (char *)name;
4353 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004356}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004357
4358#ifdef __cplusplus
4359}
4360#endif