blob: 14148c7a1c45d4e5478317ea22817871925f0174 [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)
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500107 Python 3.3a1 3210 (added size modulo 2**32 to the pyc header)
108 3220 (changed PEP 380 implementation)
Tim Peters36515e22001-11-18 04:06:29 +0000109*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000110
Nick Coghlancd419ab2010-09-11 00:39:25 +0000111/* MAGIC must change whenever the bytecode emitted by the compiler may no
112 longer be understood by older implementations of the eval loop (usually
113 due to the addition of new opcodes)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200114 TAG must change for each major Python release. The magic number will take
115 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116*/
Benjamin Peterson48deae12011-06-03 17:50:16 -0500117#define QUOTE(arg) #arg
118#define STRIFY(name) QUOTE(name)
119#define MAJOR STRIFY(PY_MAJOR_VERSION)
120#define MINOR STRIFY(PY_MINOR_VERSION)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100121#define MAGIC (3210 | ((long)'\r'<<16) | ((long)'\n'<<24))
Benjamin Peterson48deae12011-06-03 17:50:16 -0500122#define TAG "cpython-" MAJOR MINOR;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000123#define CACHEDIR "__pycache__"
124/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000125static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000126static const char *pyc_tag = TAG;
Benjamin Peterson48deae12011-06-03 17:50:16 -0500127#undef QUOTE
128#undef STRIFY
129#undef MAJOR
130#undef MINOR
Guido van Rossum96774c12000-05-01 20:19:08 +0000131
Victor Stinner95872862011-03-07 18:20:56 +0100132/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000134
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200135/* Function from Parser/tokenizer.c */
136extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
137
Guido van Rossum771c6c81997-10-31 18:37:24 +0000138/* This table is defined in config.c: */
139extern struct _inittab _PyImport_Inittab[];
140
141struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000142
Guido van Rossumed1170e1999-12-20 21:23:41 +0000143/* these tables define the module suffixes that Python recognizes */
144struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000145
Guido van Rossumed1170e1999-12-20 21:23:41 +0000146static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000148#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000150#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 {".pyc", "rb", PY_COMPILED},
152 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153};
154
Victor Stinnerd0296212011-03-14 14:04:10 -0400155static PyObject *initstr = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200156_Py_IDENTIFIER(__path__);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000158/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159
160void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000161_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 const struct filedescr *scan;
164 struct filedescr *filetab;
165 int countD = 0;
166 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000167
Victor Stinnerd0296212011-03-14 14:04:10 -0400168 initstr = PyUnicode_InternFromString("__init__");
169 if (initstr == NULL)
170 Py_FatalError("Can't initialize import variables");
171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 /* prepare _PyImport_Filetab: copy entries from
173 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
174 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000175#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
177 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000178#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
180 ++countS;
181 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
182 if (filetab == NULL)
183 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000184#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 memcpy(filetab, _PyImport_DynLoadFiletab,
186 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000187#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 memcpy(filetab + countD, _PyImport_StandardFiletab,
189 countS * sizeof(struct filedescr));
190 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 if (Py_OptimizeFlag) {
195 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
196 for (; filetab->suffix != NULL; filetab++) {
197 if (strcmp(filetab->suffix, ".pyc") == 0)
198 filetab->suffix = ".pyo";
199 }
200 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201}
202
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203void
Just van Rossum52e14d62002-12-30 22:08:05 +0000204_PyImportHooks_Init(void)
205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 PyObject *v, *path_hooks = NULL, *zimpimport;
207 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 /* adding sys.path_hooks and sys.path_importer_cache, setting up
210 zipimport */
211 if (PyType_Ready(&PyNullImporter_Type) < 0)
212 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (Py_VerboseFlag)
215 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 v = PyList_New(0);
218 if (v == NULL)
219 goto error;
220 err = PySys_SetObject("meta_path", v);
221 Py_DECREF(v);
222 if (err)
223 goto error;
224 v = PyDict_New();
225 if (v == NULL)
226 goto error;
227 err = PySys_SetObject("path_importer_cache", v);
228 Py_DECREF(v);
229 if (err)
230 goto error;
231 path_hooks = PyList_New(0);
232 if (path_hooks == NULL)
233 goto error;
234 err = PySys_SetObject("path_hooks", path_hooks);
235 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000236 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyErr_Print();
238 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
239 "path_importer_cache, or NullImporter failed"
240 );
241 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 zimpimport = PyImport_ImportModule("zipimport");
244 if (zimpimport == NULL) {
245 PyErr_Clear(); /* No zip import module -- okay */
246 if (Py_VerboseFlag)
247 PySys_WriteStderr("# can't import zipimport\n");
248 }
249 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200250 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200251 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
252 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 Py_DECREF(zimpimport);
254 if (zipimporter == NULL) {
255 PyErr_Clear(); /* No zipimporter object -- okay */
256 if (Py_VerboseFlag)
257 PySys_WriteStderr(
258 "# can't import zipimport.zipimporter\n");
259 }
260 else {
261 /* sys.path_hooks.append(zipimporter) */
262 err = PyList_Append(path_hooks, zipimporter);
263 Py_DECREF(zipimporter);
264 if (err)
265 goto error;
266 if (Py_VerboseFlag)
267 PySys_WriteStderr(
268 "# installed zipimport hook\n");
269 }
270 }
271 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000272}
273
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000274/* Locking primitives to prevent parallel imports of the same module
275 in different threads to return with a partially loaded module.
276 These calls are serialized by the global interpreter lock. */
277
278#ifdef WITH_THREAD
279
Guido van Rossum49b56061998-10-01 20:42:43 +0000280#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000281
Guido van Rossum65d5b571998-12-21 19:32:43 +0000282static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000283static long import_lock_thread = -1;
284static int import_lock_level = 0;
285
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000286void
287_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 long me = PyThread_get_thread_ident();
290 if (me == -1)
291 return; /* Too bad */
292 if (import_lock == NULL) {
293 import_lock = PyThread_allocate_lock();
294 if (import_lock == NULL)
295 return; /* Nothing much we can do. */
296 }
297 if (import_lock_thread == me) {
298 import_lock_level++;
299 return;
300 }
301 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
302 {
303 PyThreadState *tstate = PyEval_SaveThread();
304 PyThread_acquire_lock(import_lock, 1);
305 PyEval_RestoreThread(tstate);
306 }
307 import_lock_thread = me;
308 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000309}
310
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000311int
312_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 long me = PyThread_get_thread_ident();
315 if (me == -1 || import_lock == NULL)
316 return 0; /* Too bad */
317 if (import_lock_thread != me)
318 return -1;
319 import_lock_level--;
320 if (import_lock_level == 0) {
321 import_lock_thread = -1;
322 PyThread_release_lock(import_lock);
323 }
324 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000325}
326
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000327/* This function is called from PyOS_AfterFork to ensure that newly
328 created child processes do not share locks with the parent.
329 We now acquire the import lock around fork() calls but on some platforms
330 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000331
332void
333_PyImport_ReInitLock(void)
334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (import_lock != NULL)
336 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000337 if (import_lock_level > 1) {
338 /* Forked as a side effect of import */
339 long me = PyThread_get_thread_ident();
340 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100341 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000342 import_lock_thread = me;
343 import_lock_level--;
344 } else {
345 import_lock_thread = -1;
346 import_lock_level = 0;
347 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000348}
349
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000350#endif
351
Tim Peters69232342001-08-30 05:16:13 +0000352static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000353imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000354{
Tim Peters69232342001-08-30 05:16:13 +0000355#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000357#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000359#endif
360}
361
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000362static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000363imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000364{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000365#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000367#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 Py_INCREF(Py_None);
369 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000370}
371
372static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000373imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000374{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000375#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (_PyImport_ReleaseLock() < 0) {
377 PyErr_SetString(PyExc_RuntimeError,
378 "not holding the import lock");
379 return NULL;
380 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000381#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_INCREF(Py_None);
383 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000384}
385
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100386void
387_PyImport_Fini(void)
388{
389 Py_XDECREF(extensions);
390 extensions = NULL;
391 PyMem_DEL(_PyImport_Filetab);
392 _PyImport_Filetab = NULL;
393#ifdef WITH_THREAD
394 if (import_lock != NULL) {
395 PyThread_free_lock(import_lock);
396 import_lock = NULL;
397 }
398#endif
399}
400
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401static void
402imp_modules_reloading_clear(void)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyInterpreterState *interp = PyThreadState_Get()->interp;
405 if (interp->modules_reloading != NULL)
406 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000407}
408
Guido van Rossum25ce5661997-08-02 03:10:38 +0000409/* Helper for sys */
410
411PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000412PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyInterpreterState *interp = PyThreadState_GET()->interp;
415 if (interp->modules == NULL)
416 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
417 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418}
419
Guido van Rossum3f5da241990-12-20 15:06:42 +0000420
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000421/* List of names to clear in sys */
422static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 "path", "argv", "ps1", "ps2",
424 "last_type", "last_value", "last_traceback",
425 "path_hooks", "path_importer_cache", "meta_path",
426 /* misc stuff */
427 "flags", "float_info",
428 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000429};
430
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000431static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 "stdin", "__stdin__",
433 "stdout", "__stdout__",
434 "stderr", "__stderr__",
435 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000436};
437
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000438
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000439/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000440
Guido van Rossum3f5da241990-12-20 15:06:42 +0000441void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000442PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PyObject *key, *value, *dict;
446 PyInterpreterState *interp = PyThreadState_GET()->interp;
447 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (modules == NULL)
450 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 /* Delete some special variables first. These are common
453 places where user values hide and people complain when their
454 destructors fail. Since the modules containing them are
455 deleted *last* of all, they would come too late in the normal
456 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 value = PyDict_GetItemString(modules, "builtins");
459 if (value != NULL && PyModule_Check(value)) {
460 dict = PyModule_GetDict(value);
461 if (Py_VerboseFlag)
462 PySys_WriteStderr("# clear builtins._\n");
463 PyDict_SetItemString(dict, "_", Py_None);
464 }
465 value = PyDict_GetItemString(modules, "sys");
466 if (value != NULL && PyModule_Check(value)) {
467 char **p;
468 PyObject *v;
469 dict = PyModule_GetDict(value);
470 for (p = sys_deletes; *p != NULL; p++) {
471 if (Py_VerboseFlag)
472 PySys_WriteStderr("# clear sys.%s\n", *p);
473 PyDict_SetItemString(dict, *p, Py_None);
474 }
475 for (p = sys_files; *p != NULL; p+=2) {
476 if (Py_VerboseFlag)
477 PySys_WriteStderr("# restore sys.%s\n", *p);
478 v = PyDict_GetItemString(dict, *(p+1));
479 if (v == NULL)
480 v = Py_None;
481 PyDict_SetItemString(dict, *p, v);
482 }
483 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* First, delete __main__ */
486 value = PyDict_GetItemString(modules, "__main__");
487 if (value != NULL && PyModule_Check(value)) {
488 if (Py_VerboseFlag)
489 PySys_WriteStderr("# cleanup __main__\n");
490 _PyModule_Clear(value);
491 PyDict_SetItemString(modules, "__main__", Py_None);
492 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* The special treatment of "builtins" here is because even
495 when it's not referenced as a module, its dictionary is
496 referenced by almost every module's __builtins__. Since
497 deleting a module clears its dictionary (even if there are
498 references left to it), we need to delete the "builtins"
499 module last. Likewise, we don't delete sys until the very
500 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 Also note that we 'delete' modules by replacing their entry
503 in the modules dict with None, rather than really deleting
504 them; this avoids a rehash of the modules dictionary and
505 also marks them as "non existent" so they won't be
506 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Next, repeatedly delete modules with a reference count of
509 one (skipping builtins and sys) and delete them */
510 do {
511 ndone = 0;
512 pos = 0;
513 while (PyDict_Next(modules, &pos, &key, &value)) {
514 if (value->ob_refcnt != 1)
515 continue;
516 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100517 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100519 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 continue;
521 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100522 PySys_FormatStderr(
523 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 _PyModule_Clear(value);
525 PyDict_SetItem(modules, key, Py_None);
526 ndone++;
527 }
528 }
529 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* Next, delete all modules (still skipping builtins and sys) */
532 pos = 0;
533 while (PyDict_Next(modules, &pos, &key, &value)) {
534 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100535 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100537 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 continue;
539 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100540 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 _PyModule_Clear(value);
542 PyDict_SetItem(modules, key, Py_None);
543 }
544 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* Next, delete sys and builtins (in that order) */
547 value = PyDict_GetItemString(modules, "sys");
548 if (value != NULL && PyModule_Check(value)) {
549 if (Py_VerboseFlag)
550 PySys_WriteStderr("# cleanup sys\n");
551 _PyModule_Clear(value);
552 PyDict_SetItemString(modules, "sys", Py_None);
553 }
554 value = PyDict_GetItemString(modules, "builtins");
555 if (value != NULL && PyModule_Check(value)) {
556 if (Py_VerboseFlag)
557 PySys_WriteStderr("# cleanup builtins\n");
558 _PyModule_Clear(value);
559 PyDict_SetItemString(modules, "builtins", Py_None);
560 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* Finally, clear and delete the modules directory */
563 PyDict_Clear(modules);
564 interp->modules = NULL;
565 Py_DECREF(modules);
566 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000567}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000568
569
Barry Warsaw28a691b2010-04-17 00:19:56 +0000570/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000571
572long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000573PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576}
577
578
Barry Warsaw28a691b2010-04-17 00:19:56 +0000579const char *
580PyImport_GetMagicTag(void)
581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000583}
584
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585/* Magic for extension modules (built-in as well as dynamically
586 loaded). To prevent initializing an extension module more than
587 once, we keep a static dictionary 'extensions' keyed by module name
588 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000589 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100590 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591 immediately after the module initialization function succeeds. A
592 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100593 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000594
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000595 Modules which do support multiple initialization set their m_size
596 field to a non-negative number (indicating the size of the
597 module-specific state). They are still recorded in the extensions
598 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000599*/
600
601int
Victor Stinner95872862011-03-07 18:20:56 +0100602_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
603 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 PyObject *modules, *dict;
606 struct PyModuleDef *def;
607 if (extensions == NULL) {
608 extensions = PyDict_New();
609 if (extensions == NULL)
610 return -1;
611 }
612 if (mod == NULL || !PyModule_Check(mod)) {
613 PyErr_BadInternalCall();
614 return -1;
615 }
616 def = PyModule_GetDef(mod);
617 if (!def) {
618 PyErr_BadInternalCall();
619 return -1;
620 }
621 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100622 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return -1;
624 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100625 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return -1;
627 }
628 if (def->m_size == -1) {
629 if (def->m_base.m_copy) {
630 /* Somebody already imported the module,
631 likely under a different name.
632 XXX this should really not happen. */
633 Py_DECREF(def->m_base.m_copy);
634 def->m_base.m_copy = NULL;
635 }
636 dict = PyModule_GetDict(mod);
637 if (dict == NULL)
638 return -1;
639 def->m_base.m_copy = PyDict_Copy(dict);
640 if (def->m_base.m_copy == NULL)
641 return -1;
642 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000643 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000645}
646
Victor Stinner49d3f252010-10-17 01:24:53 +0000647int
648_PyImport_FixupBuiltin(PyObject *mod, char *name)
649{
650 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100651 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100652 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100653 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000654 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100655 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
656 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000657 return res;
658}
659
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100661_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyObject *mod, *mdict;
664 PyModuleDef* def;
665 if (extensions == NULL)
666 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000667 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (def == NULL)
669 return NULL;
670 if (def->m_size == -1) {
671 /* Module does not support repeated initialization */
672 if (def->m_base.m_copy == NULL)
673 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100674 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (mod == NULL)
676 return NULL;
677 mdict = PyModule_GetDict(mod);
678 if (mdict == NULL)
679 return NULL;
680 if (PyDict_Update(mdict, def->m_base.m_copy))
681 return NULL;
682 }
683 else {
684 if (def->m_base.m_init == NULL)
685 return NULL;
686 mod = def->m_base.m_init();
687 if (mod == NULL)
688 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100689 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 Py_DECREF(mod);
691 }
692 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100693 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 Py_DECREF(mod);
695 return NULL;
696 }
697 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100698 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 name, filename);
700 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000701
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702}
703
Victor Stinner49d3f252010-10-17 01:24:53 +0000704PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000705_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000706{
Victor Stinner95872862011-03-07 18:20:56 +0100707 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100708 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100709 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000710 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100711 res = _PyImport_FindExtensionObject(nameobj, nameobj);
712 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000713 return res;
714}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715
716/* Get the module object corresponding to a module name.
717 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000718 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000719 Because the former action is most common, THIS DOES NOT RETURN A
720 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721
Guido van Rossum79f25d91997-04-29 20:08:16 +0000722PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000723PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyObject *modules = PyImport_GetModuleDict();
726 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000727
Victor Stinner27ee0892011-03-04 12:57:09 +0000728 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyModule_Check(m))
730 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000731 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (m == NULL)
733 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000734 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 Py_DECREF(m);
736 return NULL;
737 }
738 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000741}
742
Victor Stinner27ee0892011-03-04 12:57:09 +0000743PyObject *
744PyImport_AddModule(const char *name)
745{
746 PyObject *nameobj, *module;
747 nameobj = PyUnicode_FromString(name);
748 if (nameobj == NULL)
749 return NULL;
750 module = PyImport_AddModuleObject(nameobj);
751 Py_DECREF(nameobj);
752 return module;
753}
754
755
Tim Peters1cd70172004-08-02 03:52:12 +0000756/* Remove name from sys.modules, if it's there. */
757static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000758remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000761 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000763 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 Py_FatalError("import: deleting existing key in"
765 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000766}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767
Victor Stinnerc9abda02011-03-14 13:33:46 -0400768static PyObject * get_sourcefile(PyObject *filename);
769static PyObject *make_source_pathname(PyObject *pathname);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200770static PyObject* make_compiled_pathname(PyObject *pathname, int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000771
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000772/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000773 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
774 * removed from sys.modules, to avoid leaving damaged module objects
775 * in sys.modules. The caller may wish to restore the original
776 * module object (if any) in this case; PyImport_ReloadModule is an
777 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000778 *
779 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
780 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000781 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000782PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000783PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return PyImport_ExecCodeModuleWithPathnames(
786 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000787}
788
789PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000790PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 return PyImport_ExecCodeModuleWithPathnames(
793 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000794}
795
796PyObject *
797PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000799{
Victor Stinner27ee0892011-03-04 12:57:09 +0000800 PyObject *m = NULL;
801 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
802
803 nameobj = PyUnicode_FromString(name);
804 if (nameobj == NULL)
805 return NULL;
806
807 if (pathname != NULL) {
808 pathobj = PyUnicode_DecodeFSDefault(pathname);
809 if (pathobj == NULL)
810 goto error;
811 } else
812 pathobj = NULL;
813 if (cpathname != NULL) {
814 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
815 if (cpathobj == NULL)
816 goto error;
817 } else
818 cpathobj = NULL;
819 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
820error:
821 Py_DECREF(nameobj);
822 Py_XDECREF(pathobj);
823 Py_XDECREF(cpathobj);
824 return m;
825}
826
827PyObject*
828PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
829 PyObject *cpathname)
830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *modules = PyImport_GetModuleDict();
832 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833
Victor Stinner27ee0892011-03-04 12:57:09 +0000834 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (m == NULL)
836 return NULL;
837 /* If the module is being reloaded, we get the old module back
838 and re-use its dict to exec the new code. */
839 d = PyModule_GetDict(m);
840 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
841 if (PyDict_SetItemString(d, "__builtins__",
842 PyEval_GetBuiltins()) != 0)
843 goto error;
844 }
845 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400847 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (v == NULL)
849 PyErr_Clear();
850 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000851 else
852 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (v == NULL) {
854 v = ((PyCodeObject *)co)->co_filename;
855 Py_INCREF(v);
856 }
857 if (PyDict_SetItemString(d, "__file__", v) != 0)
858 PyErr_Clear(); /* Not important enough to report */
859 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000862 if (cpathname != NULL)
863 v = cpathname;
864 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (PyDict_SetItemString(d, "__cached__", v) != 0)
867 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000868
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000869 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (v == NULL)
871 goto error;
872 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000873
Victor Stinner27ee0892011-03-04 12:57:09 +0000874 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000876 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 name);
878 return NULL;
879 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000884
885 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 remove_module(name);
887 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000888}
889
890
Barry Warsaw28a691b2010-04-17 00:19:56 +0000891/* Like strrchr(string, '/') but searches for the rightmost of either SEP
892 or ALTSEP, if the latter is defined.
893*/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200894static Py_UCS4*
895rightmost_sep(Py_UCS4 *s)
Victor Stinnerc9abda02011-03-14 13:33:46 -0400896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200897 Py_UCS4 *found, c;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400898 for (found = NULL; (c = *s); s++) {
899 if (c == SEP
900#ifdef ALTSEP
901 || c == ALTSEP
902#endif
903 )
904 {
905 found = s;
906 }
907 }
908 return found;
909}
910
Martin v. Löwis2db72862011-10-23 17:29:08 +0200911/* Like rightmost_sep, but operate on unicode objects. */
912static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200913rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200914{
915 Py_ssize_t found, i;
916 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200917 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200918 c = PyUnicode_READ_CHAR(o, i);
919 if (c == SEP
920#ifdef ALTSEP
921 || c == ALTSEP
922#endif
923 )
924 {
925 found = i;
926 }
927 }
928 return found;
929}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400930
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931/* Given a pathname for a Python source file, fill a buffer with the
932 pathname for the corresponding compiled file. Return the pathname
933 for the compiled file, or NULL if there's no space in the buffer.
Victor Stinner2f42ae52011-03-20 00:41:24 +0100934 Doesn't set an exception.
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000935
Martin v. Löwis30260a72011-10-23 17:35:46 +0200936 foo.py -> __pycache__/foo.<tag>.pyc
937
938 pathstr is assumed to be "ready".
939*/
Victor Stinner2f42ae52011-03-20 00:41:24 +0100940
941static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200942make_compiled_pathname(PyObject *pathstr, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000943{
Martin v. Löwis2db72862011-10-23 17:29:08 +0200944 PyObject *result;
945 Py_ssize_t fname, ext, len, i, pos, taglen;
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200946 Py_ssize_t pycache_len = sizeof(CACHEDIR) - 1;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200947 int kind;
948 void *data;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200949 Py_UCS4 lastsep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000950
Martin v. Löwis2db72862011-10-23 17:29:08 +0200951 /* Compute the output string size. */
952 len = PyUnicode_GET_LENGTH(pathstr);
953 /* If there is no separator, this returns -1, so
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200954 fname will be 0. */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200955 fname = rightmost_sep_obj(pathstr, 0, len) + 1;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200956 /* Windows: re-use the last separator character (/ or \\) when
957 appending the __pycache__ path. */
958 if (fname > 0)
959 lastsep = PyUnicode_READ_CHAR(pathstr, fname -1);
960 else
961 lastsep = SEP;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200962 ext = fname - 1;
963 for(i = fname; i < len; i++)
964 if (PyUnicode_READ_CHAR(pathstr, i) == '.')
965 ext = i + 1;
966 if (ext < fname)
967 /* No dot in filename; use entire filename */
968 ext = len;
969
970 /* result = pathstr[:fname] + "__pycache__" + SEP +
971 pathstr[fname:ext] + tag + ".py[co]" */
972 taglen = strlen(pyc_tag);
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200973 result = PyUnicode_New(ext + pycache_len + 1 + taglen + 4,
Martin v. Löwis2db72862011-10-23 17:29:08 +0200974 PyUnicode_MAX_CHAR_VALUE(pathstr));
975 if (!result)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return NULL;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200977 kind = PyUnicode_KIND(result);
978 data = PyUnicode_DATA(result);
979 PyUnicode_CopyCharacters(result, 0, pathstr, 0, fname);
980 pos = fname;
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200981 for (i = 0; i < pycache_len; i++)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200982 PyUnicode_WRITE(kind, data, pos++, CACHEDIR[i]);
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200983 PyUnicode_WRITE(kind, data, pos++, lastsep);
Martin v. Löwis2db72862011-10-23 17:29:08 +0200984 PyUnicode_CopyCharacters(result, pos, pathstr,
985 fname, ext - fname);
986 pos += ext - fname;
987 for (i = 0; pyc_tag[i]; i++)
988 PyUnicode_WRITE(kind, data, pos++, pyc_tag[i]);
989 PyUnicode_WRITE(kind, data, pos++, '.');
990 PyUnicode_WRITE(kind, data, pos++, 'p');
991 PyUnicode_WRITE(kind, data, pos++, 'y');
992 PyUnicode_WRITE(kind, data, pos++, debug ? 'c' : 'o');
993 return result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000994}
995
996
Barry Warsaw28a691b2010-04-17 00:19:56 +0000997/* Given a pathname to a Python byte compiled file, return the path to the
998 source file, if the path matches the PEP 3147 format. This does not check
999 for any file existence, however, if the pyc file name does not match PEP
1000 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001001 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002
Victor Stinnerc9abda02011-03-14 13:33:46 -04001003 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
1004
1005static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001006make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +00001007{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001008 Py_ssize_t left, right, dot0, dot1, len;
1009 Py_ssize_t i, j;
1010 PyObject *result;
1011 int kind;
1012 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001013
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001014 len = PyUnicode_GET_LENGTH(path);
1015 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001016 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 /* Look back two slashes from the end. In between these two slashes
1019 must be the string __pycache__ or this is not a PEP 3147 style
1020 path. It's possible for there to be only one slash.
1021 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001022 right = rightmost_sep_obj(path, 0, len);
1023 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001025 left = rightmost_sep_obj(path, 0, right);
1026 if (left == -1)
1027 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 else
1029 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001030 if (right-left != sizeof(CACHEDIR)-1)
1031 return NULL;
1032 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
1033 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
1034 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* Now verify that the path component to the right of the last slash
1037 has two dots in it.
1038 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001039 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
1040 if (dot0 < 0)
1041 return NULL;
1042 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
1043 if (dot1 < 0)
1044 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001046 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
1047 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 /* This is a PEP 3147 path. Start by copying everything from the
1050 start of pathname up to and including the leftmost slash. Then
1051 copy the file's basename, removing the magic tag and adding a .py
1052 suffix.
1053 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001054 result = PyUnicode_New(left + (dot0-right) + 2,
1055 PyUnicode_MAX_CHAR_VALUE(path));
1056 if (!result)
1057 return NULL;
1058 kind = PyUnicode_KIND(result);
1059 data = PyUnicode_DATA(result);
1060 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
1061 PyUnicode_CopyCharacters(result, left, path, right+1,
1062 (j = dot0-right));
1063 PyUnicode_WRITE(kind, data, i+j, 'p');
1064 PyUnicode_WRITE(kind, data, i+j+1, 'y');
1065 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001066}
1067
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068/* Given a pathname for a Python source file, its time of last
1069 modification, and a pathname for a compiled file, check whether the
1070 compiled file represents the same version of the source. If so,
1071 return a FILE pointer for the compiled file, positioned just after
1072 the header; if not, return NULL.
1073 Doesn't set an exception. */
1074
1075static FILE *
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001076check_compiled_module(PyObject *pathname, struct stat *srcstat, PyObject *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 FILE *fp;
1079 long magic;
1080 long pyc_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001081 long pyc_size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001082
Victor Stinner2f42ae52011-03-20 00:41:24 +01001083 fp = _Py_fopen(cpathname, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (fp == NULL)
1085 return NULL;
1086 magic = PyMarshal_ReadLongFromFile(fp);
1087 if (magic != pyc_magic) {
1088 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001089 PySys_FormatStderr("# %R has bad magic\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 fclose(fp);
1091 return NULL;
1092 }
1093 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001094 if (pyc_mtime != srcstat->st_mtime) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001096 PySys_FormatStderr("# %R has bad mtime\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 fclose(fp);
1098 return NULL;
1099 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001100 pyc_size = PyMarshal_ReadLongFromFile(fp);
1101 if (pyc_size != (srcstat->st_size & 0xFFFFFFFF)) {
1102 if (Py_VerboseFlag)
1103 PySys_FormatStderr("# %R has bad size\n", cpathname);
1104 fclose(fp);
1105 return NULL;
1106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001108 PySys_FormatStderr("# %R matches %R\n", cpathname, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001110}
1111
1112
1113/* Read a code object from a file and check it for validity */
1114
Guido van Rossum79f25d91997-04-29 20:08:16 +00001115static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001116read_compiled_module(PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 co = PyMarshal_ReadLastObjectFromFile(fp);
1121 if (co == NULL)
1122 return NULL;
1123 if (!PyCode_Check(co)) {
1124 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001125 "Non-code object in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 Py_DECREF(co);
1127 return NULL;
1128 }
1129 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001130}
1131
1132
1133/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001134 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001135
Guido van Rossum79f25d91997-04-29 20:08:16 +00001136static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001137load_compiled_module(PyObject *name, PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 long magic;
1140 PyCodeObject *co;
1141 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 magic = PyMarshal_ReadLongFromFile(fp);
1144 if (magic != pyc_magic) {
1145 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001146 "Bad magic number in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return NULL;
1148 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001149 /* Skip mtime and size */
1150 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 (void) PyMarshal_ReadLongFromFile(fp);
1152 co = read_compiled_module(cpathname, fp);
1153 if (co == NULL)
1154 return NULL;
1155 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001156 PySys_FormatStderr("import %U # precompiled from %R\n",
1157 name, cpathname);
1158 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1159 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001163}
1164
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001165/* Parse a source file and return the corresponding code object */
1166
Guido van Rossum79f25d91997-04-29 20:08:16 +00001167static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001168parse_source_module(PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001169{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001170 PyCodeObject *co;
1171 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 mod_ty mod;
1173 PyCompilerFlags flags;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001174 PyArena *arena;
1175
1176 pathbytes = PyUnicode_EncodeFSDefault(pathname);
1177 if (pathbytes == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001179
Victor Stinner2f42ae52011-03-20 00:41:24 +01001180 arena = PyArena_New();
1181 if (arena == NULL) {
1182 Py_DECREF(pathbytes);
1183 return NULL;
1184 }
1185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 flags.cf_flags = 0;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001187 mod = PyParser_ASTFromFile(fp, PyBytes_AS_STRING(pathbytes), NULL,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 Py_file_input, 0, 0, &flags,
1189 NULL, arena);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001190 if (mod != NULL)
1191 co = PyAST_Compile(mod, PyBytes_AS_STRING(pathbytes), NULL, arena);
1192 else
1193 co = NULL;
1194 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyArena_Free(arena);
1196 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001197}
1198
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001199/* Write a compiled module to a file, placing the time of last
1200 modification of its source into the header.
1201 Errors are ignored, if a write error occurs an attempt is made to
1202 remove the file. */
1203
1204static void
Victor Stinner2f42ae52011-03-20 00:41:24 +01001205write_compiled_module(PyCodeObject *co, PyObject *cpathname,
1206 struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208 Py_UCS4 *cpathname_ucs4;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 time_t mtime = srcstat->st_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001211 long size = srcstat->st_size & 0xFFFFFFFF;
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001212 PyObject *cpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001213#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Victor Stinner1f795172011-11-17 00:45:54 +01001215 wchar_t *wdirname, *wpathname, *wpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001216#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 mode_t dirmode = (srcstat->st_mode |
1218 S_IXUSR | S_IXGRP | S_IXOTH |
1219 S_IWUSR | S_IWGRP | S_IWOTH);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001220 PyObject *dirbytes;
Antoine Pitrou707033a2011-10-17 19:28:44 +02001221 PyObject *cpathbytes, *cpathbytes_tmp;
Victor Stinner783c82c2011-04-20 03:27:51 +02001222#endif
Charles-François Natali0c929d92011-11-10 19:12:29 +01001223 int fd;
Victor Stinner783c82c2011-04-20 03:27:51 +02001224 PyObject *dirname;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 Py_UCS4 *dirsep;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001226 int res, ok;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 /* Ensure that the __pycache__ directory exists. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229 cpathname_ucs4 = PyUnicode_AsUCS4Copy(cpathname);
1230 if (!cpathname_ucs4)
1231 return;
1232 dirsep = rightmost_sep(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001233 if (dirsep == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001235 PySys_FormatStderr("# no %s path found %R\n", CACHEDIR, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return;
1237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 dirname = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
1239 cpathname_ucs4,
1240 dirsep - cpathname_ucs4);
1241 PyMem_Free(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001242 if (dirname == NULL) {
1243 PyErr_Clear();
1244 return;
1245 }
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001246
1247#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001248 wdirname = PyUnicode_AsUnicode(dirname);
1249 if (wdirname == NULL) {
1250 PyErr_Clear();
1251 return;
1252 }
1253 res = CreateDirectoryW(wdirname, NULL);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001254 ok = (res != 0);
1255 if (!ok && GetLastError() == ERROR_ALREADY_EXISTS)
1256 ok = 1;
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001257#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001258 dirbytes = PyUnicode_EncodeFSDefault(dirname);
1259 if (dirbytes == NULL) {
1260 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 return;
1262 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001263 res = mkdir(PyBytes_AS_STRING(dirbytes), dirmode);
1264 Py_DECREF(dirbytes);
1265 if (0 <= res)
1266 ok = 1;
1267 else
1268 ok = (errno == EEXIST);
1269#endif
1270 if (!ok) {
1271 if (Py_VerboseFlag)
1272 PySys_FormatStderr("# cannot create cache dir %R\n", dirname);
1273 Py_DECREF(dirname);
1274 return;
1275 }
1276 Py_DECREF(dirname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001277
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001278 /* We first write to a tmp file and then take advantage
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001279 of atomic renaming (which *should* be true even under Windows).
1280 As in importlib, we use id(something) to generate a pseudo-random
1281 filename. mkstemp() can't be used since it doesn't allow specifying
1282 the file access permissions.
1283 */
1284 cpathname_tmp = PyUnicode_FromFormat("%U.%zd",
1285 cpathname, (Py_ssize_t) co);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001286 if (cpathname_tmp == NULL) {
1287 PyErr_Clear();
1288 return;
1289 }
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001290#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001291 wpathname = PyUnicode_AsUnicode(cpathname);
1292 if (wpathname == NULL) {
1293 PyErr_Clear();
1294 return;
1295 }
1296 wpathname_tmp = PyUnicode_AsUnicode(cpathname_tmp);
1297 if (wpathname_tmp == NULL) {
1298 PyErr_Clear();
1299 return;
1300 }
1301
1302 (void)DeleteFileW(wpathname_tmp);
1303 fd = _wopen(wpathname_tmp,
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001304 O_EXCL | O_CREAT | O_WRONLY | O_BINARY,
1305 mode);
Victor Stinner783c82c2011-04-20 03:27:51 +02001306 if (0 <= fd)
1307 fp = fdopen(fd, "wb");
1308 else
1309 fp = NULL;
1310#else
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001311 cpathbytes_tmp = PyUnicode_EncodeFSDefault(cpathname_tmp);
1312 Py_DECREF(cpathname_tmp);
1313 if (cpathbytes_tmp == NULL) {
1314 PyErr_Clear();
1315 return;
1316 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001317 cpathbytes = PyUnicode_EncodeFSDefault(cpathname);
1318 if (cpathbytes == NULL) {
1319 PyErr_Clear();
1320 return;
1321 }
Charles-François Natali0c929d92011-11-10 19:12:29 +01001322 fd = open(PyBytes_AS_STRING(cpathbytes_tmp),
1323 O_CREAT | O_EXCL | O_WRONLY, 0666);
Charles-François Natalie695eec2011-10-31 20:47:31 +01001324 if (0 <= fd)
1325 fp = fdopen(fd, "wb");
1326 else
1327 fp = NULL;
Victor Stinner783c82c2011-04-20 03:27:51 +02001328#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (fp == NULL) {
1330 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001331 PySys_FormatStderr(
1332 "# can't create %R\n", cpathname);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001333#ifdef MS_WINDOWS
1334 Py_DECREF(cpathname_tmp);
1335#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001336 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001337 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001338#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 return;
1340 }
1341 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001342 /* First write a 0 for mtime and size */
1343 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1345 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001346 fflush(fp);
Antoine Pitrou58161662012-01-25 18:06:07 +01001347 /* Now write the true mtime and size (as 32-bit fields) */
Antoine Pitrou707033a2011-10-17 19:28:44 +02001348 fseek(fp, 4L, 0);
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001349 assert(mtime <= 0xFFFFFFFF);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001350 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001351 PyMarshal_WriteLongToFile(size, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (fflush(fp) != 0 || ferror(fp)) {
1353 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001354 PySys_FormatStderr("# can't write %R\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* Don't keep partial file */
1356 fclose(fp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001357#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001358 (void)DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001359 Py_DECREF(cpathname_tmp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001360#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001361 (void) unlink(PyBytes_AS_STRING(cpathbytes_tmp));
Victor Stinner2f42ae52011-03-20 00:41:24 +01001362 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001363 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001364#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 return;
1366 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 fclose(fp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001368 /* Do a (hopefully) atomic rename */
1369#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001370 if (!MoveFileExW(wpathname_tmp, wpathname, MOVEFILE_REPLACE_EXISTING)) {
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001371 if (Py_VerboseFlag)
1372 PySys_FormatStderr("# can't write %R\n", cpathname);
1373 /* Don't keep tmp file */
Victor Stinner1f795172011-11-17 00:45:54 +01001374 (void) DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001375 Py_DECREF(cpathname_tmp);
1376 return;
1377 }
1378 Py_DECREF(cpathname_tmp);
1379#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001380 if (rename(PyBytes_AS_STRING(cpathbytes_tmp),
1381 PyBytes_AS_STRING(cpathbytes))) {
1382 if (Py_VerboseFlag)
1383 PySys_FormatStderr("# can't write %R\n", cpathname);
1384 /* Don't keep tmp file */
1385 unlink(PyBytes_AS_STRING(cpathbytes_tmp));
1386 Py_DECREF(cpathbytes);
1387 Py_DECREF(cpathbytes_tmp);
1388 return;
1389 }
1390 Py_DECREF(cpathbytes);
1391 Py_DECREF(cpathbytes_tmp);
1392#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001394 PySys_FormatStderr("# wrote %R\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001395}
1396
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001397static void
1398update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyObject *constants, *tmp;
1401 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (PyUnicode_Compare(co->co_filename, oldname))
1404 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 tmp = co->co_filename;
1407 co->co_filename = newname;
1408 Py_INCREF(co->co_filename);
1409 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 constants = co->co_consts;
1412 n = PyTuple_GET_SIZE(constants);
1413 for (i = 0; i < n; i++) {
1414 tmp = PyTuple_GET_ITEM(constants, i);
1415 if (PyCode_Check(tmp))
1416 update_code_filenames((PyCodeObject *)tmp,
1417 oldname, newname);
1418 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001419}
1420
Victor Stinner2f42ae52011-03-20 00:41:24 +01001421static void
1422update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001423{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001424 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001425
Victor Stinner2f42ae52011-03-20 00:41:24 +01001426 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1427 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 oldname = co->co_filename;
1430 Py_INCREF(oldname);
1431 update_code_filenames(co, oldname, newname);
1432 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001433}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001434
Brett Cannon442c9b92011-03-23 16:14:42 -07001435static PyObject *
1436imp_fix_co_filename(PyObject *self, PyObject *args)
1437{
1438 PyObject *co;
1439 PyObject *file_path;
1440
1441 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1442 return NULL;
1443
1444 if (!PyCode_Check(co)) {
1445 PyErr_SetString(PyExc_TypeError,
1446 "first argument must be a code object");
1447 return NULL;
1448 }
1449
1450 if (!PyUnicode_Check(file_path)) {
1451 PyErr_SetString(PyExc_TypeError,
1452 "second argument must be a string");
1453 return NULL;
1454 }
1455
1456 update_compiled_module((PyCodeObject*)co, file_path);
1457
1458 Py_RETURN_NONE;
1459}
1460
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001461/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001462 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1463 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001464
Guido van Rossum79f25d91997-04-29 20:08:16 +00001465static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001466load_source_module(PyObject *name, PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 struct stat st;
1469 FILE *fpc;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001470 PyObject *cpathname = NULL, *cpathbytes = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyCodeObject *co;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001472 PyObject *m = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (fstat(fileno(fp), &st) != 0) {
1475 PyErr_Format(PyExc_RuntimeError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001476 "unable to get file status from %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001478 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 }
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001480 if (sizeof st.st_mtime > 4) {
1481 /* Python's .pyc timestamp handling presumes that the timestamp fits
1482 in 4 bytes. Since the code only does an equality comparison,
1483 ordering is not important and we can safely ignore the higher bits
1484 (collisions are extremely unlikely).
1485 */
1486 st.st_mtime &= 0xFFFFFFFF;
1487 }
Martin v. Löwis30260a72011-10-23 17:35:46 +02001488 if (PyUnicode_READY(pathname) < 0)
1489 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 cpathname = make_compiled_pathname(pathname, !Py_OptimizeFlag);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001491
1492 if (cpathname != NULL)
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001493 fpc = check_compiled_module(pathname, &st, cpathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001494 else
1495 fpc = NULL;
1496
1497 if (fpc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 co = read_compiled_module(cpathname, fpc);
1499 fclose(fpc);
1500 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001501 goto error;
1502 update_compiled_module(co, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001504 PySys_FormatStderr("import %U # precompiled from %R\n",
1505 name, cpathname);
1506 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1507 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 }
1509 else {
1510 co = parse_source_module(pathname, fp);
1511 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001512 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001514 PySys_FormatStderr("import %U # from %R\n",
Victor Stinner98dbba52011-03-14 15:15:47 -04001515 name, pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001516 if (cpathname != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1518 if (ro == NULL || !PyObject_IsTrue(ro))
1519 write_compiled_module(co, cpathname, &st);
1520 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001521 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1522 pathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001525
Victor Stinner2f42ae52011-03-20 00:41:24 +01001526error:
1527 Py_XDECREF(cpathbytes);
1528 Py_XDECREF(cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001530}
1531
Christian Heimes3b06e532008-01-07 20:12:44 +00001532/* Get source file -> unicode or None
1533 * Returns the path to the py file if available, else the given path
1534 */
1535static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001536get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001539 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001540 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001542 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001544 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001545 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001547
Victor Stinnerc9abda02011-03-14 13:33:46 -04001548 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001549 fileuni = PyUnicode_AsUCS4Copy(filename);
1550 if (!fileuni)
1551 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001552 if (len < 5
1553 || fileuni[len-4] != '.'
1554 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1555 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1556 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* Start by trying to turn PEP 3147 path into source path. If that
1559 * fails, just chop off the trailing character, i.e. legacy pyc path
1560 * to py.
1561 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001562 py = make_source_pathname(filename);
1563 if (py == NULL) {
1564 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001565 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001567 if (py == NULL)
1568 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001569
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001570 err = _Py_stat(py, &statbuf);
1571 if (err == -2)
1572 goto error;
1573 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001574 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001575 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001576 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001577 Py_DECREF(py);
1578 goto unchanged;
1579
1580error:
1581 PyErr_Clear();
1582unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001583 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001584 Py_INCREF(filename);
1585 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001586}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001587
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001588/* Forward */
Victor Stinner41c5fec2011-03-13 21:46:30 -04001589static PyObject *load_module(PyObject *, FILE *, PyObject *, int, PyObject *);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001590static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001591 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001592static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001593
1594/* Load a package and return its module object WITH INCREMENTED
1595 REFERENCE COUNT */
1596
1597static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001598load_package(PyObject *name, PyObject *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001599{
Victor Stinner41c5fec2011-03-13 21:46:30 -04001600 PyObject *m, *d, *bufobj;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001601 PyObject *file = NULL, *path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 int err;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001603 FILE *fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001605
Victor Stinnerc9abda02011-03-14 13:33:46 -04001606 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (m == NULL)
1608 return NULL;
1609 if (Py_VerboseFlag)
Victor Stinner98dbba52011-03-14 15:15:47 -04001610 PySys_FormatStderr("import %U # directory %R\n",
1611 name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 file = get_sourcefile(pathname);
1613 if (file == NULL)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001614 return NULL;
1615 path_list = Py_BuildValue("[O]", file);
1616 if (path_list == NULL) {
1617 Py_DECREF(file);
1618 return NULL;
1619 }
1620 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 err = PyDict_SetItemString(d, "__file__", file);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001622 Py_DECREF(file);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (err == 0)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001624 err = PyDict_SetItemString(d, "__path__", path_list);
1625 if (err != 0) {
1626 Py_DECREF(path_list);
1627 return NULL;
1628 }
Victor Stinner533d7832011-03-14 13:22:54 -04001629 fdp = find_module(name, initstr, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001630 &bufobj, &fp, NULL);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001631 Py_DECREF(path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 if (fdp == NULL) {
1633 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1634 PyErr_Clear();
1635 Py_INCREF(m);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001636 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 }
1638 else
Victor Stinnerc9abda02011-03-14 13:33:46 -04001639 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001641 m = load_module(name, fp, bufobj, fdp->type, NULL);
1642 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (fp != NULL)
1644 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001646}
1647
1648
1649/* Helper to test for built-in module */
1650
1651static int
Victor Stinner95872862011-03-07 18:20:56 +01001652is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001653{
Victor Stinner95872862011-03-07 18:20:56 +01001654 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001656 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1657 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (PyImport_Inittab[i].initfunc == NULL)
1659 return -1;
1660 else
1661 return 1;
1662 }
1663 }
1664 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001665}
1666
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001667
Just van Rossum52e14d62002-12-30 22:08:05 +00001668/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1669 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001670 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001671 that can handle the path item. Return None if no hook could;
1672 this tells our caller it should fall back to the builtin
1673 import mechanism. Cache the result in path_importer_cache.
1674 Returns a borrowed reference. */
1675
1676static PyObject *
1677get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 PyObject *importer;
1681 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 /* These conditions are the caller's responsibility: */
1684 assert(PyList_Check(path_hooks));
1685 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 nhooks = PyList_Size(path_hooks);
1688 if (nhooks < 0)
1689 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 importer = PyDict_GetItem(path_importer_cache, p);
1692 if (importer != NULL)
1693 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 /* set path_importer_cache[p] to None to avoid recursion */
1696 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1697 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 for (j = 0; j < nhooks; j++) {
1700 PyObject *hook = PyList_GetItem(path_hooks, j);
1701 if (hook == NULL)
1702 return NULL;
1703 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1704 if (importer != NULL)
1705 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1708 return NULL;
1709 }
1710 PyErr_Clear();
1711 }
1712 if (importer == NULL) {
1713 importer = PyObject_CallFunctionObjArgs(
1714 (PyObject *)&PyNullImporter_Type, p, NULL
1715 );
1716 if (importer == NULL) {
1717 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1718 PyErr_Clear();
1719 return Py_None;
1720 }
1721 }
1722 }
1723 if (importer != NULL) {
1724 int err = PyDict_SetItem(path_importer_cache, p, importer);
1725 Py_DECREF(importer);
1726 if (err != 0)
1727 return NULL;
1728 }
1729 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001730}
1731
Christian Heimes9cd17752007-11-18 19:35:23 +00001732PyAPI_FUNC(PyObject *)
1733PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1737 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1738 importer = get_path_importer(path_importer_cache,
1739 path_hooks, path);
1740 }
1741 }
1742 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1743 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001744}
1745
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001746/* Search the path (default sys.path) for a module. Return the
1747 corresponding filedescr struct, and (via return arguments) the
1748 pathname and an open file. Return NULL if the module is not found. */
1749
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001750#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001751extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1752 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001753#endif
1754
Victor Stinner547a2a62011-03-20 03:07:28 +01001755/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001756static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001757static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001758static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001759
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001760/* Get the path of a module: get its importer and call importer.find_module()
1761 hook, or check if the module if a package (if path/__init__.py exists).
1762
1763 -1: error: a Python error occurred
1764 0: ignore: an error occurred because of invalid data, but the error is not
1765 important enough to be reported.
1766 1: get path: module not found, but *buf contains its path
1767 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1768 and *buf is the path */
1769
1770static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001771find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001772 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001773 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001774{
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001775 PyObject *path_unicode, *filename = NULL;
1776 Py_ssize_t len, pos;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001777 struct stat statbuf;
1778 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001779 int err, result, addsep;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001780
1781 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001782 Py_INCREF(path);
1783 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001784 }
1785 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001786 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1787 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1788 if (path_unicode == NULL)
1789 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001790 }
1791 else
1792 return 0;
1793
Victor Stinner46084ba2011-10-06 02:39:42 +02001794 if (PyUnicode_READY(path_unicode))
1795 return -1;
1796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797 len = PyUnicode_GET_LENGTH(path_unicode);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001798 if (PyUnicode_FindChar(path_unicode, 0, 0, len, 1) != -1) {
1799 result = 0;
1800 goto out; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001801 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001802
1803 /* sys.path_hooks import hook */
1804 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001805 _Py_IDENTIFIER(find_module);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001806 PyObject *importer;
1807
1808 importer = get_path_importer(path_importer_cache,
1809 path_hooks, path);
1810 if (importer == NULL) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001811 result = -1;
1812 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001813 }
1814 /* Note: importer is a borrowed reference */
1815 if (importer != Py_None) {
1816 PyObject *loader;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001817 loader = _PyObject_CallMethodId(importer,
1818 &PyId_find_module, "O", fullname);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001819 if (loader == NULL) {
1820 result = -1; /* error */
1821 goto out;
1822 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001823 if (loader != Py_None) {
1824 /* a loader was found */
1825 *p_loader = loader;
1826 *p_fd = &importhookdescr;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001827 result = 2;
1828 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001829 }
1830 Py_DECREF(loader);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001831 result = 0;
1832 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001833 }
1834 }
1835 /* no hook was found, use builtin import */
1836
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001837 addsep = 0;
1838 if (len > 0 && PyUnicode_READ_CHAR(path_unicode, len-1) != SEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001839#ifdef ALTSEP
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001840 && PyUnicode_READ_CHAR(path_unicode, len-1) != ALTSEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001841#endif
1842 )
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001843 addsep = 1;
1844 filename = PyUnicode_New(len + PyUnicode_GET_LENGTH(name) + addsep,
1845 Py_MAX(PyUnicode_MAX_CHAR_VALUE(path_unicode),
1846 PyUnicode_MAX_CHAR_VALUE(name)));
1847 if (filename == NULL) {
1848 result = -1;
1849 goto out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 }
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001851 PyUnicode_CopyCharacters(filename, 0, path_unicode, 0, len);
1852 pos = len;
1853 if (addsep)
Victor Stinner1f795172011-11-17 00:45:54 +01001854 PyUnicode_WRITE(PyUnicode_KIND(filename),
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001855 PyUnicode_DATA(filename),
1856 pos++, SEP);
Victor Stinner1f795172011-11-17 00:45:54 +01001857 PyUnicode_CopyCharacters(filename, pos, name, 0,
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001858 PyUnicode_GET_LENGTH(name));
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001859
1860 /* Check for package import (buf holds a directory name,
1861 and there's an __init__ module in that directory */
1862#ifdef HAVE_STAT
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001863 err = _Py_stat(filename, &statbuf);
1864 if (err == -2) {
1865 result = -1;
1866 goto out;
1867 }
1868 if (err == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001869 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1870 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001871 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001872
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001873 match = case_ok(filename, 0, name);
1874 if (match < 0) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001875 result = -1;
1876 goto out;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001877 }
1878 if (match) { /* case matches */
1879 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001880 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001881 filename = NULL;
Victor Stinnerd0296212011-03-14 14:04:10 -04001882 *p_fd = &fd_package;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001883 result = 2;
1884 goto out;
Victor Stinnerd0296212011-03-14 14:04:10 -04001885 }
1886 else {
1887 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001888 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001889 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001890 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001891 if (err) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001892 result = -1;
1893 goto out;
Victor Stinner547a2a62011-03-20 03:07:28 +01001894 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001895 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001896 }
1897 }
1898#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001899 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001900 filename = NULL;
1901 result = 1;
1902 out:
1903 Py_DECREF(path_unicode);
1904 Py_XDECREF(filename);
1905 return result;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001906}
1907
1908/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001909 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001910
1911 If the module is found, return a file descriptor, write the path in
1912 *p_filename, write the pointer to the file object into *p_fp, and (if
1913 p_loader is not NULL) the loader into *p_loader.
1914
1915 Otherwise, raise an exception and return NULL. */
1916
Victor Stinner37580282011-03-20 01:34:43 +01001917static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001918find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001919 PyObject *search_path_list, PyObject *path_hooks,
1920 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001921 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 struct filedescr *fdp = NULL;
1925 char *filemode;
1926 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001927 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001928 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001929 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001930
Victor Stinner37580282011-03-20 01:34:43 +01001931 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001933 PyObject *path;
1934 int ok;
1935
1936 path = PyList_GetItem(search_path_list, i);
1937 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001939
Victor Stinner2fd76e42011-03-14 15:19:39 -04001940 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001941 ok = find_module_path(fullname, name, path,
1942 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001943 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001944 if (ok < 0)
1945 return NULL;
1946 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001948 if (ok == 2) {
1949 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001950 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001951 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001954 struct stat statbuf;
1955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 filemode = fdp->mode;
1957 if (filemode[0] == 'U')
1958 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001959
Victor Stinner2fd76e42011-03-14 15:19:39 -04001960 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1961 if (filename == NULL) {
1962 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001963 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001964 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001965
1966 if (Py_VerboseFlag > 1)
1967 PySys_FormatStderr("# trying %R\n", filename);
1968
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001969 err = _Py_stat(filename, &statbuf);
1970 if (err == -2) {
1971 Py_DECREF(prefix);
1972 Py_DECREF(filename);
1973 return NULL;
1974 }
1975 if (err != 0 || S_ISDIR(statbuf.st_mode)) {
Charles-François Natali1659b832011-12-07 23:17:58 +01001976 /* it doesn't exist, or it's a directory */
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001977 Py_DECREF(filename);
1978 continue;
1979 }
1980
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001981 fp = _Py_fopen(filename, filemode);
1982 if (fp == NULL) {
1983 Py_DECREF(filename);
Victor Stinner925ef392011-06-20 15:01:10 +02001984 if (PyErr_Occurred()) {
1985 Py_DECREF(prefix);
1986 return NULL;
1987 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001988 continue;
1989 }
1990 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
1991 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001992 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001993 Py_DECREF(filename);
1994 return NULL;
1995 }
1996 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001997 Py_DECREF(prefix);
1998 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04001999 *p_fp = fp;
2000 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002002 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04002003
2004 fclose(fp);
2005 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002007 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 }
Victor Stinnerd0296212011-03-14 14:04:10 -04002009 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002010 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04002011 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002012}
2013
Victor Stinner37580282011-03-20 01:34:43 +01002014/* Find a module:
2015
2016 - try find_module() of each sys.meta_path hook
2017 - try find_frozen()
2018 - try is_builtin()
2019 - try _PyWin_FindRegisteredModule() (Windows only)
2020 - otherwise, call find_module_path_list() with search_path_list (if not
2021 NULL) or sys.path
2022
Victor Stinner2fd76e42011-03-14 15:19:39 -04002023 fullname can be NULL, but only if p_loader is NULL.
2024
Victor Stinner37580282011-03-20 01:34:43 +01002025 Return:
2026
2027 - &fd_builtin (C_BUILTIN) if it is a builtin
2028 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04002029 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01002030 if it is a package
2031 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
2032 importer loader was found
2033 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
2034 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04002035 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01002036 - NULL on error
2037
Victor Stinner2fd76e42011-03-14 15:19:39 -04002038 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
2039 Eg. *p_path is set to NULL for a builtin package.
2040*/
Victor Stinner37580282011-03-20 01:34:43 +01002041
2042static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002043find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002044 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01002045{
2046 Py_ssize_t i, npath;
2047 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
2048 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
2049 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01002050
Victor Stinner2fd76e42011-03-14 15:19:39 -04002051 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01002052 *p_fp = NULL;
2053 if (p_loader != NULL)
2054 *p_loader = NULL;
2055
Victor Stinner37580282011-03-20 01:34:43 +01002056 /* sys.meta_path import hook */
2057 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002058 _Py_IDENTIFIER(find_module);
Victor Stinner37580282011-03-20 01:34:43 +01002059 PyObject *meta_path;
2060
2061 meta_path = PySys_GetObject("meta_path");
2062 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02002063 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002064 "sys.meta_path must be a list of "
2065 "import hooks");
2066 return NULL;
2067 }
2068 Py_INCREF(meta_path); /* zap guard */
2069 npath = PyList_Size(meta_path);
2070 for (i = 0; i < npath; i++) {
2071 PyObject *loader;
2072 PyObject *hook = PyList_GetItem(meta_path, i);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002073 loader = _PyObject_CallMethodId(hook, &PyId_find_module,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002074 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01002075 search_path_list != NULL ?
2076 search_path_list : Py_None);
2077 if (loader == NULL) {
2078 Py_DECREF(meta_path);
2079 return NULL; /* true error */
2080 }
2081 if (loader != Py_None) {
2082 /* a loader was found */
2083 *p_loader = loader;
2084 Py_DECREF(meta_path);
2085 return &importhookdescr;
2086 }
2087 Py_DECREF(loader);
2088 }
2089 Py_DECREF(meta_path);
2090 }
2091
Victor Stinnerdf75a022011-03-14 13:40:04 -04002092 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002093 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01002094
2095 if (search_path_list == NULL) {
2096#ifdef MS_COREDLL
2097 FILE *fp;
2098 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01002099#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04002100 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01002101 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01002102#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04002103 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01002104 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01002105 *p_fp = fp;
2106 return fdp;
2107 }
2108 else if (PyErr_Occurred())
2109 return NULL;
2110#endif
Victor Stinner37580282011-03-20 01:34:43 +01002111 search_path_list = PySys_GetObject("path");
2112 }
2113
2114 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
Victor Stinner16191322011-09-15 19:28:05 +02002115 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002116 "sys.path must be a list of directory names");
2117 return NULL;
2118 }
2119
2120 path_hooks = PySys_GetObject("path_hooks");
2121 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02002122 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002123 "sys.path_hooks must be a list of "
2124 "import hooks");
2125 return NULL;
2126 }
2127 path_importer_cache = PySys_GetObject("path_importer_cache");
2128 if (path_importer_cache == NULL ||
2129 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02002130 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002131 "sys.path_importer_cache must be a dict");
2132 return NULL;
2133 }
2134
2135 return find_module_path_list(fullname, name,
2136 search_path_list, path_hooks,
2137 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002138 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01002139}
2140
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002141/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00002142 * The arguments here are tricky, best shown by example:
2143 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2144 * ^ ^ ^ ^
2145 * |--------------------- buf ---------------------|
2146 * |------------------- len ------------------|
2147 * |------ name -------|
2148 * |----- namelen -----|
2149 * buf is the full path, but len only counts up to (& exclusive of) the
2150 * extension. name is the module name, also exclusive of extension.
2151 *
2152 * We've already done a successful stat() or fopen() on buf, so know that
2153 * there's some match, possibly case-insensitive.
2154 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002155 * case_bytes() is to return 1 if there's a case-sensitive match for
2156 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00002157 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00002158 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002159 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00002160 * on platforms with case-insensitive filesystems. It's trivial to implement
2161 * for case-sensitive filesystems. It's pretty much a cross-platform
2162 * nightmare for systems with case-insensitive filesystems.
2163 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00002164
Tim Peters50d8d372001-02-28 05:34:27 +00002165/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002166 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00002167 */
Jason Tishler7961aa62005-05-20 00:56:54 +00002168#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002169#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00002170
Tim Peters50d8d372001-02-28 05:34:27 +00002171#elif defined(DJGPP)
2172#include <dir.h>
2173
Jason Tishler7961aa62005-05-20 00:56:54 +00002174#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00002175#include <sys/types.h>
2176#include <dirent.h>
2177
Andrew MacIntyred9400542002-02-26 11:41:34 +00002178#elif defined(PYOS_OS2)
2179#define INCL_DOS
2180#define INCL_DOSERRORS
2181#define INCL_NOPMAPI
2182#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00002183#endif
2184
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002185#if defined(DJGPP) \
2186 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
2187 && defined(HAVE_DIRENT_H)) \
2188 || defined(PYOS_OS2)
2189# define USE_CASE_OK_BYTES
2190#endif
2191
2192
2193#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00002194static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002195case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002196{
Tim Peters50d8d372001-02-28 05:34:27 +00002197/* Pick a platform-specific implementation; the sequence of #if's here should
2198 * match the sequence just above.
2199 */
2200
Tim Peters50d8d372001-02-28 05:34:27 +00002201/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002202#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 struct ffblk ffblk;
2204 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (Py_GETENV("PYTHONCASEOK") != NULL)
2207 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2210 if (done) {
2211 PyErr_Format(PyExc_NameError,
2212 "Can't find file for module %.100s\n(filename %.300s)",
2213 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01002214 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 }
2216 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002217
Jason Tishler7961aa62005-05-20 00:56:54 +00002218/* new-fangled macintosh (macosx) or Cygwin */
2219#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 DIR *dirp;
2221 struct dirent *dp;
2222 char dirname[MAXPATHLEN + 1];
2223 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (Py_GETENV("PYTHONCASEOK") != NULL)
2226 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Copy the dir component into dirname; substitute "." if empty */
2229 if (dirlen <= 0) {
2230 dirname[0] = '.';
2231 dirname[1] = '\0';
2232 }
2233 else {
2234 assert(dirlen <= MAXPATHLEN);
2235 memcpy(dirname, buf, dirlen);
2236 dirname[dirlen] = '\0';
2237 }
2238 /* Open the directory and search the entries for an exact match. */
2239 dirp = opendir(dirname);
2240 if (dirp) {
2241 char *nameWithExt = buf + len - namelen;
2242 while ((dp = readdir(dirp)) != NULL) {
2243 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002244#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002246#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002248#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (thislen >= namelen &&
2250 strcmp(dp->d_name, nameWithExt) == 0) {
2251 (void)closedir(dirp);
2252 return 1; /* Found */
2253 }
2254 }
2255 (void)closedir(dirp);
2256 }
2257 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002258
Andrew MacIntyred9400542002-02-26 11:41:34 +00002259/* OS/2 */
2260#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 HDIR hdir = 1;
2262 ULONG srchcnt = 1;
2263 FILEFINDBUF3 ffbuf;
2264 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (Py_GETENV("PYTHONCASEOK") != NULL)
2267 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 rc = DosFindFirst(buf,
2270 &hdir,
2271 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2272 &ffbuf, sizeof(ffbuf),
2273 &srchcnt,
2274 FIL_STANDARD);
2275 if (rc != NO_ERROR)
2276 return 0;
2277 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002278
Tim Peters50d8d372001-02-28 05:34:27 +00002279/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2280#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002281# error "USE_CASE_OK_BYTES is not correctly defined"
2282#endif
2283}
2284#endif
2285
2286/*
2287 * Check if a filename case matchs the name case. We've already done a
2288 * successful stat() or fopen() on buf, so know that there's some match,
2289 * possibly case-insensitive.
2290 *
2291 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
2292 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
2293 * if envar PYTHONCASEOK exists.
2294 *
2295 * case_ok() is used to implement case-sensitive import semantics even
2296 * on platforms with case-insensitive filesystems. It's trivial to implement
2297 * for case-sensitive filesystems. It's pretty much a cross-platform
2298 * nightmare for systems with case-insensitive filesystems.
2299 */
2300
2301static int
2302case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
2303{
2304#ifdef MS_WINDOWS
2305 WIN32_FIND_DATAW data;
2306 HANDLE h;
2307 int cmp;
Victor Stinner1f795172011-11-17 00:45:54 +01002308 wchar_t *wfilename, *wname;
Victor Stinner8c981892011-10-11 22:27:13 +02002309 Py_ssize_t wname_len;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002310
2311 if (Py_GETENV("PYTHONCASEOK") != NULL)
2312 return 1;
2313
Victor Stinner1f795172011-11-17 00:45:54 +01002314 wfilename = PyUnicode_AsUnicode(filename);
2315 if (wfilename == NULL)
2316 return -1;
2317
2318 h = FindFirstFileW(wfilename, &data);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002319 if (h == INVALID_HANDLE_VALUE) {
2320 PyErr_Format(PyExc_NameError,
2321 "Can't find file for module %R\n(filename %R)",
2322 name, filename);
Victor Stinner1f795172011-11-17 00:45:54 +01002323 return -1;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002324 }
2325 FindClose(h);
Victor Stinnerbeac78b2011-10-11 21:55:01 +02002326
2327 wname = PyUnicode_AsUnicodeAndSize(name, &wname_len);
2328 if (wname == NULL)
2329 return -1;
2330
2331 cmp = wcsncmp(data.cFileName, wname, wname_len);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002332 return cmp == 0;
2333#elif defined(USE_CASE_OK_BYTES)
2334 int match;
2335 PyObject *filebytes, *namebytes;
2336 filebytes = PyUnicode_EncodeFSDefault(filename);
2337 if (filebytes == NULL)
2338 return -1;
2339 namebytes = PyUnicode_EncodeFSDefault(name);
2340 if (namebytes == NULL) {
2341 Py_DECREF(filebytes);
2342 return -1;
2343 }
2344 match = case_bytes(
2345 PyBytes_AS_STRING(filebytes),
2346 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01002347 PyBytes_GET_SIZE(namebytes),
2348 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002349 Py_DECREF(filebytes);
2350 Py_DECREF(namebytes);
2351 return match;
2352#else
2353 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002355
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002356#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002357}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002358
Guido van Rossum197346f1997-10-31 18:38:52 +00002359#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002360
Victor Stinner547a2a62011-03-20 03:07:28 +01002361/* Helper to look for __init__.py or __init__.py[co] in potential package.
2362 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00002363static int
Victor Stinner547a2a62011-03-20 03:07:28 +01002364find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00002365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01002367 PyObject *filename;
2368 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002369 int err;
Guido van Rossum197346f1997-10-31 18:38:52 +00002370
Victor Stinner547a2a62011-03-20 03:07:28 +01002371 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
2372 if (filename == NULL)
2373 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002374 err = _Py_stat(filename, &statbuf);
2375 if (err == -2)
2376 return -1;
2377 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002378 /* 3=len(".py") */
2379 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002380 if (match < 0) {
2381 Py_DECREF(filename);
2382 return -1;
2383 }
2384 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002385 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 return 1;
2387 }
2388 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002389 Py_DECREF(filename);
2390
2391 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
2392 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
2393 if (filename == NULL)
2394 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002395 err = _Py_stat(filename, &statbuf);
2396 if (err == -2) {
2397 Py_DECREF(filename);
2398 return -1;
2399 }
2400 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002401 /* 4=len(".pyc") */
2402 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002403 if (match < 0) {
2404 Py_DECREF(filename);
2405 return -1;
2406 }
2407 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002408 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return 1;
2410 }
2411 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002412 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002414}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002415
Guido van Rossum197346f1997-10-31 18:38:52 +00002416#endif /* HAVE_STAT */
2417
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002418
Victor Stinner95872862011-03-07 18:20:56 +01002419static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002420
Victor Stinner44c6c152010-08-09 00:59:10 +00002421static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002422load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002423{
2424 PyObject *m, *modules;
2425 int err;
2426
Victor Stinner44c6c152010-08-09 00:59:10 +00002427 if (type == C_BUILTIN)
2428 err = init_builtin(name);
2429 else
Victor Stinner95872862011-03-07 18:20:56 +01002430 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002431 if (err < 0)
2432 return NULL;
2433 if (err == 0) {
2434 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002435 "Purported %s module %R not found",
2436 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002437 name);
2438 return NULL;
2439 }
2440
2441 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002442 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002443 if (m == NULL) {
2444 PyErr_Format(
2445 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002446 "%s module %R not properly initialized",
2447 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002448 name);
2449 return NULL;
2450 }
2451 Py_INCREF(m);
2452 return m;
2453}
2454
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002455/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002456 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002457
Guido van Rossum79f25d91997-04-29 20:08:16 +00002458static PyObject *
Victor Stinner41c5fec2011-03-13 21:46:30 -04002459load_module(PyObject *name, FILE *fp, PyObject *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* First check that there's an open file (if we need one) */
2464 switch (type) {
2465 case PY_SOURCE:
2466 case PY_COMPILED:
2467 if (fp == NULL) {
2468 PyErr_Format(PyExc_ValueError,
Victor Stinner41c5fec2011-03-13 21:46:30 -04002469 "file object required for import (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 type);
2471 return NULL;
2472 }
2473 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002476
Victor Stinner41c5fec2011-03-13 21:46:30 -04002477 case PY_SOURCE:
2478 m = load_source_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002480
Victor Stinner41c5fec2011-03-13 21:46:30 -04002481 case PY_COMPILED:
2482 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002484
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002485#ifdef HAVE_DYNAMIC_LOADING
Victor Stinner41c5fec2011-03-13 21:46:30 -04002486 case C_EXTENSION:
2487 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002489#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490
Victor Stinner41c5fec2011-03-13 21:46:30 -04002491 case PKG_DIRECTORY:
2492 m = load_package(name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 case C_BUILTIN:
Victor Stinner41c5fec2011-03-13 21:46:30 -04002496 case PY_FROZEN:
2497 m = load_builtin(name, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 case IMP_HOOK: {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002501 _Py_IDENTIFIER(load_module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 if (loader == NULL) {
2503 PyErr_SetString(PyExc_ImportError,
2504 "import hook without loader");
2505 return NULL;
2506 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002507 m = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 break;
2509 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 default:
2512 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002513 "Don't know how to import %R (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 name, type);
2515 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002520}
2521
2522
2523/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002524 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002525 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002526
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002527static int
Victor Stinner95872862011-03-07 18:20:56 +01002528init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002531
Victor Stinner95872862011-03-07 18:20:56 +01002532 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 for (p = PyImport_Inittab; p->name != NULL; p++) {
2536 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002537 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01002538 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (p->initfunc == NULL) {
2540 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002541 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 name);
2543 return -1;
2544 }
2545 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002546 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 mod = (*p->initfunc)();
2548 if (mod == 0)
2549 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002550 /* Remember pointer to module init function. */
2551 def = PyModule_GetDef(mod);
2552 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01002553 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 return -1;
2555 /* FixupExtension has put the module into sys.modules,
2556 so we can release our own reference. */
2557 Py_DECREF(mod);
2558 return 1;
2559 }
2560 }
2561 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002562}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002563
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002564
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002565/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002566
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002567static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002568find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002571
Victor Stinner53dc7352011-03-20 01:50:21 +01002572 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 for (p = PyImport_FrozenModules; ; p++) {
2576 if (p->name == NULL)
2577 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002578 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 break;
2580 }
2581 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002582}
2583
Guido van Rossum79f25d91997-04-29 20:08:16 +00002584static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002585get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 struct _frozen *p = find_frozen(name);
2588 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 if (p == NULL) {
2591 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002592 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 name);
2594 return NULL;
2595 }
2596 if (p->code == NULL) {
2597 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002598 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 name);
2600 return NULL;
2601 }
2602 size = p->size;
2603 if (size < 0)
2604 size = -size;
2605 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002606}
2607
Brett Cannon8d110132009-03-15 02:20:16 +00002608static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002609is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 struct _frozen *p = find_frozen(name);
2612 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 if (p == NULL) {
2615 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002616 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 name);
2618 return NULL;
2619 }
Brett Cannon8d110132009-03-15 02:20:16 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 if (size < 0)
2624 Py_RETURN_TRUE;
2625 else
2626 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002627}
2628
2629
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002630/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002631 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002632 an exception set if the initialization failed.
2633 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002634
2635int
Victor Stinner53dc7352011-03-20 01:50:21 +01002636PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002637{
Victor Stinner53dc7352011-03-20 01:50:21 +01002638 struct _frozen *p;
2639 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 int ispackage;
2641 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002642
Victor Stinner53dc7352011-03-20 01:50:21 +01002643 p = find_frozen(name);
2644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 if (p == NULL)
2646 return 0;
2647 if (p->code == NULL) {
2648 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002649 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 name);
2651 return -1;
2652 }
2653 size = p->size;
2654 ispackage = (size < 0);
2655 if (ispackage)
2656 size = -size;
2657 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002658 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 name, ispackage ? " package" : "");
2660 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2661 if (co == NULL)
2662 return -1;
2663 if (!PyCode_Check(co)) {
2664 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002665 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 name);
2667 goto err_return;
2668 }
2669 if (ispackage) {
2670 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002671 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002673 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 if (m == NULL)
2675 goto err_return;
2676 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 l = PyList_New(1);
2678 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 goto err_return;
2680 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002681 Py_INCREF(name);
2682 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 err = PyDict_SetItemString(d, "__path__", l);
2684 Py_DECREF(l);
2685 if (err != 0)
2686 goto err_return;
2687 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002688 path = PyUnicode_FromString("<frozen>");
2689 if (path == NULL)
2690 goto err_return;
2691 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2692 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 if (m == NULL)
2694 goto err_return;
2695 Py_DECREF(co);
2696 Py_DECREF(m);
2697 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002698err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 Py_DECREF(co);
2700 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002701}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002702
Victor Stinner53dc7352011-03-20 01:50:21 +01002703int
2704PyImport_ImportFrozenModule(char *name)
2705{
2706 PyObject *nameobj;
2707 int ret;
2708 nameobj = PyUnicode_InternFromString(name);
2709 if (nameobj == NULL)
2710 return -1;
2711 ret = PyImport_ImportFrozenModuleObject(nameobj);
2712 Py_DECREF(nameobj);
2713 return ret;
2714}
2715
Guido van Rossum74e6a111994-08-29 12:54:38 +00002716
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002717/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002718 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002719
Guido van Rossum79f25d91997-04-29 20:08:16 +00002720PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002721PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 PyObject *pname;
2724 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 pname = PyUnicode_FromString(name);
2727 if (pname == NULL)
2728 return NULL;
2729 result = PyImport_Import(pname);
2730 Py_DECREF(pname);
2731 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002732}
2733
Christian Heimes072c0f12008-01-03 23:01:04 +00002734/* Import a module without blocking
2735 *
2736 * At first it tries to fetch the module from sys.modules. If the module was
2737 * never loaded before it loads it with PyImport_ImportModule() unless another
2738 * thread holds the import lock. In the latter case the function raises an
2739 * ImportError instead of blocking.
2740 *
2741 * Returns the module object with incremented ref count.
2742 */
2743PyObject *
2744PyImport_ImportModuleNoBlock(const char *name)
2745{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002746 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002747#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002749#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 /* Try to get the module from sys.modules[name] */
2752 modules = PyImport_GetModuleDict();
2753 if (modules == NULL)
2754 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002755
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002756 nameobj = PyUnicode_FromString(name);
2757 if (nameobj == NULL)
2758 return NULL;
2759 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002761 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 Py_INCREF(result);
2763 return result;
2764 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002765 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002766#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 /* check the import lock
2768 * me might be -1 but I ignore the error here, the lock function
2769 * takes care of the problem */
2770 me = PyThread_get_thread_ident();
2771 if (import_lock_thread == -1 || import_lock_thread == me) {
2772 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002773 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 }
2775 else {
2776 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002777 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002779 nameobj);
2780 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002782#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002783 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002784#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002785 Py_DECREF(nameobj);
2786 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002787}
2788
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002789/* Forward declarations for helper routines */
Victor Stinner974389d2011-03-15 09:33:57 +01002790static PyObject *get_parent(PyObject *globals,
2791 PyObject **p_name,
2792 int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002793static PyObject *load_next(PyObject *mod, PyObject *altmod,
Victor Stinner974389d2011-03-15 09:33:57 +01002794 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002795 PyObject **p_prefix);
Victor Stinner974389d2011-03-15 09:33:57 +01002796static int mark_miss(PyObject *name);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002797static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Victor Stinner974389d2011-03-15 09:33:57 +01002798 PyObject *buf, int recursive);
2799static PyObject * import_submodule(PyObject *mod, PyObject *name,
2800 PyObject *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002801
2802/* The Magnum Opus of dotted-name import :-) */
2803
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002804static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01002805import_module_level(PyObject *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002807{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002808 PyObject *parent, *next, *inputname, *outputname;
2809 PyObject *head = NULL;
2810 PyObject *tail = NULL;
2811 PyObject *prefix = NULL;
2812 PyObject *result = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002813 Py_ssize_t sep, altsep;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002815 if (PyUnicode_READY(name))
2816 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002818 sep = PyUnicode_FindChar(name, SEP, 0, PyUnicode_GET_LENGTH(name), 1);
2819 if (sep == -2)
2820 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002821#ifdef ALTSEP
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002822 altsep = PyUnicode_FindChar(name, ALTSEP, 0, PyUnicode_GET_LENGTH(name), 1);
2823 if (altsep == -2)
2824 return NULL;
2825#else
2826 altsep = -1;
Christian Heimes454f37b2008-01-10 00:10:02 +00002827#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002828 if (sep != -1 || altsep != -1)
2829 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 PyErr_SetString(PyExc_ImportError,
2831 "Import by filename is not supported.");
2832 return NULL;
2833 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002834
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002835 parent = get_parent(globals, &prefix, level);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002836 if (parent == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002838 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002839
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002840 if (PyUnicode_READY(prefix))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002841 return NULL;
Victor Stinner974389d2011-03-15 09:33:57 +01002842
2843 head = load_next(parent, level < 0 ? Py_None : parent, name, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002844 &prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 if (head == NULL)
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002846 goto out;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 tail = head;
2849 Py_INCREF(tail);
Victor Stinner974389d2011-03-15 09:33:57 +01002850
2851 if (outputname != NULL) {
2852 while (1) {
2853 inputname = outputname;
2854 next = load_next(tail, tail, inputname, &outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002855 &prefix);
2856 Py_CLEAR(tail);
2857 Py_CLEAR(inputname);
2858 if (next == NULL)
2859 goto out;
Victor Stinner974389d2011-03-15 09:33:57 +01002860 tail = next;
2861
2862 if (outputname == NULL) {
2863 break;
2864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 }
2867 if (tail == Py_None) {
2868 /* If tail is Py_None, both get_parent and load_next found
2869 an empty module name: someone called __import__("") or
2870 doctored faulty bytecode */
Victor Stinner974389d2011-03-15 09:33:57 +01002871 PyErr_SetString(PyExc_ValueError, "Empty module name");
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002872 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 if (fromlist != NULL) {
2876 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2877 fromlist = NULL;
2878 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 if (fromlist == NULL) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002881 result = head;
2882 Py_INCREF(result);
2883 goto out;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002885
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002886 if (!ensure_fromlist(tail, fromlist, prefix, 0))
2887 goto out;
Victor Stinner1f795172011-11-17 00:45:54 +01002888
Martin v. Löwisf45dee92011-10-30 23:50:02 +01002889 result = tail;
2890 Py_INCREF(result);
2891 out:
2892 Py_XDECREF(head);
2893 Py_XDECREF(tail);
2894 Py_XDECREF(prefix);
2895 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002896}
2897
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002898PyObject *
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002899PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2900 PyObject *locals, PyObject *fromlist,
2901 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002902{
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002903 PyObject *mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 _PyImport_AcquireLock();
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002905 mod = import_module_level(name, globals, locals, fromlist, level);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 if (_PyImport_ReleaseLock() < 0) {
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002907 Py_XDECREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 PyErr_SetString(PyExc_RuntimeError,
2909 "not holding the import lock");
2910 return NULL;
2911 }
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002912 return mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002913}
2914
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002915PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002916PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002917 PyObject *fromlist, int level)
2918{
2919 PyObject *nameobj, *mod;
2920 nameobj = PyUnicode_FromString(name);
2921 if (nameobj == NULL)
2922 return NULL;
2923 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2924 fromlist, level);
2925 Py_DECREF(nameobj);
2926 return mod;
2927}
2928
2929
Fred Drake87590902004-05-28 20:21:36 +00002930/* Return the package that an import is being performed in. If globals comes
2931 from the module foo.bar.bat (not itself a package), this returns the
2932 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002933 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002934
Victor Stinner974389d2011-03-15 09:33:57 +01002935 The name of the returned package is returned in *p_name.
Fred Drake87590902004-05-28 20:21:36 +00002936
2937 If globals doesn't come from a package or a module in a package, or a
2938 corresponding entry is not found in sys.modules, Py_None is returned.
2939*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002940static PyObject *
Victor Stinner9599de52011-03-13 22:38:38 -04002941get_parent(PyObject *globals, PyObject **p_name, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002942{
Victor Stinner974389d2011-03-15 09:33:57 +01002943 PyObject *nameobj;
2944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 static PyObject *namestr = NULL;
2946 static PyObject *pathstr = NULL;
2947 static PyObject *pkgstr = NULL;
2948 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2949 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 if (globals == NULL || !PyDict_Check(globals) || !level)
Victor Stinner974389d2011-03-15 09:33:57 +01002952 goto return_none;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 if (namestr == NULL) {
2955 namestr = PyUnicode_InternFromString("__name__");
2956 if (namestr == NULL)
2957 return NULL;
2958 }
2959 if (pathstr == NULL) {
2960 pathstr = PyUnicode_InternFromString("__path__");
2961 if (pathstr == NULL)
2962 return NULL;
2963 }
2964 if (pkgstr == NULL) {
2965 pkgstr = PyUnicode_InternFromString("__package__");
2966 if (pkgstr == NULL)
2967 return NULL;
2968 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 if ((pkgname != NULL) && (pkgname != Py_None)) {
2973 /* __package__ is set, so use it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 if (!PyUnicode_Check(pkgname)) {
2975 PyErr_SetString(PyExc_ValueError,
2976 "__package__ set to non-string");
2977 return NULL;
2978 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002979 if (PyUnicode_GET_LENGTH(pkgname) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 if (level > 0) {
2981 PyErr_SetString(PyExc_ValueError,
2982 "Attempted relative import in non-package");
2983 return NULL;
2984 }
Victor Stinner974389d2011-03-15 09:33:57 +01002985 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002987 Py_INCREF(pkgname);
2988 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 } else {
2990 /* __package__ not set, so figure it out and set it */
2991 modname = PyDict_GetItem(globals, namestr);
2992 if (modname == NULL || !PyUnicode_Check(modname))
Victor Stinner974389d2011-03-15 09:33:57 +01002993 goto return_none;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 modpath = PyDict_GetItem(globals, pathstr);
2996 if (modpath != NULL) {
2997 /* __path__ is set, so modname is already the package name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 error = PyDict_SetItem(globals, pkgstr, modname);
3001 if (error) {
3002 PyErr_SetString(PyExc_ValueError,
3003 "Could not set __package__");
3004 return NULL;
3005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003006 Py_INCREF(modname);
3007 nameobj = modname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 } else {
3009 /* Normal module, so work out the package name if any */
Victor Stinner974389d2011-03-15 09:33:57 +01003010 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003011 len = PyUnicode_FindChar(modname, '.',
3012 0, PyUnicode_GET_LENGTH(modname), -1);
3013 if (len == -2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003015 if (len < 0) {
3016 if (level > 0) {
3017 PyErr_SetString(PyExc_ValueError,
3018 "Attempted relative import in non-package");
3019 return NULL;
3020 }
3021 if (PyDict_SetItem(globals, pkgstr, Py_None)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 PyErr_SetString(PyExc_ValueError,
3023 "Could not set __package__");
3024 return NULL;
3025 }
Victor Stinner974389d2011-03-15 09:33:57 +01003026 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003028 pkgname = PyUnicode_Substring(modname, 0, len);
3029 if (pkgname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003031 if (PyDict_SetItem(globals, pkgstr, pkgname)) {
3032 Py_DECREF(pkgname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 PyErr_SetString(PyExc_ValueError,
3034 "Could not set __package__");
3035 return NULL;
3036 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003037 nameobj = pkgname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 }
3039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003040 if (level > 1) {
3041 Py_ssize_t dot, end = PyUnicode_GET_LENGTH(nameobj);
3042 PyObject *newname;
3043 while (--level > 0) {
3044 dot = PyUnicode_FindChar(nameobj, '.', 0, end, -1);
3045 if (dot == -2) {
3046 Py_DECREF(nameobj);
3047 return NULL;
3048 }
3049 if (dot < 0) {
3050 Py_DECREF(nameobj);
3051 PyErr_SetString(PyExc_ValueError,
3052 "Attempted relative import beyond "
3053 "toplevel package");
3054 return NULL;
3055 }
3056 end = dot;
3057 }
3058 newname = PyUnicode_Substring(nameobj, 0, end);
3059 Py_DECREF(nameobj);
3060 if (newname == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003062 nameobj = newname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 }
Victor Stinner974389d2011-03-15 09:33:57 +01003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003066 parent = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 if (parent == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003068 int err;
3069
3070 if (orig_level >= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 PyErr_Format(PyExc_SystemError,
Victor Stinner974389d2011-03-15 09:33:57 +01003072 "Parent module %R not loaded, "
3073 "cannot perform relative import", nameobj);
3074 Py_DECREF(nameobj);
3075 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 }
Victor Stinner974389d2011-03-15 09:33:57 +01003077
3078 err = PyErr_WarnFormat(
3079 PyExc_RuntimeWarning, 1,
3080 "Parent module %R not found while handling absolute import",
3081 nameobj);
3082 Py_DECREF(nameobj);
3083 if (err)
3084 return NULL;
3085
3086 goto return_none;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 }
Victor Stinner974389d2011-03-15 09:33:57 +01003088 *p_name = nameobj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 return parent;
3090 /* We expect, but can't guarantee, if parent != None, that:
Victor Stinner974389d2011-03-15 09:33:57 +01003091 - parent.__name__ == name
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 - parent.__dict__ is globals
3093 If this is violated... Who cares? */
Victor Stinner974389d2011-03-15 09:33:57 +01003094
3095return_none:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003096 nameobj = PyUnicode_New(0, 0);
Victor Stinner974389d2011-03-15 09:33:57 +01003097 if (nameobj == NULL)
3098 return NULL;
3099 *p_name = nameobj;
3100 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003101}
3102
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003103/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003104static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003105load_next(PyObject *mod, PyObject *altmod,
3106 PyObject *inputname, PyObject **p_outputname,
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003107 PyObject **p_prefix)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003108{
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003109 Py_ssize_t dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003110 Py_ssize_t len;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003111 PyObject *fullname, *name = NULL, *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003112
Victor Stinner974389d2011-03-15 09:33:57 +01003113 *p_outputname = NULL;
3114
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003115 len = PyUnicode_GET_LENGTH(inputname);
3116 if (len == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 /* completely empty module name should only happen in
3118 'from . import' (or '__import__("")')*/
3119 Py_INCREF(mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 return mod;
3121 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003122
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003123
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003124 dot = PyUnicode_FindChar(inputname, '.', 0, len, 1);
3125 if (dot >= 0) {
3126 len = dot;
Victor Stinner974389d2011-03-15 09:33:57 +01003127 if (len == 0) {
3128 PyErr_SetString(PyExc_ValueError,
3129 "Empty module name");
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003130 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003131 }
3132 }
Victor Stinner974389d2011-03-15 09:33:57 +01003133
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003134 /* name = inputname[:len] */
3135 name = PyUnicode_Substring(inputname, 0, len);
3136 if (name == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003137 goto error;
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003138
3139 if (PyUnicode_GET_LENGTH(*p_prefix)) {
3140 /* fullname = prefix + "." + name */
3141 fullname = PyUnicode_FromFormat("%U.%U", *p_prefix, name);
3142 if (fullname == NULL)
3143 goto error;
3144 }
3145 else {
3146 fullname = name;
3147 Py_INCREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003149
Victor Stinner974389d2011-03-15 09:33:57 +01003150 result = import_submodule(mod, name, fullname);
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003151 Py_DECREF(*p_prefix);
3152 /* Transfer reference. */
3153 *p_prefix = fullname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 if (result == Py_None && altmod != mod) {
3155 Py_DECREF(result);
3156 /* Here, altmod must be None and mod must not be None */
Victor Stinner974389d2011-03-15 09:33:57 +01003157 result = import_submodule(altmod, name, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 if (result != NULL && result != Py_None) {
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003159 if (mark_miss(*p_prefix) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003161 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 }
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003163 Py_DECREF(*p_prefix);
3164 *p_prefix = name;
3165 Py_INCREF(*p_prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 }
3167 }
3168 if (result == NULL)
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003169 goto error;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 if (result == Py_None) {
3172 Py_DECREF(result);
3173 PyErr_Format(PyExc_ImportError,
Victor Stinner974389d2011-03-15 09:33:57 +01003174 "No module named %R", inputname);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003175 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003177
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003178 if (dot >= 0) {
3179 *p_outputname = PyUnicode_Substring(inputname, dot+1,
3180 PyUnicode_GET_LENGTH(inputname));
Victor Stinner974389d2011-03-15 09:33:57 +01003181 if (*p_outputname == NULL) {
3182 Py_DECREF(result);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003183 goto error;
Victor Stinner974389d2011-03-15 09:33:57 +01003184 }
3185 }
3186
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003187 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 return result;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003189
3190error:
Martin v. Löwisf45dee92011-10-30 23:50:02 +01003191 Py_XDECREF(name);
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02003192 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003193}
3194
3195static int
Victor Stinner974389d2011-03-15 09:33:57 +01003196mark_miss(PyObject *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner974389d2011-03-15 09:33:57 +01003199 return PyDict_SetItem(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00003200}
3201
3202static int
Victor Stinner974389d2011-03-15 09:33:57 +01003203ensure_fromlist(PyObject *mod, PyObject *fromlist, PyObject *name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 int i;
Victor Stinner974389d2011-03-15 09:33:57 +01003207 PyObject *fullname;
3208 Py_ssize_t fromlist_len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003209
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003210 if (!_PyObject_HasAttrId(mod, &PyId___path__))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003212
Victor Stinner974389d2011-03-15 09:33:57 +01003213 fromlist_len = PySequence_Size(fromlist);
3214
3215 for (i = 0; i < fromlist_len; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 PyObject *item = PySequence_GetItem(fromlist, i);
3217 int hasit;
Victor Stinner974389d2011-03-15 09:33:57 +01003218 if (item == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 if (!PyUnicode_Check(item)) {
3221 PyErr_SetString(PyExc_TypeError,
3222 "Item in ``from list'' not a string");
3223 Py_DECREF(item);
3224 return 0;
3225 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003226 if (PyUnicode_READ_CHAR(item, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 PyObject *all;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003228 _Py_IDENTIFIER(__all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 Py_DECREF(item);
3230 /* See if the package defines __all__ */
3231 if (recursive)
3232 continue; /* Avoid endless recursion */
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003233 all = _PyObject_GetAttrId(mod, &PyId___all__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 if (all == NULL)
3235 PyErr_Clear();
3236 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003237 int ret = ensure_fromlist(mod, all, name, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 Py_DECREF(all);
3239 if (!ret)
3240 return 0;
3241 }
3242 continue;
3243 }
3244 hasit = PyObject_HasAttr(mod, item);
3245 if (!hasit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 PyObject *submod;
Victor Stinner974389d2011-03-15 09:33:57 +01003247 fullname = PyUnicode_FromFormat("%U.%U", name, item);
3248 if (fullname != NULL) {
3249 submod = import_submodule(mod, item, fullname);
3250 Py_DECREF(fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 }
Victor Stinner974389d2011-03-15 09:33:57 +01003252 else
3253 submod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 Py_XDECREF(submod);
3255 if (submod == NULL) {
3256 Py_DECREF(item);
3257 return 0;
3258 }
3259 }
3260 Py_DECREF(item);
3261 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003262
Victor Stinner974389d2011-03-15 09:33:57 +01003263 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003264}
3265
Neil Schemenauer00b09662003-06-16 21:03:07 +00003266static int
Victor Stinner974389d2011-03-15 09:33:57 +01003267add_submodule(PyObject *mod, PyObject *submod, PyObject *fullname,
3268 PyObject *subname, PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00003269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (mod == Py_None)
3271 return 1;
3272 /* Irrespective of the success of this load, make a
3273 reference to it in the parent package module. A copy gets
3274 saved in the modules dictionary under the full name, so get a
3275 reference from there, if need be. (The exception is when the
3276 load failed with a SyntaxError -- then there's no trace in
3277 sys.modules. In that case, of course, do nothing extra.) */
3278 if (submod == NULL) {
Victor Stinner974389d2011-03-15 09:33:57 +01003279 submod = PyDict_GetItem(modules, fullname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 if (submod == NULL)
3281 return 1;
3282 }
3283 if (PyModule_Check(mod)) {
3284 /* We can't use setattr here since it can give a
3285 * spurious warning if the submodule name shadows a
3286 * builtin name */
3287 PyObject *dict = PyModule_GetDict(mod);
3288 if (!dict)
3289 return 0;
Victor Stinner974389d2011-03-15 09:33:57 +01003290 if (PyDict_SetItem(dict, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 return 0;
3292 }
3293 else {
Victor Stinner974389d2011-03-15 09:33:57 +01003294 if (PyObject_SetAttr(mod, subname, submod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 return 0;
3296 }
3297 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00003298}
3299
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003300static PyObject *
Victor Stinner974389d2011-03-15 09:33:57 +01003301import_submodule(PyObject *mod, PyObject *subname, PyObject *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003304 PyObject *m = NULL, *bufobj, *path_list, *loader;
Victor Stinner9599de52011-03-13 22:38:38 -04003305 struct filedescr *fdp;
3306 FILE *fp;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 /* Require:
3309 if mod == None: subname == fullname
3310 else: mod.__name__ + "." + subname == fullname
3311 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003312
Victor Stinner974389d2011-03-15 09:33:57 +01003313 if ((m = PyDict_GetItem(modules, fullname)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 Py_INCREF(m);
Victor Stinner9599de52011-03-13 22:38:38 -04003315 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 }
Victor Stinner9599de52011-03-13 22:38:38 -04003317
3318 if (mod == Py_None)
Victor Stinner533d7832011-03-14 13:22:54 -04003319 path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 else {
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003321 path_list = _PyObject_GetAttrId(mod, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003322 if (path_list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 PyErr_Clear();
3324 Py_INCREF(Py_None);
3325 return Py_None;
3326 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003328
Victor Stinner533d7832011-03-14 13:22:54 -04003329 fdp = find_module(fullname, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003330 &bufobj, &fp, &loader);
Victor Stinner533d7832011-03-14 13:22:54 -04003331 Py_XDECREF(path_list);
Victor Stinner9599de52011-03-13 22:38:38 -04003332 if (fdp == NULL) {
3333 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3334 return NULL;
3335 PyErr_Clear();
3336 Py_INCREF(Py_None);
3337 return Py_None;
3338 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003339 m = load_module(fullname, fp, bufobj, fdp->type, loader);
3340 Py_XDECREF(bufobj);
Victor Stinner9599de52011-03-13 22:38:38 -04003341 Py_XDECREF(loader);
3342 if (fp)
3343 fclose(fp);
3344 if (m == NULL)
3345 return NULL;
3346 if (!add_submodule(mod, m, fullname, subname, modules)) {
3347 Py_XDECREF(m);
3348 return NULL;
3349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003351}
3352
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003353
3354/* Re-import a module of any kind and return its module object, WITH
3355 INCREMENTED REFERENCE COUNT */
3356
Guido van Rossum79f25d91997-04-29 20:08:16 +00003357PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003358PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 PyInterpreterState *interp = PyThreadState_Get()->interp;
3361 PyObject *modules_reloading = interp->modules_reloading;
3362 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner533d7832011-03-14 13:22:54 -04003363 PyObject *path_list = NULL, *loader = NULL, *existing_m = NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003364 PyObject *name, *bufobj, *subname;
3365 Py_ssize_t subname_start;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 struct filedescr *fdp;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003367 FILE *fp = NULL;
3368 PyObject *newm = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 if (modules_reloading == NULL) {
3371 Py_FatalError("PyImport_ReloadModule: "
3372 "no modules_reloading dictionary!");
3373 return NULL;
3374 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 if (m == NULL || !PyModule_Check(m)) {
3377 PyErr_SetString(PyExc_TypeError,
3378 "reload() argument must be module");
3379 return NULL;
3380 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003381 name = PyModule_GetNameObject(m);
3382 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003384 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003386 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01003387 name);
3388 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 return NULL;
3390 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003391 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 if (existing_m != NULL) {
3393 /* Due to a recursive reload, this module is already
3394 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003395 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 Py_INCREF(existing_m);
3397 return existing_m;
3398 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003399 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
3400 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003402 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003403
Martin v. Löwis796ea532011-10-30 09:07:07 +01003404 subname_start = PyUnicode_FindChar(name, '.', 0,
3405 PyUnicode_GET_LENGTH(name), -1);
3406 if (subname_start == -1) {
3407 Py_INCREF(name);
3408 subname = name;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 else {
3411 PyObject *parentname, *parent;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003412 Py_ssize_t len;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003413 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003415 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 }
3417 parent = PyDict_GetItem(modules, parentname);
3418 if (parent == NULL) {
3419 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003420 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 parentname);
3422 Py_DECREF(parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003423 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 }
3425 Py_DECREF(parentname);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003426 path_list = _PyObject_GetAttrId(parent, &PyId___path__);
Victor Stinner533d7832011-03-14 13:22:54 -04003427 if (path_list == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 PyErr_Clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003429 subname_start++;
3430 len = PyUnicode_GET_LENGTH(name) - (subname_start + 1);
3431 subname = PyUnicode_Substring(name, subname_start, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003433 if (subname == NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003434 goto error;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003435 fdp = find_module(name, subname, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003436 &bufobj, &fp, &loader);
Martin v. Löwis796ea532011-10-30 09:07:07 +01003437 Py_DECREF(subname);
Victor Stinner533d7832011-03-14 13:22:54 -04003438 Py_XDECREF(path_list);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 if (fdp == NULL) {
3441 Py_XDECREF(loader);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003442 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003444
Martin v. Löwis796ea532011-10-30 09:07:07 +01003445 newm = load_module(name, fp, bufobj, fdp->type, loader);
Victor Stinner2fd76e42011-03-14 15:19:39 -04003446 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 if (fp)
3450 fclose(fp);
3451 if (newm == NULL) {
3452 /* load_module probably removed name from modules because of
3453 * the error. Put back the original module object. We're
3454 * going to return NULL in this case regardless of whether
3455 * replacing name succeeds, so the return value is ignored.
3456 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003457 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003459
3460error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003462 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003464}
3465
3466
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003467/* Higher-level import emulator which emulates the "import" statement
3468 more accurately -- it invokes the __import__() function from the
3469 builtins of the current globals. This means that the import is
3470 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003471 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003472 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003473 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003474 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003475
3476PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003477PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 static PyObject *silly_list = NULL;
3480 static PyObject *builtins_str = NULL;
3481 static PyObject *import_str = NULL;
3482 PyObject *globals = NULL;
3483 PyObject *import = NULL;
3484 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003485 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 /* Initialize constant string objects */
3489 if (silly_list == NULL) {
3490 import_str = PyUnicode_InternFromString("__import__");
3491 if (import_str == NULL)
3492 return NULL;
3493 builtins_str = PyUnicode_InternFromString("__builtins__");
3494 if (builtins_str == NULL)
3495 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003496 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 if (silly_list == NULL)
3498 return NULL;
3499 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 /* Get the builtins from current globals */
3502 globals = PyEval_GetGlobals();
3503 if (globals != NULL) {
3504 Py_INCREF(globals);
3505 builtins = PyObject_GetItem(globals, builtins_str);
3506 if (builtins == NULL)
3507 goto err;
3508 }
3509 else {
3510 /* No globals -- use standard builtins, and fake globals */
3511 builtins = PyImport_ImportModuleLevel("builtins",
3512 NULL, NULL, NULL, 0);
3513 if (builtins == NULL)
3514 return NULL;
3515 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3516 if (globals == NULL)
3517 goto err;
3518 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 /* Get the __import__ function from the builtins */
3521 if (PyDict_Check(builtins)) {
3522 import = PyObject_GetItem(builtins, import_str);
3523 if (import == NULL)
3524 PyErr_SetObject(PyExc_KeyError, import_str);
3525 }
3526 else
3527 import = PyObject_GetAttr(builtins, import_str);
3528 if (import == NULL)
3529 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003532 Always use absolute import here.
3533 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3535 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003536 if (r == NULL)
3537 goto err;
3538 Py_DECREF(r);
3539
3540 modules = PyImport_GetModuleDict();
3541 r = PyDict_GetItem(modules, module_name);
3542 if (r != NULL)
3543 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003544
3545 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 Py_XDECREF(globals);
3547 Py_XDECREF(builtins);
3548 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003551}
3552
3553
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003554/* Module 'imp' provides Python access to the primitives used for
3555 importing modules.
3556*/
3557
Guido van Rossum79f25d91997-04-29 20:08:16 +00003558static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003559imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 buf[0] = (char) ((magic >> 0) & 0xff);
3564 buf[1] = (char) ((magic >> 8) & 0xff);
3565 buf[2] = (char) ((magic >> 16) & 0xff);
3566 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003569}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003570
3571static PyObject *
3572imp_get_magic(PyObject *self, PyObject *noargs)
3573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003575}
3576
3577static PyObject *
3578imp_get_tag(PyObject *self, PyObject *noargs)
3579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003581}
3582
Guido van Rossum79f25d91997-04-29 20:08:16 +00003583static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003584imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 PyObject *list;
3587 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 list = PyList_New(0);
3590 if (list == NULL)
3591 return NULL;
3592 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3593 PyObject *item = Py_BuildValue("ssi",
3594 fdp->suffix, fdp->mode, fdp->type);
3595 if (item == NULL) {
3596 Py_DECREF(list);
3597 return NULL;
3598 }
3599 if (PyList_Append(list, item) < 0) {
3600 Py_DECREF(list);
3601 Py_DECREF(item);
3602 return NULL;
3603 }
3604 Py_DECREF(item);
3605 }
3606 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003607}
3608
Guido van Rossum79f25d91997-04-29 20:08:16 +00003609static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003610call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 extern int fclose(FILE *);
3613 PyObject *fob, *ret;
3614 PyObject *pathobj;
3615 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003616 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 int fd = -1;
3618 char *found_encoding = NULL;
3619 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003620
Victor Stinner533d7832011-03-14 13:22:54 -04003621 if (path_list == Py_None)
3622 path_list = NULL;
3623 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003624 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 if (fdp == NULL)
3626 return NULL;
3627 if (fp != NULL) {
3628 fd = fileno(fp);
3629 if (fd != -1)
3630 fd = dup(fd);
3631 fclose(fp);
3632 fp = NULL;
Antoine Pitrou72146122012-02-22 18:03:04 +01003633 if (fd == -1)
3634 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 }
3636 if (fd != -1) {
3637 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003638 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003640 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003642 if (found_encoding == NULL && PyErr_Occurred()) {
3643 Py_XDECREF(pathobj);
Antoine Pitrou4f22a8d2012-02-22 18:05:43 +01003644 close(fd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 encoding = (found_encoding != NULL) ? found_encoding :
3648 (char*)PyUnicode_GetDefaultEncoding();
3649 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003650 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 (char*)encoding, NULL, NULL, 1);
3652 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003653 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 close(fd);
3655 PyMem_FREE(found_encoding);
3656 return NULL;
3657 }
3658 }
3659 else {
3660 fob = Py_None;
3661 Py_INCREF(fob);
3662 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003663 if (pathobj == NULL) {
3664 Py_INCREF(Py_None);
3665 pathobj = Py_None;
3666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 ret = Py_BuildValue("NN(ssi)",
3668 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3669 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003672}
3673
Guido van Rossum79f25d91997-04-29 20:08:16 +00003674static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003675imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003676{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003677 PyObject *name, *path_list = NULL;
3678 if (!PyArg_ParseTuple(args, "U|O:find_module",
3679 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003681 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003682}
3683
3684static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003685imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003686{
Victor Stinner95872862011-03-07 18:20:56 +01003687 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 int ret;
3689 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003690 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 return NULL;
3692 ret = init_builtin(name);
3693 if (ret < 0)
3694 return NULL;
3695 if (ret == 0) {
3696 Py_INCREF(Py_None);
3697 return Py_None;
3698 }
Victor Stinner95872862011-03-07 18:20:56 +01003699 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 Py_XINCREF(m);
3701 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003702}
3703
Guido van Rossum79f25d91997-04-29 20:08:16 +00003704static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003705imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003706{
Victor Stinner53dc7352011-03-20 01:50:21 +01003707 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 int ret;
3709 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003710 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003712 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 if (ret < 0)
3714 return NULL;
3715 if (ret == 0) {
3716 Py_INCREF(Py_None);
3717 return Py_None;
3718 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003719 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 Py_XINCREF(m);
3721 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003722}
3723
Guido van Rossum79f25d91997-04-29 20:08:16 +00003724static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003725imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003726{
Victor Stinner53dc7352011-03-20 01:50:21 +01003727 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003728
Victor Stinner53dc7352011-03-20 01:50:21 +01003729 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 return NULL;
3731 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003732}
3733
Guido van Rossum79f25d91997-04-29 20:08:16 +00003734static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003735imp_is_frozen_package(PyObject *self, PyObject *args)
3736{
Victor Stinner53dc7352011-03-20 01:50:21 +01003737 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003738
Victor Stinner53dc7352011-03-20 01:50:21 +01003739 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 return NULL;
3741 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003742}
3743
3744static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003745imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003746{
Victor Stinner95872862011-03-07 18:20:56 +01003747 PyObject *name;
3748 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 return NULL;
3750 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003751}
3752
Guido van Rossum79f25d91997-04-29 20:08:16 +00003753static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003754imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003755{
Victor Stinner53dc7352011-03-20 01:50:21 +01003756 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003758 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003759 return NULL;
3760 p = find_frozen(name);
3761 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003762}
3763
3764static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003765get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 FILE *fp;
3768 if (mode[0] == 'U')
3769 mode = "r" PY_STDIOTEXTMODE;
3770 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003771 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003772 if (!fp) {
3773 if (!PyErr_Occurred())
3774 PyErr_SetFromErrno(PyExc_IOError);
3775 return NULL;
3776 }
3777 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 }
3779 else {
3780 int fd = PyObject_AsFileDescriptor(fob);
3781 if (fd == -1)
3782 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01003783 if (!_PyVerify_fd(fd)) {
3784 PyErr_SetFromErrno(PyExc_IOError);
3785 return NULL;
3786 }
3787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 /* the FILE struct gets a new fd, so that it can be closed
3789 * independently of the file descriptor given
3790 */
3791 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01003792 if (fd == -1) {
3793 PyErr_SetFromErrno(PyExc_IOError);
3794 return NULL;
3795 }
3796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003798 if (!fp) {
3799 PyErr_SetFromErrno(PyExc_IOError);
3800 return NULL;
3801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003803 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003804}
3805
Guido van Rossum79f25d91997-04-29 20:08:16 +00003806static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003807imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003808{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003809 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 PyObject *fob = NULL;
3811 PyObject *m;
3812 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003813 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003815 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 &fob))
3817 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003818 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003820 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 return NULL;
3822 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003823 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003825 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003827}
3828
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003829#ifdef HAVE_DYNAMIC_LOADING
3830
Guido van Rossum79f25d91997-04-29 20:08:16 +00003831static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003832imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003833{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003834 PyObject *name, *pathname, *fob = NULL, *mod;
3835 FILE *fp;
3836
3837 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3838 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003840 if (fob != NULL) {
3841 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003842 if (fp == NULL) {
3843 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003845 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003847 else
3848 fp = NULL;
3849 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003850 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 if (fp)
3852 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003853 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003854}
3855
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003856#endif /* HAVE_DYNAMIC_LOADING */
3857
Guido van Rossum79f25d91997-04-29 20:08:16 +00003858static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003859imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003860{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003861 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 PyObject *fob = NULL;
3863 PyObject *m;
3864 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003865 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003867 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 &fob))
3869 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003870 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003872 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 return NULL;
3874 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003875 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003876 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 fclose(fp);
3878 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003879}
3880
Guido van Rossum79f25d91997-04-29 20:08:16 +00003881static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003882imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003883{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003884 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 char *suffix; /* Unused */
3886 char *mode;
3887 int type;
3888 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003889
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003890 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3891 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003893 if (pathname_obj != Py_None) {
3894 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3895 return NULL;
3896 }
3897 else
3898 pathname = NULL;
3899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 if (*mode) {
3901 /* Mode must start with 'r' or 'U' and must not contain '+'.
3902 Implicit in this test is the assumption that the mode
3903 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3906 PyErr_Format(PyExc_ValueError,
3907 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003908 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 return NULL;
3910 }
3911 }
3912 if (fob == Py_None)
3913 fp = NULL;
3914 else {
3915 fp = get_file(NULL, fob, mode);
3916 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003917 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 return NULL;
3919 }
3920 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003921 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003922 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 if (fp)
3924 fclose(fp);
3925 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003926}
3927
3928static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003929imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003930{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003931 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003933 if (!PyArg_ParseTuple(args, "UO&:load_package",
3934 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003936 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003937 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003939}
3940
3941static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003942imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003943{
Victor Stinnerfe19d212011-03-14 14:53:28 -04003944 PyObject *name;
3945 if (!PyArg_ParseTuple(args, "U:new_module", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 return NULL;
Victor Stinnerfe19d212011-03-14 14:53:28 -04003947 return PyModule_NewObject(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003948}
3949
Christian Heimes13a7a212008-01-07 17:13:09 +00003950static PyObject *
3951imp_reload(PyObject *self, PyObject *v)
3952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003954}
3955
3956PyDoc_STRVAR(doc_reload,
3957"reload(module) -> module\n\
3958\n\
3959Reload the module. The module must have been successfully imported before.");
3960
Barry Warsaw28a691b2010-04-17 00:19:56 +00003961static PyObject *
3962imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003965
Victor Stinner2f42ae52011-03-20 00:41:24 +01003966 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003967 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003971 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003972 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003974
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003975 if (debug_override != NULL &&
3976 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003977 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003978 return NULL;
3979 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003980
Martin v. Löwis30260a72011-10-23 17:35:46 +02003981 if (PyUnicode_READY(pathname) < 0)
3982 return NULL;
3983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003984 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003985 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 if (cpathname == NULL) {
3988 PyErr_Format(PyExc_SystemError, "path buffer too short");
3989 return NULL;
3990 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003991 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003992}
3993
3994PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01003995"cache_from_source(path, [debug_override]) -> path\n\
3996Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003997\n\
3998The .py file does not need to exist; this simply returns the path to the\n\
3999.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
4000will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
4001\n\
4002If debug_override is not None, then it must be a boolean and is taken as\n\
4003the value of __debug__ instead.");
4004
4005static PyObject *
4006imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
4007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04004009 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00004012 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04004013 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004015
Victor Stinnerc9abda02011-03-14 13:33:46 -04004016 source = make_source_pathname(pathname);
4017 if (source == NULL) {
4018 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04004020 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 return NULL;
4022 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04004023 Py_DECREF(pathname);
4024 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00004025}
4026
4027PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01004028"source_from_cache(path) -> path\n\
4029Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00004030\n\
4031The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
4032the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
4033does not conform to PEP 3147 format, ValueError will be raised.");
4034
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004035/* Doc strings */
4036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004037PyDoc_STRVAR(doc_imp,
4038"This module provides the components needed to build your own\n\
4039__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004041PyDoc_STRVAR(doc_find_module,
4042"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004043Search for a module. If path is omitted or None, search for a\n\
4044built-in, frozen or special module and continue search in sys.path.\n\
4045The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004046package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004048PyDoc_STRVAR(doc_load_module,
4049"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004050Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004051The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004053PyDoc_STRVAR(doc_get_magic,
4054"get_magic() -> string\n\
4055Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004056
Barry Warsaw28a691b2010-04-17 00:19:56 +00004057PyDoc_STRVAR(doc_get_tag,
4058"get_tag() -> string\n\
4059Return the magic tag for .pyc or .pyo files.");
4060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004061PyDoc_STRVAR(doc_get_suffixes,
4062"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004063Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004064that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004066PyDoc_STRVAR(doc_new_module,
4067"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004068Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004069The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00004070
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004071PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00004072"lock_held() -> boolean\n\
4073Return True if the import lock is currently held, else False.\n\
4074On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00004075
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004076PyDoc_STRVAR(doc_acquire_lock,
4077"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00004078Acquires the interpreter's import lock for the current thread.\n\
4079This lock should be used by import hooks to ensure thread-safety\n\
4080when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00004081On platforms without threads, this function does nothing.");
4082
4083PyDoc_STRVAR(doc_release_lock,
4084"release_lock() -> None\n\
4085Release the interpreter's import lock.\n\
4086On platforms without threads, this function does nothing.");
4087
Guido van Rossum79f25d91997-04-29 20:08:16 +00004088static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
4090 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
4091 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
4092 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
4093 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
4094 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
4095 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
4096 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
4097 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
4098 {"reload", imp_reload, METH_O, doc_reload},
4099 {"cache_from_source", (PyCFunction)imp_cache_from_source,
4100 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
4101 {"source_from_cache", (PyCFunction)imp_source_from_cache,
4102 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
4103 /* The rest are obsolete */
4104 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
4105 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
4106 {"init_builtin", imp_init_builtin, METH_VARARGS},
4107 {"init_frozen", imp_init_frozen, METH_VARARGS},
4108 {"is_builtin", imp_is_builtin, METH_VARARGS},
4109 {"is_frozen", imp_is_frozen, METH_VARARGS},
4110 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004111#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00004113#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 {"load_package", imp_load_package, METH_VARARGS},
4115 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07004116 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004118};
4119
Guido van Rossum1a8791e1998-08-04 22:46:29 +00004120static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004121setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 PyObject *v;
4124 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 v = PyLong_FromLong((long)value);
4127 err = PyDict_SetItemString(d, name, v);
4128 Py_XDECREF(v);
4129 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004130}
4131
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004132typedef struct {
4133 PyObject_HEAD
4134} NullImporter;
4135
4136static int
4137NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
4138{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004139#ifndef MS_WINDOWS
4140 PyObject *path;
4141 struct stat statbuf;
4142 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4145 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004146
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004147 if (!PyArg_ParseTuple(args, "O&:NullImporter",
4148 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004150
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004151 if (PyBytes_GET_SIZE(path) == 0) {
4152 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 PyErr_SetString(PyExc_ImportError, "empty pathname");
4154 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004156
4157 rv = stat(PyBytes_AS_STRING(path), &statbuf);
4158 Py_DECREF(path);
4159 if (rv == 0) {
4160 /* it exists */
4161 if (S_ISDIR(statbuf.st_mode)) {
4162 /* it's a directory */
4163 PyErr_SetString(PyExc_ImportError, "existing directory");
4164 return -1;
4165 }
4166 }
4167#else /* MS_WINDOWS */
4168 PyObject *pathobj;
4169 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00004170 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004171
4172 if (!_PyArg_NoKeywords("NullImporter()", kwds))
4173 return -1;
4174
4175 if (!PyArg_ParseTuple(args, "U:NullImporter",
4176 &pathobj))
4177 return -1;
4178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004179 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004180 PyErr_SetString(PyExc_ImportError, "empty pathname");
4181 return -1;
4182 }
4183
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00004184 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004185 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004186 return -1;
4187 /* see issue1293 and issue3677:
4188 * stat() on Windows doesn't recognise paths like
4189 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
4190 */
4191 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00004192 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00004193 if (rv != INVALID_FILE_ATTRIBUTES) {
4194 /* it exists */
4195 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
4196 /* it's a directory */
4197 PyErr_SetString(PyExc_ImportError, "existing directory");
4198 return -1;
4199 }
4200 }
4201#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004203}
4204
4205static PyObject *
4206NullImporter_find_module(NullImporter *self, PyObject *args)
4207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004209}
4210
4211static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
4213 "Always return None"
4214 },
4215 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004216};
4217
4218
Christian Heimes9cd17752007-11-18 19:35:23 +00004219PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 PyVarObject_HEAD_INIT(NULL, 0)
4221 "imp.NullImporter", /*tp_name*/
4222 sizeof(NullImporter), /*tp_basicsize*/
4223 0, /*tp_itemsize*/
4224 0, /*tp_dealloc*/
4225 0, /*tp_print*/
4226 0, /*tp_getattr*/
4227 0, /*tp_setattr*/
4228 0, /*tp_reserved*/
4229 0, /*tp_repr*/
4230 0, /*tp_as_number*/
4231 0, /*tp_as_sequence*/
4232 0, /*tp_as_mapping*/
4233 0, /*tp_hash */
4234 0, /*tp_call*/
4235 0, /*tp_str*/
4236 0, /*tp_getattro*/
4237 0, /*tp_setattro*/
4238 0, /*tp_as_buffer*/
4239 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4240 "Null importer object", /* tp_doc */
4241 0, /* tp_traverse */
4242 0, /* tp_clear */
4243 0, /* tp_richcompare */
4244 0, /* tp_weaklistoffset */
4245 0, /* tp_iter */
4246 0, /* tp_iternext */
4247 NullImporter_methods, /* tp_methods */
4248 0, /* tp_members */
4249 0, /* tp_getset */
4250 0, /* tp_base */
4251 0, /* tp_dict */
4252 0, /* tp_descr_get */
4253 0, /* tp_descr_set */
4254 0, /* tp_dictoffset */
4255 (initproc)NullImporter_init, /* tp_init */
4256 0, /* tp_alloc */
4257 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004258};
4259
Martin v. Löwis1a214512008-06-11 05:26:20 +00004260static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 PyModuleDef_HEAD_INIT,
4262 "imp",
4263 doc_imp,
4264 0,
4265 imp_methods,
4266 NULL,
4267 NULL,
4268 NULL,
4269 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004270};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004271
Jason Tishler6bc06ec2003-09-04 11:59:50 +00004272PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004273PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 if (PyType_Ready(&PyNullImporter_Type) < 0)
4278 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 m = PyModule_Create(&impmodule);
4281 if (m == NULL)
4282 goto failure;
4283 d = PyModule_GetDict(m);
4284 if (d == NULL)
4285 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
4288 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
4289 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
4290 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
4291 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
4292 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
4293 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4294 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4295 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4296 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 Py_INCREF(&PyNullImporter_Type);
4299 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4300 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004301 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 Py_XDECREF(m);
4303 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004304}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004305
4306
Guido van Rossumb18618d2000-05-03 23:44:39 +00004307/* API for embedding applications that want to add their own entries
4308 to the table of built-in modules. This should normally be called
4309 *before* Py_Initialize(). When the table resize fails, -1 is
4310 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004311
4312 After a similar function by Just van Rossum. */
4313
4314int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004315PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 static struct _inittab *our_copy = NULL;
4318 struct _inittab *p;
4319 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 /* Count the number of entries in both tables */
4322 for (n = 0; newtab[n].name != NULL; n++)
4323 ;
4324 if (n == 0)
4325 return 0; /* Nothing to do */
4326 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4327 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 /* Allocate new memory for the combined table */
4330 p = our_copy;
4331 PyMem_RESIZE(p, struct _inittab, i+n+1);
4332 if (p == NULL)
4333 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 /* Copy the tables into the new memory */
4336 if (our_copy != PyImport_Inittab)
4337 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4338 PyImport_Inittab = our_copy = p;
4339 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004342}
4343
4344/* Shorthand to add a single entry given a name and a function */
4345
4346int
Brett Cannona826f322009-04-02 03:41:46 +00004347PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 newtab[0].name = (char *)name;
4354 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004357}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004358
4359#ifdef __cplusplus
4360}
4361#endif