blob: f3de7d826278134ba9f59f21e6ff7fb94651ad8a [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 Petersonabdb5522012-03-15 15:40:37 -0500107 3210 (added size modulo 2**32 to the pyc header)
108 Python 3.3a1 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)
Benjamin Petersonf53d20f2012-03-16 09:39:12 -0500121#define MAGIC (3220 | ((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;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000157/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158
159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 const struct filedescr *scan;
163 struct filedescr *filetab;
164 int countD = 0;
165 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000166
Victor Stinnerd0296212011-03-14 14:04:10 -0400167 initstr = PyUnicode_InternFromString("__init__");
168 if (initstr == NULL)
169 Py_FatalError("Can't initialize import variables");
170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* prepare _PyImport_Filetab: copy entries from
172 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
173 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000174#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
176 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
179 ++countS;
180 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
181 if (filetab == NULL)
182 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000183#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 memcpy(filetab, _PyImport_DynLoadFiletab,
185 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000186#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 memcpy(filetab + countD, _PyImport_StandardFiletab,
188 countS * sizeof(struct filedescr));
189 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (Py_OptimizeFlag) {
194 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
195 for (; filetab->suffix != NULL; filetab++) {
196 if (strcmp(filetab->suffix, ".pyc") == 0)
197 filetab->suffix = ".pyo";
198 }
199 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202void
Just van Rossum52e14d62002-12-30 22:08:05 +0000203_PyImportHooks_Init(void)
204{
Brett Cannonfd074152012-04-14 14:10:13 -0400205 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (PyType_Ready(&PyNullImporter_Type) < 0)
209 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000210
Brett Cannonfd074152012-04-14 14:10:13 -0400211 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 v = PyList_New(0);
213 if (v == NULL)
214 goto error;
215 err = PySys_SetObject("meta_path", v);
216 Py_DECREF(v);
217 if (err)
218 goto error;
219 v = PyDict_New();
220 if (v == NULL)
221 goto error;
222 err = PySys_SetObject("path_importer_cache", v);
223 Py_DECREF(v);
224 if (err)
225 goto error;
226 path_hooks = PyList_New(0);
227 if (path_hooks == NULL)
228 goto error;
229 err = PySys_SetObject("path_hooks", path_hooks);
230 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000231 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400232 PyErr_Print();
233 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
234 "path_importer_cache, or NullImporter failed"
235 );
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 }
Brett Cannonfd074152012-04-14 14:10:13 -0400237 Py_DECREF(path_hooks);
238}
239
240void
241_PyImportZip_Init(void)
242{
243 PyObject *path_hooks, *zimpimport;
244 int err = 0;
245
246 path_hooks = PySys_GetObject("path_hooks");
247 if (path_hooks == NULL)
248 goto error;
249
250 if (Py_VerboseFlag)
251 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 zimpimport = PyImport_ImportModule("zipimport");
254 if (zimpimport == NULL) {
255 PyErr_Clear(); /* No zip import module -- okay */
256 if (Py_VerboseFlag)
257 PySys_WriteStderr("# can't import zipimport\n");
258 }
259 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200260 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200261 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
262 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_DECREF(zimpimport);
264 if (zipimporter == NULL) {
265 PyErr_Clear(); /* No zipimporter object -- okay */
266 if (Py_VerboseFlag)
267 PySys_WriteStderr(
268 "# can't import zipimport.zipimporter\n");
269 }
270 else {
271 /* sys.path_hooks.append(zipimporter) */
272 err = PyList_Append(path_hooks, zipimporter);
273 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400274 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (Py_VerboseFlag)
278 PySys_WriteStderr(
279 "# installed zipimport hook\n");
280 }
281 }
Brett Cannonfd074152012-04-14 14:10:13 -0400282
283 return;
284
285 error:
286 PyErr_Print();
287 Py_FatalError("initializing zipimport or NullImporter failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000288}
289
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290/* Locking primitives to prevent parallel imports of the same module
291 in different threads to return with a partially loaded module.
292 These calls are serialized by the global interpreter lock. */
293
294#ifdef WITH_THREAD
295
Guido van Rossum49b56061998-10-01 20:42:43 +0000296#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297
Guido van Rossum65d5b571998-12-21 19:32:43 +0000298static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000299static long import_lock_thread = -1;
300static int import_lock_level = 0;
301
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000302void
303_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 long me = PyThread_get_thread_ident();
306 if (me == -1)
307 return; /* Too bad */
308 if (import_lock == NULL) {
309 import_lock = PyThread_allocate_lock();
310 if (import_lock == NULL)
311 return; /* Nothing much we can do. */
312 }
313 if (import_lock_thread == me) {
314 import_lock_level++;
315 return;
316 }
317 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
318 {
319 PyThreadState *tstate = PyEval_SaveThread();
320 PyThread_acquire_lock(import_lock, 1);
321 PyEval_RestoreThread(tstate);
322 }
323 import_lock_thread = me;
324 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000325}
326
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000327int
328_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 long me = PyThread_get_thread_ident();
331 if (me == -1 || import_lock == NULL)
332 return 0; /* Too bad */
333 if (import_lock_thread != me)
334 return -1;
335 import_lock_level--;
336 if (import_lock_level == 0) {
337 import_lock_thread = -1;
338 PyThread_release_lock(import_lock);
339 }
340 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000341}
342
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000343/* This function is called from PyOS_AfterFork to ensure that newly
344 created child processes do not share locks with the parent.
345 We now acquire the import lock around fork() calls but on some platforms
346 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000347
348void
349_PyImport_ReInitLock(void)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (import_lock != NULL)
352 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000353 if (import_lock_level > 1) {
354 /* Forked as a side effect of import */
355 long me = PyThread_get_thread_ident();
356 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100357 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000358 import_lock_thread = me;
359 import_lock_level--;
360 } else {
361 import_lock_thread = -1;
362 import_lock_level = 0;
363 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000364}
365
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000366#endif
367
Tim Peters69232342001-08-30 05:16:13 +0000368static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000369imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000370{
Tim Peters69232342001-08-30 05:16:13 +0000371#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000373#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000375#endif
376}
377
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000378static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000379imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000380{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000381#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000383#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_INCREF(Py_None);
385 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000386}
387
388static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000389imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000390{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000391#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (_PyImport_ReleaseLock() < 0) {
393 PyErr_SetString(PyExc_RuntimeError,
394 "not holding the import lock");
395 return NULL;
396 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 Py_INCREF(Py_None);
399 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000400}
401
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100402void
403_PyImport_Fini(void)
404{
405 Py_XDECREF(extensions);
406 extensions = NULL;
407 PyMem_DEL(_PyImport_Filetab);
408 _PyImport_Filetab = NULL;
409#ifdef WITH_THREAD
410 if (import_lock != NULL) {
411 PyThread_free_lock(import_lock);
412 import_lock = NULL;
413 }
414#endif
415}
416
Guido van Rossumd8faa362007-04-27 19:54:29 +0000417static void
418imp_modules_reloading_clear(void)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyInterpreterState *interp = PyThreadState_Get()->interp;
421 if (interp->modules_reloading != NULL)
422 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423}
424
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425/* Helper for sys */
426
427PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000428PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyInterpreterState *interp = PyThreadState_GET()->interp;
431 if (interp->modules == NULL)
432 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
433 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000434}
435
Guido van Rossum3f5da241990-12-20 15:06:42 +0000436
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437/* List of names to clear in sys */
438static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 "path", "argv", "ps1", "ps2",
440 "last_type", "last_value", "last_traceback",
441 "path_hooks", "path_importer_cache", "meta_path",
442 /* misc stuff */
443 "flags", "float_info",
444 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000445};
446
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000447static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 "stdin", "__stdin__",
449 "stdout", "__stdout__",
450 "stderr", "__stderr__",
451 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000452};
453
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000454
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000455/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000456
Guido van Rossum3f5da241990-12-20 15:06:42 +0000457void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000458PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyObject *key, *value, *dict;
462 PyInterpreterState *interp = PyThreadState_GET()->interp;
463 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (modules == NULL)
466 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* Delete some special variables first. These are common
469 places where user values hide and people complain when their
470 destructors fail. Since the modules containing them are
471 deleted *last* of all, they would come too late in the normal
472 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 value = PyDict_GetItemString(modules, "builtins");
475 if (value != NULL && PyModule_Check(value)) {
476 dict = PyModule_GetDict(value);
477 if (Py_VerboseFlag)
478 PySys_WriteStderr("# clear builtins._\n");
479 PyDict_SetItemString(dict, "_", Py_None);
480 }
481 value = PyDict_GetItemString(modules, "sys");
482 if (value != NULL && PyModule_Check(value)) {
483 char **p;
484 PyObject *v;
485 dict = PyModule_GetDict(value);
486 for (p = sys_deletes; *p != NULL; p++) {
487 if (Py_VerboseFlag)
488 PySys_WriteStderr("# clear sys.%s\n", *p);
489 PyDict_SetItemString(dict, *p, Py_None);
490 }
491 for (p = sys_files; *p != NULL; p+=2) {
492 if (Py_VerboseFlag)
493 PySys_WriteStderr("# restore sys.%s\n", *p);
494 v = PyDict_GetItemString(dict, *(p+1));
495 if (v == NULL)
496 v = Py_None;
497 PyDict_SetItemString(dict, *p, v);
498 }
499 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* First, delete __main__ */
502 value = PyDict_GetItemString(modules, "__main__");
503 if (value != NULL && PyModule_Check(value)) {
504 if (Py_VerboseFlag)
505 PySys_WriteStderr("# cleanup __main__\n");
506 _PyModule_Clear(value);
507 PyDict_SetItemString(modules, "__main__", Py_None);
508 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* The special treatment of "builtins" here is because even
511 when it's not referenced as a module, its dictionary is
512 referenced by almost every module's __builtins__. Since
513 deleting a module clears its dictionary (even if there are
514 references left to it), we need to delete the "builtins"
515 module last. Likewise, we don't delete sys until the very
516 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Also note that we 'delete' modules by replacing their entry
519 in the modules dict with None, rather than really deleting
520 them; this avoids a rehash of the modules dictionary and
521 also marks them as "non existent" so they won't be
522 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Next, repeatedly delete modules with a reference count of
525 one (skipping builtins and sys) and delete them */
526 do {
527 ndone = 0;
528 pos = 0;
529 while (PyDict_Next(modules, &pos, &key, &value)) {
530 if (value->ob_refcnt != 1)
531 continue;
532 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100533 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100535 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 continue;
537 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100538 PySys_FormatStderr(
539 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 _PyModule_Clear(value);
541 PyDict_SetItem(modules, key, Py_None);
542 ndone++;
543 }
544 }
545 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* Next, delete all modules (still skipping builtins and sys) */
548 pos = 0;
549 while (PyDict_Next(modules, &pos, &key, &value)) {
550 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100551 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100553 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 continue;
555 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100556 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 _PyModule_Clear(value);
558 PyDict_SetItem(modules, key, Py_None);
559 }
560 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* Next, delete sys and builtins (in that order) */
563 value = PyDict_GetItemString(modules, "sys");
564 if (value != NULL && PyModule_Check(value)) {
565 if (Py_VerboseFlag)
566 PySys_WriteStderr("# cleanup sys\n");
567 _PyModule_Clear(value);
568 PyDict_SetItemString(modules, "sys", Py_None);
569 }
570 value = PyDict_GetItemString(modules, "builtins");
571 if (value != NULL && PyModule_Check(value)) {
572 if (Py_VerboseFlag)
573 PySys_WriteStderr("# cleanup builtins\n");
574 _PyModule_Clear(value);
575 PyDict_SetItemString(modules, "builtins", Py_None);
576 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Finally, clear and delete the modules directory */
579 PyDict_Clear(modules);
580 interp->modules = NULL;
581 Py_DECREF(modules);
582 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000583}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000584
585
Barry Warsaw28a691b2010-04-17 00:19:56 +0000586/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
588long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000589PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000592}
593
594
Barry Warsaw28a691b2010-04-17 00:19:56 +0000595const char *
596PyImport_GetMagicTag(void)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000599}
600
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601/* Magic for extension modules (built-in as well as dynamically
602 loaded). To prevent initializing an extension module more than
603 once, we keep a static dictionary 'extensions' keyed by module name
604 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000605 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100606 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607 immediately after the module initialization function succeeds. A
608 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100609 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000611 Modules which do support multiple initialization set their m_size
612 field to a non-negative number (indicating the size of the
613 module-specific state). They are still recorded in the extensions
614 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000615*/
616
617int
Victor Stinner95872862011-03-07 18:20:56 +0100618_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
619 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *modules, *dict;
622 struct PyModuleDef *def;
623 if (extensions == NULL) {
624 extensions = PyDict_New();
625 if (extensions == NULL)
626 return -1;
627 }
628 if (mod == NULL || !PyModule_Check(mod)) {
629 PyErr_BadInternalCall();
630 return -1;
631 }
632 def = PyModule_GetDef(mod);
633 if (!def) {
634 PyErr_BadInternalCall();
635 return -1;
636 }
637 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100638 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return -1;
640 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100641 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return -1;
643 }
644 if (def->m_size == -1) {
645 if (def->m_base.m_copy) {
646 /* Somebody already imported the module,
647 likely under a different name.
648 XXX this should really not happen. */
649 Py_DECREF(def->m_base.m_copy);
650 def->m_base.m_copy = NULL;
651 }
652 dict = PyModule_GetDict(mod);
653 if (dict == NULL)
654 return -1;
655 def->m_base.m_copy = PyDict_Copy(dict);
656 if (def->m_base.m_copy == NULL)
657 return -1;
658 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000659 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661}
662
Victor Stinner49d3f252010-10-17 01:24:53 +0000663int
664_PyImport_FixupBuiltin(PyObject *mod, char *name)
665{
666 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100667 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100668 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100669 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000670 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100671 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
672 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000673 return res;
674}
675
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100677_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *mod, *mdict;
680 PyModuleDef* def;
681 if (extensions == NULL)
682 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000683 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (def == NULL)
685 return NULL;
686 if (def->m_size == -1) {
687 /* Module does not support repeated initialization */
688 if (def->m_base.m_copy == NULL)
689 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100690 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (mod == NULL)
692 return NULL;
693 mdict = PyModule_GetDict(mod);
694 if (mdict == NULL)
695 return NULL;
696 if (PyDict_Update(mdict, def->m_base.m_copy))
697 return NULL;
698 }
699 else {
700 if (def->m_base.m_init == NULL)
701 return NULL;
702 mod = def->m_base.m_init();
703 if (mod == NULL)
704 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100705 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_DECREF(mod);
707 }
708 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100709 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(mod);
711 return NULL;
712 }
713 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100714 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 name, filename);
716 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000717
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718}
719
Victor Stinner49d3f252010-10-17 01:24:53 +0000720PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000721_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000722{
Victor Stinner95872862011-03-07 18:20:56 +0100723 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100724 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100725 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000726 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100727 res = _PyImport_FindExtensionObject(nameobj, nameobj);
728 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000729 return res;
730}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
732/* Get the module object corresponding to a module name.
733 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000734 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000735 Because the former action is most common, THIS DOES NOT RETURN A
736 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000739PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject *modules = PyImport_GetModuleDict();
742 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743
Victor Stinner27ee0892011-03-04 12:57:09 +0000744 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyModule_Check(m))
746 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000747 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (m == NULL)
749 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000750 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 Py_DECREF(m);
752 return NULL;
753 }
754 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757}
758
Victor Stinner27ee0892011-03-04 12:57:09 +0000759PyObject *
760PyImport_AddModule(const char *name)
761{
762 PyObject *nameobj, *module;
763 nameobj = PyUnicode_FromString(name);
764 if (nameobj == NULL)
765 return NULL;
766 module = PyImport_AddModuleObject(nameobj);
767 Py_DECREF(nameobj);
768 return module;
769}
770
771
Tim Peters1cd70172004-08-02 03:52:12 +0000772/* Remove name from sys.modules, if it's there. */
773static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000774remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000777 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000779 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 Py_FatalError("import: deleting existing key in"
781 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000782}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783
Victor Stinnerc9abda02011-03-14 13:33:46 -0400784static PyObject * get_sourcefile(PyObject *filename);
785static PyObject *make_source_pathname(PyObject *pathname);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200786static PyObject* make_compiled_pathname(PyObject *pathname, int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000787
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000788/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000789 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
790 * removed from sys.modules, to avoid leaving damaged module objects
791 * in sys.modules. The caller may wish to restore the original
792 * module object (if any) in this case; PyImport_ReloadModule is an
793 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000794 *
795 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
796 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000797 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000798PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000799PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return PyImport_ExecCodeModuleWithPathnames(
802 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000803}
804
805PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000806PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return PyImport_ExecCodeModuleWithPathnames(
809 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000810}
811
812PyObject *
813PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000815{
Victor Stinner27ee0892011-03-04 12:57:09 +0000816 PyObject *m = NULL;
817 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
818
819 nameobj = PyUnicode_FromString(name);
820 if (nameobj == NULL)
821 return NULL;
822
823 if (pathname != NULL) {
824 pathobj = PyUnicode_DecodeFSDefault(pathname);
825 if (pathobj == NULL)
826 goto error;
827 } else
828 pathobj = NULL;
829 if (cpathname != NULL) {
830 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
831 if (cpathobj == NULL)
832 goto error;
833 } else
834 cpathobj = NULL;
835 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
836error:
837 Py_DECREF(nameobj);
838 Py_XDECREF(pathobj);
839 Py_XDECREF(cpathobj);
840 return m;
841}
842
843PyObject*
844PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
845 PyObject *cpathname)
846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 PyObject *modules = PyImport_GetModuleDict();
848 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000849
Victor Stinner27ee0892011-03-04 12:57:09 +0000850 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (m == NULL)
852 return NULL;
853 /* If the module is being reloaded, we get the old module back
854 and re-use its dict to exec the new code. */
855 d = PyModule_GetDict(m);
856 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
857 if (PyDict_SetItemString(d, "__builtins__",
858 PyEval_GetBuiltins()) != 0)
859 goto error;
860 }
861 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400863 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (v == NULL)
865 PyErr_Clear();
866 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000867 else
868 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (v == NULL) {
870 v = ((PyCodeObject *)co)->co_filename;
871 Py_INCREF(v);
872 }
873 if (PyDict_SetItemString(d, "__file__", v) != 0)
874 PyErr_Clear(); /* Not important enough to report */
875 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000878 if (cpathname != NULL)
879 v = cpathname;
880 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (PyDict_SetItemString(d, "__cached__", v) != 0)
883 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000884
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000885 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (v == NULL)
887 goto error;
888 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000889
Victor Stinner27ee0892011-03-04 12:57:09 +0000890 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000892 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 name);
894 return NULL;
895 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000900
901 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 remove_module(name);
903 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904}
905
906
Martin v. Löwis2db72862011-10-23 17:29:08 +0200907/* Like rightmost_sep, but operate on unicode objects. */
908static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200909rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200910{
911 Py_ssize_t found, i;
912 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200913 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200914 c = PyUnicode_READ_CHAR(o, i);
915 if (c == SEP
916#ifdef ALTSEP
917 || c == ALTSEP
918#endif
919 )
920 {
921 found = i;
922 }
923 }
924 return found;
925}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400926
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000927/* Given a pathname for a Python source file, fill a buffer with the
928 pathname for the corresponding compiled file. Return the pathname
929 for the compiled file, or NULL if there's no space in the buffer.
Victor Stinner2f42ae52011-03-20 00:41:24 +0100930 Doesn't set an exception.
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
Martin v. Löwis30260a72011-10-23 17:35:46 +0200932 foo.py -> __pycache__/foo.<tag>.pyc
933
934 pathstr is assumed to be "ready".
935*/
Victor Stinner2f42ae52011-03-20 00:41:24 +0100936
937static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200938make_compiled_pathname(PyObject *pathstr, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000939{
Martin v. Löwis2db72862011-10-23 17:29:08 +0200940 PyObject *result;
941 Py_ssize_t fname, ext, len, i, pos, taglen;
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200942 Py_ssize_t pycache_len = sizeof(CACHEDIR) - 1;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200943 int kind;
944 void *data;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200945 Py_UCS4 lastsep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000946
Martin v. Löwis2db72862011-10-23 17:29:08 +0200947 /* Compute the output string size. */
948 len = PyUnicode_GET_LENGTH(pathstr);
949 /* If there is no separator, this returns -1, so
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200950 fname will be 0. */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200951 fname = rightmost_sep_obj(pathstr, 0, len) + 1;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200952 /* Windows: re-use the last separator character (/ or \\) when
953 appending the __pycache__ path. */
954 if (fname > 0)
955 lastsep = PyUnicode_READ_CHAR(pathstr, fname -1);
956 else
957 lastsep = SEP;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200958 ext = fname - 1;
959 for(i = fname; i < len; i++)
960 if (PyUnicode_READ_CHAR(pathstr, i) == '.')
961 ext = i + 1;
962 if (ext < fname)
963 /* No dot in filename; use entire filename */
964 ext = len;
965
966 /* result = pathstr[:fname] + "__pycache__" + SEP +
967 pathstr[fname:ext] + tag + ".py[co]" */
968 taglen = strlen(pyc_tag);
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200969 result = PyUnicode_New(ext + pycache_len + 1 + taglen + 4,
Martin v. Löwis2db72862011-10-23 17:29:08 +0200970 PyUnicode_MAX_CHAR_VALUE(pathstr));
971 if (!result)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200972 return NULL;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200973 kind = PyUnicode_KIND(result);
974 data = PyUnicode_DATA(result);
975 PyUnicode_CopyCharacters(result, 0, pathstr, 0, fname);
976 pos = fname;
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200977 for (i = 0; i < pycache_len; i++)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200978 PyUnicode_WRITE(kind, data, pos++, CACHEDIR[i]);
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200979 PyUnicode_WRITE(kind, data, pos++, lastsep);
Martin v. Löwis2db72862011-10-23 17:29:08 +0200980 PyUnicode_CopyCharacters(result, pos, pathstr,
981 fname, ext - fname);
982 pos += ext - fname;
983 for (i = 0; pyc_tag[i]; i++)
984 PyUnicode_WRITE(kind, data, pos++, pyc_tag[i]);
985 PyUnicode_WRITE(kind, data, pos++, '.');
986 PyUnicode_WRITE(kind, data, pos++, 'p');
987 PyUnicode_WRITE(kind, data, pos++, 'y');
988 PyUnicode_WRITE(kind, data, pos++, debug ? 'c' : 'o');
989 return result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000990}
991
992
Barry Warsaw28a691b2010-04-17 00:19:56 +0000993/* Given a pathname to a Python byte compiled file, return the path to the
994 source file, if the path matches the PEP 3147 format. This does not check
995 for any file existence, however, if the pyc file name does not match PEP
996 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400997 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998
Victor Stinnerc9abda02011-03-14 13:33:46 -0400999 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
1000
1001static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001002make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +00001003{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001004 Py_ssize_t left, right, dot0, dot1, len;
1005 Py_ssize_t i, j;
1006 PyObject *result;
1007 int kind;
1008 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001009
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001010 len = PyUnicode_GET_LENGTH(path);
1011 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001012 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* Look back two slashes from the end. In between these two slashes
1015 must be the string __pycache__ or this is not a PEP 3147 style
1016 path. It's possible for there to be only one slash.
1017 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001018 right = rightmost_sep_obj(path, 0, len);
1019 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001021 left = rightmost_sep_obj(path, 0, right);
1022 if (left == -1)
1023 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 else
1025 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001026 if (right-left != sizeof(CACHEDIR)-1)
1027 return NULL;
1028 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
1029 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
1030 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 /* Now verify that the path component to the right of the last slash
1033 has two dots in it.
1034 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001035 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
1036 if (dot0 < 0)
1037 return NULL;
1038 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
1039 if (dot1 < 0)
1040 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001042 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
1043 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* This is a PEP 3147 path. Start by copying everything from the
1046 start of pathname up to and including the leftmost slash. Then
1047 copy the file's basename, removing the magic tag and adding a .py
1048 suffix.
1049 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001050 result = PyUnicode_New(left + (dot0-right) + 2,
1051 PyUnicode_MAX_CHAR_VALUE(path));
1052 if (!result)
1053 return NULL;
1054 kind = PyUnicode_KIND(result);
1055 data = PyUnicode_DATA(result);
1056 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
1057 PyUnicode_CopyCharacters(result, left, path, right+1,
1058 (j = dot0-right));
1059 PyUnicode_WRITE(kind, data, i+j, 'p');
1060 PyUnicode_WRITE(kind, data, i+j+1, 'y');
1061 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001062}
1063
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064
1065/* Read a code object from a file and check it for validity */
1066
Guido van Rossum79f25d91997-04-29 20:08:16 +00001067static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001068read_compiled_module(PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 co = PyMarshal_ReadLastObjectFromFile(fp);
1073 if (co == NULL)
1074 return NULL;
1075 if (!PyCode_Check(co)) {
1076 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001077 "Non-code object in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 Py_DECREF(co);
1079 return NULL;
1080 }
1081 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001082}
1083
1084
1085/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001086 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001087
Guido van Rossum79f25d91997-04-29 20:08:16 +00001088static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001089load_compiled_module(PyObject *name, PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 long magic;
1092 PyCodeObject *co;
1093 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 magic = PyMarshal_ReadLongFromFile(fp);
1096 if (magic != pyc_magic) {
1097 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001098 "Bad magic number in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 return NULL;
1100 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001101 /* Skip mtime and size */
1102 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 (void) PyMarshal_ReadLongFromFile(fp);
1104 co = read_compiled_module(cpathname, fp);
1105 if (co == NULL)
1106 return NULL;
1107 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001108 PySys_FormatStderr("import %U # precompiled from %R\n",
1109 name, cpathname);
1110 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1111 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001115}
1116
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001117static void
1118update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyObject *constants, *tmp;
1121 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (PyUnicode_Compare(co->co_filename, oldname))
1124 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 tmp = co->co_filename;
1127 co->co_filename = newname;
1128 Py_INCREF(co->co_filename);
1129 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 constants = co->co_consts;
1132 n = PyTuple_GET_SIZE(constants);
1133 for (i = 0; i < n; i++) {
1134 tmp = PyTuple_GET_ITEM(constants, i);
1135 if (PyCode_Check(tmp))
1136 update_code_filenames((PyCodeObject *)tmp,
1137 oldname, newname);
1138 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001139}
1140
Victor Stinner2f42ae52011-03-20 00:41:24 +01001141static void
1142update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001143{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001144 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001145
Victor Stinner2f42ae52011-03-20 00:41:24 +01001146 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1147 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 oldname = co->co_filename;
1150 Py_INCREF(oldname);
1151 update_code_filenames(co, oldname, newname);
1152 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001153}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001154
Brett Cannon442c9b92011-03-23 16:14:42 -07001155static PyObject *
1156imp_fix_co_filename(PyObject *self, PyObject *args)
1157{
1158 PyObject *co;
1159 PyObject *file_path;
1160
1161 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1162 return NULL;
1163
1164 if (!PyCode_Check(co)) {
1165 PyErr_SetString(PyExc_TypeError,
1166 "first argument must be a code object");
1167 return NULL;
1168 }
1169
1170 if (!PyUnicode_Check(file_path)) {
1171 PyErr_SetString(PyExc_TypeError,
1172 "second argument must be a string");
1173 return NULL;
1174 }
1175
1176 update_compiled_module((PyCodeObject*)co, file_path);
1177
1178 Py_RETURN_NONE;
1179}
1180
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001181
Christian Heimes3b06e532008-01-07 20:12:44 +00001182/* Get source file -> unicode or None
1183 * Returns the path to the py file if available, else the given path
1184 */
1185static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001186get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001189 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001190 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001192 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001194 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001195 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001197
Victor Stinnerc9abda02011-03-14 13:33:46 -04001198 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001199 fileuni = PyUnicode_AsUCS4Copy(filename);
1200 if (!fileuni)
1201 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001202 if (len < 5
1203 || fileuni[len-4] != '.'
1204 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1205 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1206 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Start by trying to turn PEP 3147 path into source path. If that
1209 * fails, just chop off the trailing character, i.e. legacy pyc path
1210 * to py.
1211 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001212 py = make_source_pathname(filename);
1213 if (py == NULL) {
1214 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001215 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001217 if (py == NULL)
1218 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001219
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001220 err = _Py_stat(py, &statbuf);
1221 if (err == -2)
1222 goto error;
1223 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001224 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001225 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001226 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001227 Py_DECREF(py);
1228 goto unchanged;
1229
1230error:
1231 PyErr_Clear();
1232unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001233 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001234 Py_INCREF(filename);
1235 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001236}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001237
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001238/* Forward */
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001239static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001240 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001241static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001242
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001243
1244/* Helper to test for built-in module */
1245
1246static int
Victor Stinner95872862011-03-07 18:20:56 +01001247is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001248{
Victor Stinner95872862011-03-07 18:20:56 +01001249 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001251 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1252 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (PyImport_Inittab[i].initfunc == NULL)
1254 return -1;
1255 else
1256 return 1;
1257 }
1258 }
1259 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001260}
1261
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001262
Just van Rossum52e14d62002-12-30 22:08:05 +00001263/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1264 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001265 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001266 that can handle the path item. Return None if no hook could;
1267 this tells our caller it should fall back to the builtin
1268 import mechanism. Cache the result in path_importer_cache.
1269 Returns a borrowed reference. */
1270
1271static PyObject *
1272get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject *importer;
1276 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* These conditions are the caller's responsibility: */
1279 assert(PyList_Check(path_hooks));
1280 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 nhooks = PyList_Size(path_hooks);
1283 if (nhooks < 0)
1284 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 importer = PyDict_GetItem(path_importer_cache, p);
1287 if (importer != NULL)
1288 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 /* set path_importer_cache[p] to None to avoid recursion */
1291 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1292 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 for (j = 0; j < nhooks; j++) {
1295 PyObject *hook = PyList_GetItem(path_hooks, j);
1296 if (hook == NULL)
1297 return NULL;
1298 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1299 if (importer != NULL)
1300 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1303 return NULL;
1304 }
1305 PyErr_Clear();
1306 }
1307 if (importer == NULL) {
1308 importer = PyObject_CallFunctionObjArgs(
1309 (PyObject *)&PyNullImporter_Type, p, NULL
1310 );
1311 if (importer == NULL) {
1312 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1313 PyErr_Clear();
1314 return Py_None;
1315 }
1316 }
1317 }
1318 if (importer != NULL) {
1319 int err = PyDict_SetItem(path_importer_cache, p, importer);
1320 Py_DECREF(importer);
1321 if (err != 0)
1322 return NULL;
1323 }
1324 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001325}
1326
Christian Heimes9cd17752007-11-18 19:35:23 +00001327PyAPI_FUNC(PyObject *)
1328PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1332 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1333 importer = get_path_importer(path_importer_cache,
1334 path_hooks, path);
1335 }
1336 }
1337 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1338 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001339}
1340
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001341/* Search the path (default sys.path) for a module. Return the
1342 corresponding filedescr struct, and (via return arguments) the
1343 pathname and an open file. Return NULL if the module is not found. */
1344
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001345#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001346extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1347 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001348#endif
1349
Victor Stinner547a2a62011-03-20 03:07:28 +01001350/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001351static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001352static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001353static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001354
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001355/* Get the path of a module: get its importer and call importer.find_module()
1356 hook, or check if the module if a package (if path/__init__.py exists).
1357
1358 -1: error: a Python error occurred
1359 0: ignore: an error occurred because of invalid data, but the error is not
1360 important enough to be reported.
1361 1: get path: module not found, but *buf contains its path
1362 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1363 and *buf is the path */
1364
1365static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001366find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001367 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001368 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001369{
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001370 PyObject *path_unicode, *filename = NULL;
1371 Py_ssize_t len, pos;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001372 struct stat statbuf;
1373 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001374 int err, result, addsep;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001375
1376 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001377 Py_INCREF(path);
1378 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001379 }
1380 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001381 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1382 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1383 if (path_unicode == NULL)
1384 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001385 }
1386 else
1387 return 0;
1388
Victor Stinner46084ba2011-10-06 02:39:42 +02001389 if (PyUnicode_READY(path_unicode))
1390 return -1;
1391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001392 len = PyUnicode_GET_LENGTH(path_unicode);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001393 if (PyUnicode_FindChar(path_unicode, 0, 0, len, 1) != -1) {
1394 result = 0;
1395 goto out; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001396 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001397
1398 /* sys.path_hooks import hook */
1399 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001400 _Py_IDENTIFIER(find_module);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001401 PyObject *importer;
1402
1403 importer = get_path_importer(path_importer_cache,
1404 path_hooks, path);
1405 if (importer == NULL) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001406 result = -1;
1407 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001408 }
1409 /* Note: importer is a borrowed reference */
1410 if (importer != Py_None) {
1411 PyObject *loader;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001412 loader = _PyObject_CallMethodId(importer,
1413 &PyId_find_module, "O", fullname);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001414 if (loader == NULL) {
1415 result = -1; /* error */
1416 goto out;
1417 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001418 if (loader != Py_None) {
1419 /* a loader was found */
1420 *p_loader = loader;
1421 *p_fd = &importhookdescr;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001422 result = 2;
1423 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001424 }
1425 Py_DECREF(loader);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001426 result = 0;
1427 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001428 }
1429 }
1430 /* no hook was found, use builtin import */
1431
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001432 addsep = 0;
1433 if (len > 0 && PyUnicode_READ_CHAR(path_unicode, len-1) != SEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001434#ifdef ALTSEP
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001435 && PyUnicode_READ_CHAR(path_unicode, len-1) != ALTSEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001436#endif
1437 )
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001438 addsep = 1;
1439 filename = PyUnicode_New(len + PyUnicode_GET_LENGTH(name) + addsep,
1440 Py_MAX(PyUnicode_MAX_CHAR_VALUE(path_unicode),
1441 PyUnicode_MAX_CHAR_VALUE(name)));
1442 if (filename == NULL) {
1443 result = -1;
1444 goto out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445 }
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001446 PyUnicode_CopyCharacters(filename, 0, path_unicode, 0, len);
1447 pos = len;
1448 if (addsep)
Victor Stinner1f795172011-11-17 00:45:54 +01001449 PyUnicode_WRITE(PyUnicode_KIND(filename),
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001450 PyUnicode_DATA(filename),
1451 pos++, SEP);
Victor Stinner1f795172011-11-17 00:45:54 +01001452 PyUnicode_CopyCharacters(filename, pos, name, 0,
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001453 PyUnicode_GET_LENGTH(name));
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001454
1455 /* Check for package import (buf holds a directory name,
1456 and there's an __init__ module in that directory */
1457#ifdef HAVE_STAT
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001458 err = _Py_stat(filename, &statbuf);
1459 if (err == -2) {
1460 result = -1;
1461 goto out;
1462 }
1463 if (err == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001464 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1465 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001466 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001467
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001468 match = case_ok(filename, 0, name);
1469 if (match < 0) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001470 result = -1;
1471 goto out;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001472 }
1473 if (match) { /* case matches */
1474 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001475 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001476 filename = NULL;
Victor Stinnerd0296212011-03-14 14:04:10 -04001477 *p_fd = &fd_package;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001478 result = 2;
1479 goto out;
Victor Stinnerd0296212011-03-14 14:04:10 -04001480 }
1481 else {
1482 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001483 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001484 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001485 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001486 if (err) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001487 result = -1;
1488 goto out;
Victor Stinner547a2a62011-03-20 03:07:28 +01001489 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001490 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001491 }
1492 }
1493#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001494 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001495 filename = NULL;
1496 result = 1;
1497 out:
1498 Py_DECREF(path_unicode);
1499 Py_XDECREF(filename);
1500 return result;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001501}
1502
1503/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001504 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001505
1506 If the module is found, return a file descriptor, write the path in
1507 *p_filename, write the pointer to the file object into *p_fp, and (if
1508 p_loader is not NULL) the loader into *p_loader.
1509
1510 Otherwise, raise an exception and return NULL. */
1511
Victor Stinner37580282011-03-20 01:34:43 +01001512static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001513find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001514 PyObject *search_path_list, PyObject *path_hooks,
1515 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001516 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 struct filedescr *fdp = NULL;
1520 char *filemode;
1521 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001522 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001523 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001524 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001525
Victor Stinner37580282011-03-20 01:34:43 +01001526 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001528 PyObject *path;
1529 int ok;
1530
1531 path = PyList_GetItem(search_path_list, i);
1532 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001534
Victor Stinner2fd76e42011-03-14 15:19:39 -04001535 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001536 ok = find_module_path(fullname, name, path,
1537 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001538 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001539 if (ok < 0)
1540 return NULL;
1541 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001543 if (ok == 2) {
1544 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001545 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001546 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001549 struct stat statbuf;
1550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 filemode = fdp->mode;
1552 if (filemode[0] == 'U')
1553 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001554
Victor Stinner2fd76e42011-03-14 15:19:39 -04001555 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1556 if (filename == NULL) {
1557 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001558 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001559 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001560
1561 if (Py_VerboseFlag > 1)
1562 PySys_FormatStderr("# trying %R\n", filename);
1563
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001564 err = _Py_stat(filename, &statbuf);
1565 if (err == -2) {
1566 Py_DECREF(prefix);
1567 Py_DECREF(filename);
1568 return NULL;
1569 }
1570 if (err != 0 || S_ISDIR(statbuf.st_mode)) {
Charles-François Natali1659b832011-12-07 23:17:58 +01001571 /* it doesn't exist, or it's a directory */
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001572 Py_DECREF(filename);
1573 continue;
1574 }
1575
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001576 fp = _Py_fopen(filename, filemode);
1577 if (fp == NULL) {
1578 Py_DECREF(filename);
Victor Stinner925ef392011-06-20 15:01:10 +02001579 if (PyErr_Occurred()) {
1580 Py_DECREF(prefix);
1581 return NULL;
1582 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001583 continue;
1584 }
1585 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
1586 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001587 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001588 Py_DECREF(filename);
1589 return NULL;
1590 }
1591 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001592 Py_DECREF(prefix);
1593 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04001594 *p_fp = fp;
1595 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001597 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04001598
1599 fclose(fp);
1600 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001602 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001604 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04001605 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04001606 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001607}
1608
Victor Stinner37580282011-03-20 01:34:43 +01001609/* Find a module:
1610
1611 - try find_module() of each sys.meta_path hook
1612 - try find_frozen()
1613 - try is_builtin()
1614 - try _PyWin_FindRegisteredModule() (Windows only)
1615 - otherwise, call find_module_path_list() with search_path_list (if not
1616 NULL) or sys.path
1617
Victor Stinner2fd76e42011-03-14 15:19:39 -04001618 fullname can be NULL, but only if p_loader is NULL.
1619
Victor Stinner37580282011-03-20 01:34:43 +01001620 Return:
1621
1622 - &fd_builtin (C_BUILTIN) if it is a builtin
1623 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04001624 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01001625 if it is a package
1626 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
1627 importer loader was found
1628 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
1629 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04001630 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01001631 - NULL on error
1632
Victor Stinner2fd76e42011-03-14 15:19:39 -04001633 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
1634 Eg. *p_path is set to NULL for a builtin package.
1635*/
Victor Stinner37580282011-03-20 01:34:43 +01001636
1637static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001638find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001639 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01001640{
1641 Py_ssize_t i, npath;
1642 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1643 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1644 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01001645
Victor Stinner2fd76e42011-03-14 15:19:39 -04001646 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01001647 *p_fp = NULL;
1648 if (p_loader != NULL)
1649 *p_loader = NULL;
1650
Victor Stinner37580282011-03-20 01:34:43 +01001651 /* sys.meta_path import hook */
1652 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001653 _Py_IDENTIFIER(find_module);
Victor Stinner37580282011-03-20 01:34:43 +01001654 PyObject *meta_path;
1655
1656 meta_path = PySys_GetObject("meta_path");
1657 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02001658 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01001659 "sys.meta_path must be a list of "
1660 "import hooks");
1661 return NULL;
1662 }
1663 Py_INCREF(meta_path); /* zap guard */
1664 npath = PyList_Size(meta_path);
1665 for (i = 0; i < npath; i++) {
1666 PyObject *loader;
1667 PyObject *hook = PyList_GetItem(meta_path, i);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001668 loader = _PyObject_CallMethodId(hook, &PyId_find_module,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001669 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01001670 search_path_list != NULL ?
1671 search_path_list : Py_None);
1672 if (loader == NULL) {
1673 Py_DECREF(meta_path);
1674 return NULL; /* true error */
1675 }
1676 if (loader != Py_None) {
1677 /* a loader was found */
1678 *p_loader = loader;
1679 Py_DECREF(meta_path);
1680 return &importhookdescr;
1681 }
1682 Py_DECREF(loader);
1683 }
1684 Py_DECREF(meta_path);
1685 }
1686
Victor Stinnerdf75a022011-03-14 13:40:04 -04001687 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001688 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01001689
1690 if (search_path_list == NULL) {
1691#ifdef MS_COREDLL
1692 FILE *fp;
1693 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01001694#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04001695 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01001696 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01001697#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04001698 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01001699 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01001700 *p_fp = fp;
1701 return fdp;
1702 }
1703 else if (PyErr_Occurred())
1704 return NULL;
1705#endif
Victor Stinner37580282011-03-20 01:34:43 +01001706 search_path_list = PySys_GetObject("path");
1707 }
1708
1709 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
Victor Stinner16191322011-09-15 19:28:05 +02001710 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01001711 "sys.path must be a list of directory names");
1712 return NULL;
1713 }
1714
1715 path_hooks = PySys_GetObject("path_hooks");
1716 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02001717 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01001718 "sys.path_hooks must be a list of "
1719 "import hooks");
1720 return NULL;
1721 }
1722 path_importer_cache = PySys_GetObject("path_importer_cache");
1723 if (path_importer_cache == NULL ||
1724 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02001725 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01001726 "sys.path_importer_cache must be a dict");
1727 return NULL;
1728 }
1729
1730 return find_module_path_list(fullname, name,
1731 search_path_list, path_hooks,
1732 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001733 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01001734}
1735
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001736/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001737 * The arguments here are tricky, best shown by example:
1738 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1739 * ^ ^ ^ ^
1740 * |--------------------- buf ---------------------|
1741 * |------------------- len ------------------|
1742 * |------ name -------|
1743 * |----- namelen -----|
1744 * buf is the full path, but len only counts up to (& exclusive of) the
1745 * extension. name is the module name, also exclusive of extension.
1746 *
1747 * We've already done a successful stat() or fopen() on buf, so know that
1748 * there's some match, possibly case-insensitive.
1749 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001750 * case_bytes() is to return 1 if there's a case-sensitive match for
1751 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00001752 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001753 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001754 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00001755 * on platforms with case-insensitive filesystems. It's trivial to implement
1756 * for case-sensitive filesystems. It's pretty much a cross-platform
1757 * nightmare for systems with case-insensitive filesystems.
1758 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001759
Tim Peters50d8d372001-02-28 05:34:27 +00001760/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001761 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00001762 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001763#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001764#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001765
Tim Peters50d8d372001-02-28 05:34:27 +00001766#elif defined(DJGPP)
1767#include <dir.h>
1768
Jason Tishler7961aa62005-05-20 00:56:54 +00001769#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001770#include <sys/types.h>
1771#include <dirent.h>
1772
Andrew MacIntyred9400542002-02-26 11:41:34 +00001773#elif defined(PYOS_OS2)
1774#define INCL_DOS
1775#define INCL_DOSERRORS
1776#define INCL_NOPMAPI
1777#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001778#endif
1779
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001780#if defined(DJGPP) \
1781 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
1782 && defined(HAVE_DIRENT_H)) \
1783 || defined(PYOS_OS2)
1784# define USE_CASE_OK_BYTES
1785#endif
1786
1787
1788#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00001789static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001790case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001791{
Tim Peters50d8d372001-02-28 05:34:27 +00001792/* Pick a platform-specific implementation; the sequence of #if's here should
1793 * match the sequence just above.
1794 */
1795
Tim Peters50d8d372001-02-28 05:34:27 +00001796/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001797#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 struct ffblk ffblk;
1799 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (Py_GETENV("PYTHONCASEOK") != NULL)
1802 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1805 if (done) {
1806 PyErr_Format(PyExc_NameError,
1807 "Can't find file for module %.100s\n(filename %.300s)",
1808 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01001809 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
1811 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001812
Jason Tishler7961aa62005-05-20 00:56:54 +00001813/* new-fangled macintosh (macosx) or Cygwin */
1814#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 DIR *dirp;
1816 struct dirent *dp;
1817 char dirname[MAXPATHLEN + 1];
1818 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (Py_GETENV("PYTHONCASEOK") != NULL)
1821 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 /* Copy the dir component into dirname; substitute "." if empty */
1824 if (dirlen <= 0) {
1825 dirname[0] = '.';
1826 dirname[1] = '\0';
1827 }
1828 else {
1829 assert(dirlen <= MAXPATHLEN);
1830 memcpy(dirname, buf, dirlen);
1831 dirname[dirlen] = '\0';
1832 }
1833 /* Open the directory and search the entries for an exact match. */
1834 dirp = opendir(dirname);
1835 if (dirp) {
1836 char *nameWithExt = buf + len - namelen;
1837 while ((dp = readdir(dirp)) != NULL) {
1838 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001839#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001841#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001843#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (thislen >= namelen &&
1845 strcmp(dp->d_name, nameWithExt) == 0) {
1846 (void)closedir(dirp);
1847 return 1; /* Found */
1848 }
1849 }
1850 (void)closedir(dirp);
1851 }
1852 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001853
Andrew MacIntyred9400542002-02-26 11:41:34 +00001854/* OS/2 */
1855#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 HDIR hdir = 1;
1857 ULONG srchcnt = 1;
1858 FILEFINDBUF3 ffbuf;
1859 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (Py_GETENV("PYTHONCASEOK") != NULL)
1862 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 rc = DosFindFirst(buf,
1865 &hdir,
1866 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1867 &ffbuf, sizeof(ffbuf),
1868 &srchcnt,
1869 FIL_STANDARD);
1870 if (rc != NO_ERROR)
1871 return 0;
1872 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001873
Tim Peters50d8d372001-02-28 05:34:27 +00001874/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1875#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001876# error "USE_CASE_OK_BYTES is not correctly defined"
1877#endif
1878}
1879#endif
1880
1881/*
1882 * Check if a filename case matchs the name case. We've already done a
1883 * successful stat() or fopen() on buf, so know that there's some match,
1884 * possibly case-insensitive.
1885 *
1886 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
1887 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
1888 * if envar PYTHONCASEOK exists.
1889 *
1890 * case_ok() is used to implement case-sensitive import semantics even
1891 * on platforms with case-insensitive filesystems. It's trivial to implement
1892 * for case-sensitive filesystems. It's pretty much a cross-platform
1893 * nightmare for systems with case-insensitive filesystems.
1894 */
1895
1896static int
1897case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
1898{
1899#ifdef MS_WINDOWS
1900 WIN32_FIND_DATAW data;
1901 HANDLE h;
1902 int cmp;
Victor Stinner1f795172011-11-17 00:45:54 +01001903 wchar_t *wfilename, *wname;
Victor Stinner8c981892011-10-11 22:27:13 +02001904 Py_ssize_t wname_len;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001905
1906 if (Py_GETENV("PYTHONCASEOK") != NULL)
1907 return 1;
1908
Victor Stinner1f795172011-11-17 00:45:54 +01001909 wfilename = PyUnicode_AsUnicode(filename);
1910 if (wfilename == NULL)
1911 return -1;
1912
1913 h = FindFirstFileW(wfilename, &data);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001914 if (h == INVALID_HANDLE_VALUE) {
1915 PyErr_Format(PyExc_NameError,
1916 "Can't find file for module %R\n(filename %R)",
1917 name, filename);
Victor Stinner1f795172011-11-17 00:45:54 +01001918 return -1;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001919 }
1920 FindClose(h);
Victor Stinnerbeac78b2011-10-11 21:55:01 +02001921
1922 wname = PyUnicode_AsUnicodeAndSize(name, &wname_len);
1923 if (wname == NULL)
1924 return -1;
1925
1926 cmp = wcsncmp(data.cFileName, wname, wname_len);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001927 return cmp == 0;
1928#elif defined(USE_CASE_OK_BYTES)
1929 int match;
1930 PyObject *filebytes, *namebytes;
1931 filebytes = PyUnicode_EncodeFSDefault(filename);
1932 if (filebytes == NULL)
1933 return -1;
1934 namebytes = PyUnicode_EncodeFSDefault(name);
1935 if (namebytes == NULL) {
1936 Py_DECREF(filebytes);
1937 return -1;
1938 }
1939 match = case_bytes(
1940 PyBytes_AS_STRING(filebytes),
1941 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01001942 PyBytes_GET_SIZE(namebytes),
1943 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001944 Py_DECREF(filebytes);
1945 Py_DECREF(namebytes);
1946 return match;
1947#else
1948 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001950
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001951#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001952}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001953
Guido van Rossum197346f1997-10-31 18:38:52 +00001954#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001955
Victor Stinner547a2a62011-03-20 03:07:28 +01001956/* Helper to look for __init__.py or __init__.py[co] in potential package.
1957 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00001958static int
Victor Stinner547a2a62011-03-20 03:07:28 +01001959find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00001960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01001962 PyObject *filename;
1963 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001964 int err;
Guido van Rossum197346f1997-10-31 18:38:52 +00001965
Victor Stinner547a2a62011-03-20 03:07:28 +01001966 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
1967 if (filename == NULL)
1968 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001969 err = _Py_stat(filename, &statbuf);
1970 if (err == -2)
1971 return -1;
1972 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01001973 /* 3=len(".py") */
1974 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001975 if (match < 0) {
1976 Py_DECREF(filename);
1977 return -1;
1978 }
1979 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01001980 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 return 1;
1982 }
1983 }
Victor Stinner547a2a62011-03-20 03:07:28 +01001984 Py_DECREF(filename);
1985
1986 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
1987 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
1988 if (filename == NULL)
1989 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001990 err = _Py_stat(filename, &statbuf);
1991 if (err == -2) {
1992 Py_DECREF(filename);
1993 return -1;
1994 }
1995 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01001996 /* 4=len(".pyc") */
1997 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001998 if (match < 0) {
1999 Py_DECREF(filename);
2000 return -1;
2001 }
2002 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002003 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 return 1;
2005 }
2006 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002007 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002009}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002010
Guido van Rossum197346f1997-10-31 18:38:52 +00002011#endif /* HAVE_STAT */
2012
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002013
Victor Stinner95872862011-03-07 18:20:56 +01002014static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002015
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002016/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002017 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002018 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002019
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002020static int
Victor Stinner95872862011-03-07 18:20:56 +01002021init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002024
Victor Stinner95872862011-03-07 18:20:56 +01002025 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 for (p = PyImport_Inittab; p->name != NULL; p++) {
2029 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002030 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01002031 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (p->initfunc == NULL) {
2033 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002034 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 name);
2036 return -1;
2037 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 mod = (*p->initfunc)();
2039 if (mod == 0)
2040 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002041 /* Remember pointer to module init function. */
2042 def = PyModule_GetDef(mod);
2043 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01002044 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 return -1;
2046 /* FixupExtension has put the module into sys.modules,
2047 so we can release our own reference. */
2048 Py_DECREF(mod);
2049 return 1;
2050 }
2051 }
2052 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002053}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002054
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002055
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002056/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002057
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002058static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002059find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002062
Victor Stinner53dc7352011-03-20 01:50:21 +01002063 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 for (p = PyImport_FrozenModules; ; p++) {
2067 if (p->name == NULL)
2068 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002069 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 break;
2071 }
2072 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002073}
2074
Guido van Rossum79f25d91997-04-29 20:08:16 +00002075static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002076get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 struct _frozen *p = find_frozen(name);
2079 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 if (p == NULL) {
2082 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002083 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 name);
2085 return NULL;
2086 }
2087 if (p->code == NULL) {
2088 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002089 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 name);
2091 return NULL;
2092 }
2093 size = p->size;
2094 if (size < 0)
2095 size = -size;
2096 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002097}
2098
Brett Cannon8d110132009-03-15 02:20:16 +00002099static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002100is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 struct _frozen *p = find_frozen(name);
2103 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (p == NULL) {
2106 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002107 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 name);
2109 return NULL;
2110 }
Brett Cannon8d110132009-03-15 02:20:16 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 if (size < 0)
2115 Py_RETURN_TRUE;
2116 else
2117 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002118}
2119
2120
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002121/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002122 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002123 an exception set if the initialization failed.
2124 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002125
2126int
Victor Stinner53dc7352011-03-20 01:50:21 +01002127PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002128{
Victor Stinner53dc7352011-03-20 01:50:21 +01002129 struct _frozen *p;
2130 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 int ispackage;
2132 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002133
Victor Stinner53dc7352011-03-20 01:50:21 +01002134 p = find_frozen(name);
2135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (p == NULL)
2137 return 0;
2138 if (p->code == NULL) {
2139 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002140 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 name);
2142 return -1;
2143 }
2144 size = p->size;
2145 ispackage = (size < 0);
2146 if (ispackage)
2147 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2149 if (co == NULL)
2150 return -1;
2151 if (!PyCode_Check(co)) {
2152 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002153 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 name);
2155 goto err_return;
2156 }
2157 if (ispackage) {
2158 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002159 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002161 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (m == NULL)
2163 goto err_return;
2164 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 l = PyList_New(1);
2166 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 goto err_return;
2168 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002169 Py_INCREF(name);
2170 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 err = PyDict_SetItemString(d, "__path__", l);
2172 Py_DECREF(l);
2173 if (err != 0)
2174 goto err_return;
2175 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002176 path = PyUnicode_FromString("<frozen>");
2177 if (path == NULL)
2178 goto err_return;
2179 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2180 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (m == NULL)
2182 goto err_return;
2183 Py_DECREF(co);
2184 Py_DECREF(m);
2185 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002186err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 Py_DECREF(co);
2188 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002189}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002190
Victor Stinner53dc7352011-03-20 01:50:21 +01002191int
2192PyImport_ImportFrozenModule(char *name)
2193{
2194 PyObject *nameobj;
2195 int ret;
2196 nameobj = PyUnicode_InternFromString(name);
2197 if (nameobj == NULL)
2198 return -1;
2199 ret = PyImport_ImportFrozenModuleObject(nameobj);
2200 Py_DECREF(nameobj);
2201 return ret;
2202}
2203
Guido van Rossum74e6a111994-08-29 12:54:38 +00002204
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002205/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002206 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002207
Guido van Rossum79f25d91997-04-29 20:08:16 +00002208PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002209PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyObject *pname;
2212 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 pname = PyUnicode_FromString(name);
2215 if (pname == NULL)
2216 return NULL;
2217 result = PyImport_Import(pname);
2218 Py_DECREF(pname);
2219 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002220}
2221
Christian Heimes072c0f12008-01-03 23:01:04 +00002222/* Import a module without blocking
2223 *
2224 * At first it tries to fetch the module from sys.modules. If the module was
2225 * never loaded before it loads it with PyImport_ImportModule() unless another
2226 * thread holds the import lock. In the latter case the function raises an
2227 * ImportError instead of blocking.
2228 *
2229 * Returns the module object with incremented ref count.
2230 */
2231PyObject *
2232PyImport_ImportModuleNoBlock(const char *name)
2233{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002234 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002235#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002237#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 /* Try to get the module from sys.modules[name] */
2240 modules = PyImport_GetModuleDict();
2241 if (modules == NULL)
2242 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002243
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002244 nameobj = PyUnicode_FromString(name);
2245 if (nameobj == NULL)
2246 return NULL;
2247 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002249 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 Py_INCREF(result);
2251 return result;
2252 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002253 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002254#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* check the import lock
2256 * me might be -1 but I ignore the error here, the lock function
2257 * takes care of the problem */
2258 me = PyThread_get_thread_ident();
2259 if (import_lock_thread == -1 || import_lock_thread == me) {
2260 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002261 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 }
2263 else {
2264 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002265 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002267 nameobj);
2268 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002270#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002271 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002272#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002273 Py_DECREF(nameobj);
2274 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002275}
2276
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002277
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002278PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04002279PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
2280 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002281 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002282{
Brett Cannonfd074152012-04-14 14:10:13 -04002283 _Py_IDENTIFIER(__import__);
2284 _Py_IDENTIFIER(__package__);
2285 _Py_IDENTIFIER(__path__);
2286 _Py_IDENTIFIER(__name__);
2287 _Py_IDENTIFIER(_find_and_load);
2288 _Py_IDENTIFIER(_handle_fromlist);
2289 _Py_static_string(single_dot, ".");
2290 PyObject *abs_name = NULL;
2291 PyObject *builtins_import = NULL;
2292 PyObject *final_mod = NULL;
2293 PyObject *mod = NULL;
2294 PyObject *package = NULL;
2295 PyObject *globals = NULL;
2296 PyObject *fromlist = NULL;
2297 PyInterpreterState *interp = PyThreadState_GET()->interp;
2298
2299 /* Make sure to use default values so as to not have
2300 PyObject_CallMethodObjArgs() truncate the parameter list because of a
2301 NULL argument. */
2302 if (given_globals == NULL) {
2303 globals = PyDict_New();
2304 if (globals == NULL) {
2305 goto error;
2306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 }
Brett Cannonfd074152012-04-14 14:10:13 -04002308 else {
2309 /* Only have to care what given_globals is if it will be used
2310 fortsomething. */
2311 if (level > 0 && !PyDict_Check(given_globals)) {
2312 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
2313 goto error;
2314 }
2315 globals = given_globals;
2316 Py_INCREF(globals);
2317 }
2318
2319 if (given_fromlist == NULL) {
2320 fromlist = PyList_New(0);
2321 if (fromlist == NULL) {
2322 goto error;
2323 }
2324 }
2325 else {
2326 fromlist = given_fromlist;
2327 Py_INCREF(fromlist);
2328 }
2329 if (name == NULL) {
2330 PyErr_SetString(PyExc_ValueError, "Empty module name");
2331 goto error;
2332 }
2333
2334 /* The below code is importlib.__import__() & _gcd_import(), ported to C
2335 for added performance. */
2336
2337 if (!PyUnicode_Check(name)) {
2338 PyErr_SetString(PyExc_TypeError, "module name must be a string");
2339 goto error;
2340 }
2341 else if (PyUnicode_READY(name) < 0) {
2342 goto error;
2343 }
2344 if (level < 0) {
2345 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
2346 goto error;
2347 }
2348 else if (level > 0) {
2349 package = _PyDict_GetItemId(globals, &PyId___package__);
2350 if (package != NULL && package != Py_None) {
2351 Py_INCREF(package);
2352 if (!PyUnicode_Check(package)) {
2353 PyErr_SetString(PyExc_TypeError, "package must be a string");
2354 goto error;
2355 }
2356 }
2357 else {
2358 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
2359 if (package == NULL) {
2360 goto error;
2361 }
2362 else if (!PyUnicode_Check(package)) {
2363 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
2364 }
2365 Py_INCREF(package);
2366
2367 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04002368 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04002369 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
2370 if (borrowed_dot == NULL) {
2371 goto error;
2372 }
Brett Cannon740fce02012-04-14 14:23:49 -04002373 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04002374 Py_DECREF(package);
2375 if (partition == NULL) {
2376 goto error;
2377 }
2378 package = PyTuple_GET_ITEM(partition, 0);
2379 Py_INCREF(package);
2380 Py_DECREF(partition);
2381 }
2382 }
2383
2384 if (PyDict_GetItem(interp->modules, package) == NULL) {
2385 PyErr_Format(PyExc_SystemError,
2386 "Parent module %R not loaded, cannot perform relative "
2387 "import", package);
2388 goto error;
2389 }
2390 }
2391 else { /* level == 0 */
2392 if (PyUnicode_GET_LENGTH(name) == 0) {
2393 PyErr_SetString(PyExc_ValueError, "Empty module name");
2394 goto error;
2395 }
2396 package = Py_None;
2397 Py_INCREF(package);
2398 }
2399
2400 if (level > 0) {
2401 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
2402 PyObject *base = NULL;
2403 int level_up = 1;
2404
2405 for (level_up = 1; level_up < level; level_up += 1) {
2406 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
2407 if (last_dot == -2) {
2408 goto error;
2409 }
2410 else if (last_dot == -1) {
2411 PyErr_SetString(PyExc_ValueError,
2412 "attempted relative import beyond top-level "
2413 "package");
2414 goto error;
2415 }
2416 }
2417 base = PyUnicode_Substring(package, 0, last_dot);
2418 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02002419 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04002420
2421 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02002422 seq = PyTuple_Pack(2, base, name);
2423 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04002424 if (borrowed_dot == NULL || seq == NULL) {
2425 goto error;
2426 }
2427
2428 abs_name = PyUnicode_Join(borrowed_dot, seq);
2429 Py_DECREF(seq);
2430 if (abs_name == NULL) {
2431 goto error;
2432 }
2433 }
2434 else {
2435 abs_name = base;
2436 }
2437 }
2438 else {
2439 abs_name = name;
2440 Py_INCREF(abs_name);
2441 }
2442
Brian Curtine6b299f2012-04-14 14:19:33 -05002443#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04002444 _PyImport_AcquireLock();
2445#endif
2446 /* From this point forward, goto error_with_unlock! */
2447 if (PyDict_Check(globals)) {
2448 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
2449 }
2450 if (builtins_import == NULL) {
2451 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
2452 if (builtins_import == NULL) {
2453 Py_FatalError("__import__ missing");
2454 }
2455 }
2456 Py_INCREF(builtins_import);
2457
2458 mod = PyDict_GetItem(interp->modules, abs_name);
2459 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04002460 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
2461 "None in sys.modules", abs_name);
2462 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05002463 PyErr_SetImportError(msg, abs_name, NULL);
2464 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04002465 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02002466 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04002467 goto error_with_unlock;
2468 }
2469 else if (mod != NULL) {
2470 Py_INCREF(mod);
2471 }
2472 else {
2473 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
2474 &PyId__find_and_load, abs_name,
2475 builtins_import, NULL);
2476 if (mod == NULL) {
2477 goto error_with_unlock;
2478 }
2479 }
2480
2481 if (PyObject_Not(fromlist)) {
2482 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
2483 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05002484 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04002485 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
2486
2487 if (borrowed_dot == NULL) {
2488 goto error_with_unlock;
2489 }
2490
Brian Curtine6b299f2012-04-14 14:19:33 -05002491 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04002492 if (partition == NULL) {
2493 goto error_with_unlock;
2494 }
2495
2496 front = PyTuple_GET_ITEM(partition, 0);
2497 Py_INCREF(front);
2498 Py_DECREF(partition);
2499
2500 if (level == 0) {
Brett Cannon881535b2012-04-15 15:24:04 -04002501 if (PyUnicode_GET_LENGTH(name) ==
2502 PyUnicode_GET_LENGTH(front)) {
2503 final_mod = mod;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04002504 }
2505 else {
Brett Cannon881535b2012-04-15 15:24:04 -04002506 final_mod = PyDict_GetItem(interp->modules, front);
2507 if (final_mod == NULL) {
2508 PyErr_Format(PyExc_KeyError,
2509 "%R not in sys.modules as expected", front);
2510 }
Brett Cannon49f8d8b2012-04-14 21:50:00 -04002511 }
Brett Cannon881535b2012-04-15 15:24:04 -04002512 Py_DECREF(front);
2513 if (final_mod == NULL) {
2514 goto error_with_unlock;
2515 }
2516 Py_INCREF(final_mod);
Brett Cannonfd074152012-04-14 14:10:13 -04002517 }
2518 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02002519 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
2520 PyUnicode_GET_LENGTH(front);
2521 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04002522 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04002523 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02002524 Py_DECREF(front);
2525 if (to_return == NULL) {
2526 goto error_with_unlock;
2527 }
Brett Cannonfd074152012-04-14 14:10:13 -04002528
2529 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04002530 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04002531 if (final_mod == NULL) {
2532 PyErr_Format(PyExc_KeyError,
2533 "%R not in sys.modules as expected",
2534 to_return);
2535 }
2536 else {
2537 Py_INCREF(final_mod);
2538 }
Brett Cannonfd074152012-04-14 14:10:13 -04002539 }
2540 }
2541 else {
2542 final_mod = mod;
2543 Py_INCREF(mod);
2544 }
2545 }
2546 else {
2547 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
2548 &PyId__handle_fromlist, mod,
2549 fromlist, builtins_import,
2550 NULL);
2551 }
2552 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05002553#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04002554 if (_PyImport_ReleaseLock() < 0) {
2555 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
2556 }
2557#endif
2558 error:
2559 Py_XDECREF(abs_name);
2560 Py_XDECREF(builtins_import);
2561 Py_XDECREF(mod);
2562 Py_XDECREF(package);
2563 Py_XDECREF(globals);
2564 Py_XDECREF(fromlist);
2565 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002566}
2567
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002568PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05002569PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002570 PyObject *fromlist, int level)
2571{
2572 PyObject *nameobj, *mod;
2573 nameobj = PyUnicode_FromString(name);
2574 if (nameobj == NULL)
2575 return NULL;
2576 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2577 fromlist, level);
2578 Py_DECREF(nameobj);
2579 return mod;
2580}
2581
2582
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002583/* Re-import a module of any kind and return its module object, WITH
2584 INCREMENTED REFERENCE COUNT */
2585
Guido van Rossum79f25d91997-04-29 20:08:16 +00002586PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002587PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 PyInterpreterState *interp = PyThreadState_Get()->interp;
2590 PyObject *modules_reloading = interp->modules_reloading;
2591 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon8a1d04c2012-04-15 17:56:09 -04002592 PyObject *loader = NULL, *existing_m = NULL;
2593 PyObject *name;
Martin v. Löwis796ea532011-10-30 09:07:07 +01002594 Py_ssize_t subname_start;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002595 PyObject *newm = NULL;
Brett Cannon8a1d04c2012-04-15 17:56:09 -04002596 _Py_IDENTIFIER(__loader__);
2597 _Py_IDENTIFIER(load_module);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (modules_reloading == NULL) {
2600 Py_FatalError("PyImport_ReloadModule: "
2601 "no modules_reloading dictionary!");
2602 return NULL;
2603 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (m == NULL || !PyModule_Check(m)) {
2606 PyErr_SetString(PyExc_TypeError,
2607 "reload() argument must be module");
2608 return NULL;
2609 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01002610 name = PyModule_GetNameObject(m);
2611 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01002613 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002615 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01002616 name);
2617 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 return NULL;
2619 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01002620 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 if (existing_m != NULL) {
2622 /* Due to a recursive reload, this module is already
2623 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01002624 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 Py_INCREF(existing_m);
2626 return existing_m;
2627 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01002628 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
2629 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002631 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002632
Martin v. Löwis796ea532011-10-30 09:07:07 +01002633 subname_start = PyUnicode_FindChar(name, '.', 0,
2634 PyUnicode_GET_LENGTH(name), -1);
Brett Cannon8a1d04c2012-04-15 17:56:09 -04002635 if (subname_start != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 PyObject *parentname, *parent;
Martin v. Löwis796ea532011-10-30 09:07:07 +01002637 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002639 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 }
2641 parent = PyDict_GetItem(modules, parentname);
Brett Cannon8a1d04c2012-04-15 17:56:09 -04002642 Py_XDECREF(parent);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 if (parent == NULL) {
2644 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002645 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002647 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002650
Brett Cannon8a1d04c2012-04-15 17:56:09 -04002651 loader = _PyObject_GetAttrId(m, &PyId___loader__);
2652 if (loader == NULL) {
2653 goto error;
2654 }
2655 newm = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
2656 Py_DECREF(loader);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (newm == NULL) {
2658 /* load_module probably removed name from modules because of
2659 * the error. Put back the original module object. We're
2660 * going to return NULL in this case regardless of whether
2661 * replacing name succeeds, so the return value is ignored.
2662 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01002663 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002665
2666error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01002668 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002670}
2671
2672
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002673/* Higher-level import emulator which emulates the "import" statement
2674 more accurately -- it invokes the __import__() function from the
2675 builtins of the current globals. This means that the import is
2676 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002677 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002678 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002679 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002680 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002681
2682PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002683PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 static PyObject *silly_list = NULL;
2686 static PyObject *builtins_str = NULL;
2687 static PyObject *import_str = NULL;
2688 PyObject *globals = NULL;
2689 PyObject *import = NULL;
2690 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002691 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 /* Initialize constant string objects */
2695 if (silly_list == NULL) {
2696 import_str = PyUnicode_InternFromString("__import__");
2697 if (import_str == NULL)
2698 return NULL;
2699 builtins_str = PyUnicode_InternFromString("__builtins__");
2700 if (builtins_str == NULL)
2701 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002702 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 if (silly_list == NULL)
2704 return NULL;
2705 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* Get the builtins from current globals */
2708 globals = PyEval_GetGlobals();
2709 if (globals != NULL) {
2710 Py_INCREF(globals);
2711 builtins = PyObject_GetItem(globals, builtins_str);
2712 if (builtins == NULL)
2713 goto err;
2714 }
2715 else {
2716 /* No globals -- use standard builtins, and fake globals */
2717 builtins = PyImport_ImportModuleLevel("builtins",
2718 NULL, NULL, NULL, 0);
2719 if (builtins == NULL)
2720 return NULL;
2721 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2722 if (globals == NULL)
2723 goto err;
2724 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 /* Get the __import__ function from the builtins */
2727 if (PyDict_Check(builtins)) {
2728 import = PyObject_GetItem(builtins, import_str);
2729 if (import == NULL)
2730 PyErr_SetObject(PyExc_KeyError, import_str);
2731 }
2732 else
2733 import = PyObject_GetAttr(builtins, import_str);
2734 if (import == NULL)
2735 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00002738 Always use absolute import here.
2739 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2741 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00002742 if (r == NULL)
2743 goto err;
2744 Py_DECREF(r);
2745
2746 modules = PyImport_GetModuleDict();
2747 r = PyDict_GetItem(modules, module_name);
2748 if (r != NULL)
2749 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002750
2751 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 Py_XDECREF(globals);
2753 Py_XDECREF(builtins);
2754 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002757}
2758
2759
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002760/* Module 'imp' provides Python access to the primitives used for
2761 importing modules.
2762*/
2763
Guido van Rossum79f25d91997-04-29 20:08:16 +00002764static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00002765imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 buf[0] = (char) ((magic >> 0) & 0xff);
2770 buf[1] = (char) ((magic >> 8) & 0xff);
2771 buf[2] = (char) ((magic >> 16) & 0xff);
2772 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00002775}
Barry Warsaw28a691b2010-04-17 00:19:56 +00002776
2777static PyObject *
2778imp_get_magic(PyObject *self, PyObject *noargs)
2779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00002781}
2782
2783static PyObject *
2784imp_get_tag(PyObject *self, PyObject *noargs)
2785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002787}
2788
Guido van Rossum79f25d91997-04-29 20:08:16 +00002789static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002790imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 PyObject *list;
2793 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 list = PyList_New(0);
2796 if (list == NULL)
2797 return NULL;
2798 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2799 PyObject *item = Py_BuildValue("ssi",
2800 fdp->suffix, fdp->mode, fdp->type);
2801 if (item == NULL) {
2802 Py_DECREF(list);
2803 return NULL;
2804 }
2805 if (PyList_Append(list, item) < 0) {
2806 Py_DECREF(list);
2807 Py_DECREF(item);
2808 return NULL;
2809 }
2810 Py_DECREF(item);
2811 }
2812 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002813}
2814
Guido van Rossum79f25d91997-04-29 20:08:16 +00002815static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04002816call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 extern int fclose(FILE *);
2819 PyObject *fob, *ret;
2820 PyObject *pathobj;
2821 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05002822 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 int fd = -1;
2824 char *found_encoding = NULL;
2825 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002826
Victor Stinner533d7832011-03-14 13:22:54 -04002827 if (path_list == Py_None)
2828 path_list = NULL;
2829 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002830 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 if (fdp == NULL)
2832 return NULL;
2833 if (fp != NULL) {
2834 fd = fileno(fp);
2835 if (fd != -1)
2836 fd = dup(fd);
2837 fclose(fp);
2838 fp = NULL;
Antoine Pitrou72146122012-02-22 18:03:04 +01002839 if (fd == -1)
2840 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 }
2842 if (fd != -1) {
2843 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02002844 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02002846 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04002848 if (found_encoding == NULL && PyErr_Occurred()) {
2849 Py_XDECREF(pathobj);
Antoine Pitrou4f22a8d2012-02-22 18:05:43 +01002850 close(fd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04002852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 encoding = (found_encoding != NULL) ? found_encoding :
2854 (char*)PyUnicode_GetDefaultEncoding();
2855 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002856 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 (char*)encoding, NULL, NULL, 1);
2858 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04002859 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 close(fd);
2861 PyMem_FREE(found_encoding);
2862 return NULL;
2863 }
2864 }
2865 else {
2866 fob = Py_None;
2867 Py_INCREF(fob);
2868 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002869 if (pathobj == NULL) {
2870 Py_INCREF(Py_None);
2871 pathobj = Py_None;
2872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 ret = Py_BuildValue("NN(ssi)",
2874 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
2875 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002878}
2879
Guido van Rossum79f25d91997-04-29 20:08:16 +00002880static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002881imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002882{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002883 PyObject *name, *path_list = NULL;
2884 if (!PyArg_ParseTuple(args, "U|O:find_module",
2885 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002887 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002888}
2889
2890static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002891imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002892{
Victor Stinner95872862011-03-07 18:20:56 +01002893 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 int ret;
2895 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01002896 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 return NULL;
2898 ret = init_builtin(name);
2899 if (ret < 0)
2900 return NULL;
2901 if (ret == 0) {
2902 Py_INCREF(Py_None);
2903 return Py_None;
2904 }
Victor Stinner95872862011-03-07 18:20:56 +01002905 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 Py_XINCREF(m);
2907 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002908}
2909
Guido van Rossum79f25d91997-04-29 20:08:16 +00002910static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002911imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002912{
Victor Stinner53dc7352011-03-20 01:50:21 +01002913 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 int ret;
2915 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01002916 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002918 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (ret < 0)
2920 return NULL;
2921 if (ret == 0) {
2922 Py_INCREF(Py_None);
2923 return Py_None;
2924 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002925 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 Py_XINCREF(m);
2927 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002928}
2929
Guido van Rossum79f25d91997-04-29 20:08:16 +00002930static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002931imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002932{
Victor Stinner53dc7352011-03-20 01:50:21 +01002933 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002934
Victor Stinner53dc7352011-03-20 01:50:21 +01002935 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 return NULL;
2937 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002938}
2939
Guido van Rossum79f25d91997-04-29 20:08:16 +00002940static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00002941imp_is_frozen_package(PyObject *self, PyObject *args)
2942{
Victor Stinner53dc7352011-03-20 01:50:21 +01002943 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002944
Victor Stinner53dc7352011-03-20 01:50:21 +01002945 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 return NULL;
2947 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002948}
2949
2950static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002951imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002952{
Victor Stinner95872862011-03-07 18:20:56 +01002953 PyObject *name;
2954 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 return NULL;
2956 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002957}
2958
Guido van Rossum79f25d91997-04-29 20:08:16 +00002959static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002960imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002961{
Victor Stinner53dc7352011-03-20 01:50:21 +01002962 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01002964 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 return NULL;
2966 p = find_frozen(name);
2967 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002968}
2969
2970static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01002971get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 FILE *fp;
2974 if (mode[0] == 'U')
2975 mode = "r" PY_STDIOTEXTMODE;
2976 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01002977 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01002978 if (!fp) {
2979 if (!PyErr_Occurred())
2980 PyErr_SetFromErrno(PyExc_IOError);
2981 return NULL;
2982 }
2983 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 }
2985 else {
2986 int fd = PyObject_AsFileDescriptor(fob);
2987 if (fd == -1)
2988 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01002989 if (!_PyVerify_fd(fd)) {
2990 PyErr_SetFromErrno(PyExc_IOError);
2991 return NULL;
2992 }
2993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 /* the FILE struct gets a new fd, so that it can be closed
2995 * independently of the file descriptor given
2996 */
2997 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01002998 if (fd == -1) {
2999 PyErr_SetFromErrno(PyExc_IOError);
3000 return NULL;
3001 }
3002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003004 if (!fp) {
3005 PyErr_SetFromErrno(PyExc_IOError);
3006 return NULL;
3007 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003009 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003010}
3011
Guido van Rossum79f25d91997-04-29 20:08:16 +00003012static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003013imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003014{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003015 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 PyObject *fob = NULL;
3017 PyObject *m;
3018 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003019 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003021 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 &fob))
3023 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003024 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003026 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 return NULL;
3028 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003029 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003031 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003033}
3034
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003035#ifdef HAVE_DYNAMIC_LOADING
3036
Guido van Rossum79f25d91997-04-29 20:08:16 +00003037static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003038imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003039{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003040 PyObject *name, *pathname, *fob = NULL, *mod;
3041 FILE *fp;
3042
3043 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3044 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003046 if (fob != NULL) {
3047 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003048 if (fp == NULL) {
3049 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003051 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003053 else
3054 fp = NULL;
3055 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003056 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 if (fp)
3058 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003059 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003060}
3061
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003062#endif /* HAVE_DYNAMIC_LOADING */
3063
Guido van Rossum79f25d91997-04-29 20:08:16 +00003064static PyObject *
Christian Heimes13a7a212008-01-07 17:13:09 +00003065imp_reload(PyObject *self, PyObject *v)
3066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003068}
3069
3070PyDoc_STRVAR(doc_reload,
3071"reload(module) -> module\n\
3072\n\
3073Reload the module. The module must have been successfully imported before.");
3074
Barry Warsaw28a691b2010-04-17 00:19:56 +00003075static PyObject *
3076imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003079
Victor Stinner2f42ae52011-03-20 00:41:24 +01003080 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003081 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003085 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003086 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003088
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003089 if (debug_override != NULL &&
3090 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003091 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003092 return NULL;
3093 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003094
Martin v. Löwis30260a72011-10-23 17:35:46 +02003095 if (PyUnicode_READY(pathname) < 0)
3096 return NULL;
3097
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003098 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003099 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 if (cpathname == NULL) {
3102 PyErr_Format(PyExc_SystemError, "path buffer too short");
3103 return NULL;
3104 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003105 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003106}
3107
3108PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01003109"cache_from_source(path, [debug_override]) -> path\n\
3110Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003111\n\
3112The .py file does not need to exist; this simply returns the path to the\n\
3113.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3114will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3115\n\
3116If debug_override is not None, then it must be a boolean and is taken as\n\
3117the value of __debug__ instead.");
3118
3119static PyObject *
3120imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04003123 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003126 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04003127 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003129
Victor Stinnerc9abda02011-03-14 13:33:46 -04003130 source = make_source_pathname(pathname);
3131 if (source == NULL) {
3132 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04003134 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 return NULL;
3136 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04003137 Py_DECREF(pathname);
3138 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003139}
3140
3141PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01003142"source_from_cache(path) -> path\n\
3143Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003144\n\
3145The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3146the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3147does not conform to PEP 3147 format, ValueError will be raised.");
3148
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003149/* Doc strings */
3150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003151PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04003152"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003154PyDoc_STRVAR(doc_find_module,
3155"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003156Search for a module. If path is omitted or None, search for a\n\
3157built-in, frozen or special module and continue search in sys.path.\n\
3158The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003159package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003161PyDoc_STRVAR(doc_get_magic,
3162"get_magic() -> string\n\
3163Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003164
Barry Warsaw28a691b2010-04-17 00:19:56 +00003165PyDoc_STRVAR(doc_get_tag,
3166"get_tag() -> string\n\
3167Return the magic tag for .pyc or .pyo files.");
3168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003169PyDoc_STRVAR(doc_get_suffixes,
3170"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003171Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003172that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003173
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003174PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003175"lock_held() -> boolean\n\
3176Return True if the import lock is currently held, else False.\n\
3177On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003178
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003179PyDoc_STRVAR(doc_acquire_lock,
3180"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003181Acquires the interpreter's import lock for the current thread.\n\
3182This lock should be used by import hooks to ensure thread-safety\n\
3183when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003184On platforms without threads, this function does nothing.");
3185
3186PyDoc_STRVAR(doc_release_lock,
3187"release_lock() -> None\n\
3188Release the interpreter's import lock.\n\
3189On platforms without threads, this function does nothing.");
3190
Guido van Rossum79f25d91997-04-29 20:08:16 +00003191static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3193 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3194 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3195 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3197 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3198 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3199 {"reload", imp_reload, METH_O, doc_reload},
3200 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3201 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3202 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3203 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3204 /* The rest are obsolete */
3205 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3206 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3207 {"init_builtin", imp_init_builtin, METH_VARARGS},
3208 {"init_frozen", imp_init_frozen, METH_VARARGS},
3209 {"is_builtin", imp_is_builtin, METH_VARARGS},
3210 {"is_frozen", imp_is_frozen, METH_VARARGS},
3211 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003212#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003214#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07003215 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003217};
3218
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003219static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003220setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 PyObject *v;
3223 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 v = PyLong_FromLong((long)value);
3226 err = PyDict_SetItemString(d, name, v);
3227 Py_XDECREF(v);
3228 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003229}
3230
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003231typedef struct {
3232 PyObject_HEAD
3233} NullImporter;
3234
3235static int
3236NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3237{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003238#ifndef MS_WINDOWS
3239 PyObject *path;
3240 struct stat statbuf;
3241 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3244 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003245
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003246 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3247 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003249
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003250 if (PyBytes_GET_SIZE(path) == 0) {
3251 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 PyErr_SetString(PyExc_ImportError, "empty pathname");
3253 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003255
3256 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3257 Py_DECREF(path);
3258 if (rv == 0) {
3259 /* it exists */
3260 if (S_ISDIR(statbuf.st_mode)) {
3261 /* it's a directory */
3262 PyErr_SetString(PyExc_ImportError, "existing directory");
3263 return -1;
3264 }
3265 }
3266#else /* MS_WINDOWS */
3267 PyObject *pathobj;
3268 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003269 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003270
3271 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3272 return -1;
3273
3274 if (!PyArg_ParseTuple(args, "U:NullImporter",
3275 &pathobj))
3276 return -1;
3277
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003278 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003279 PyErr_SetString(PyExc_ImportError, "empty pathname");
3280 return -1;
3281 }
3282
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003283 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003284 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003285 return -1;
3286 /* see issue1293 and issue3677:
3287 * stat() on Windows doesn't recognise paths like
3288 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3289 */
3290 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003291 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003292 if (rv != INVALID_FILE_ATTRIBUTES) {
3293 /* it exists */
3294 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3295 /* it's a directory */
3296 PyErr_SetString(PyExc_ImportError, "existing directory");
3297 return -1;
3298 }
3299 }
3300#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003302}
3303
3304static PyObject *
3305NullImporter_find_module(NullImporter *self, PyObject *args)
3306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003308}
3309
3310static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3312 "Always return None"
3313 },
3314 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003315};
3316
3317
Christian Heimes9cd17752007-11-18 19:35:23 +00003318PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 PyVarObject_HEAD_INIT(NULL, 0)
3320 "imp.NullImporter", /*tp_name*/
3321 sizeof(NullImporter), /*tp_basicsize*/
3322 0, /*tp_itemsize*/
3323 0, /*tp_dealloc*/
3324 0, /*tp_print*/
3325 0, /*tp_getattr*/
3326 0, /*tp_setattr*/
3327 0, /*tp_reserved*/
3328 0, /*tp_repr*/
3329 0, /*tp_as_number*/
3330 0, /*tp_as_sequence*/
3331 0, /*tp_as_mapping*/
3332 0, /*tp_hash */
3333 0, /*tp_call*/
3334 0, /*tp_str*/
3335 0, /*tp_getattro*/
3336 0, /*tp_setattro*/
3337 0, /*tp_as_buffer*/
3338 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3339 "Null importer object", /* tp_doc */
3340 0, /* tp_traverse */
3341 0, /* tp_clear */
3342 0, /* tp_richcompare */
3343 0, /* tp_weaklistoffset */
3344 0, /* tp_iter */
3345 0, /* tp_iternext */
3346 NullImporter_methods, /* tp_methods */
3347 0, /* tp_members */
3348 0, /* tp_getset */
3349 0, /* tp_base */
3350 0, /* tp_dict */
3351 0, /* tp_descr_get */
3352 0, /* tp_descr_set */
3353 0, /* tp_dictoffset */
3354 (initproc)NullImporter_init, /* tp_init */
3355 0, /* tp_alloc */
3356 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003357};
3358
Martin v. Löwis1a214512008-06-11 05:26:20 +00003359static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04003361 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 doc_imp,
3363 0,
3364 imp_methods,
3365 NULL,
3366 NULL,
3367 NULL,
3368 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003369};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003370
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003371PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003372PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 if (PyType_Ready(&PyNullImporter_Type) < 0)
3377 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 m = PyModule_Create(&impmodule);
3380 if (m == NULL)
3381 goto failure;
3382 d = PyModule_GetDict(m);
3383 if (d == NULL)
3384 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3387 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3388 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3389 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3390 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3391 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3392 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3393 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3394 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3395 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 Py_INCREF(&PyNullImporter_Type);
3398 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3399 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003400 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 Py_XDECREF(m);
3402 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003403}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003404
3405
Guido van Rossumb18618d2000-05-03 23:44:39 +00003406/* API for embedding applications that want to add their own entries
3407 to the table of built-in modules. This should normally be called
3408 *before* Py_Initialize(). When the table resize fails, -1 is
3409 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003410
3411 After a similar function by Just van Rossum. */
3412
3413int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003414PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 static struct _inittab *our_copy = NULL;
3417 struct _inittab *p;
3418 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 /* Count the number of entries in both tables */
3421 for (n = 0; newtab[n].name != NULL; n++)
3422 ;
3423 if (n == 0)
3424 return 0; /* Nothing to do */
3425 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3426 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 /* Allocate new memory for the combined table */
3429 p = our_copy;
3430 PyMem_RESIZE(p, struct _inittab, i+n+1);
3431 if (p == NULL)
3432 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 /* Copy the tables into the new memory */
3435 if (our_copy != PyImport_Inittab)
3436 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3437 PyImport_Inittab = our_copy = p;
3438 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003441}
3442
3443/* Shorthand to add a single entry given a name and a function */
3444
3445int
Brett Cannona826f322009-04-02 03:41:46 +00003446PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 newtab[0].name = (char *)name;
3453 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003456}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003457
3458#ifdef __cplusplus
3459}
3460#endif