blob: 71485bd1eaff1307d6f2cbbd1486ddc45fbc7d25 [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
Brett Cannonfd074152012-04-14 14:10:13 -0400208 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 v = PyList_New(0);
210 if (v == NULL)
211 goto error;
212 err = PySys_SetObject("meta_path", v);
213 Py_DECREF(v);
214 if (err)
215 goto error;
216 v = PyDict_New();
217 if (v == NULL)
218 goto error;
219 err = PySys_SetObject("path_importer_cache", v);
220 Py_DECREF(v);
221 if (err)
222 goto error;
223 path_hooks = PyList_New(0);
224 if (path_hooks == NULL)
225 goto error;
226 err = PySys_SetObject("path_hooks", path_hooks);
227 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000228 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400229 PyErr_Print();
230 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Brett Cannonacf85cd2012-04-29 12:50:03 -0400231 "or path_importer_cache");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 }
Brett Cannonfd074152012-04-14 14:10:13 -0400233 Py_DECREF(path_hooks);
234}
235
236void
237_PyImportZip_Init(void)
238{
239 PyObject *path_hooks, *zimpimport;
240 int err = 0;
241
242 path_hooks = PySys_GetObject("path_hooks");
243 if (path_hooks == NULL)
244 goto error;
245
246 if (Py_VerboseFlag)
247 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 zimpimport = PyImport_ImportModule("zipimport");
250 if (zimpimport == NULL) {
251 PyErr_Clear(); /* No zip import module -- okay */
252 if (Py_VerboseFlag)
253 PySys_WriteStderr("# can't import zipimport\n");
254 }
255 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200256 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200257 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
258 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 Py_DECREF(zimpimport);
260 if (zipimporter == NULL) {
261 PyErr_Clear(); /* No zipimporter object -- okay */
262 if (Py_VerboseFlag)
263 PySys_WriteStderr(
264 "# can't import zipimport.zipimporter\n");
265 }
266 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400267 /* sys.path_hooks.insert(0, zipimporter) */
268 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400270 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400272 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (Py_VerboseFlag)
274 PySys_WriteStderr(
275 "# installed zipimport hook\n");
276 }
277 }
Brett Cannonfd074152012-04-14 14:10:13 -0400278
279 return;
280
281 error:
282 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400283 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000284}
285
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000286/* Locking primitives to prevent parallel imports of the same module
287 in different threads to return with a partially loaded module.
288 These calls are serialized by the global interpreter lock. */
289
290#ifdef WITH_THREAD
291
Guido van Rossum49b56061998-10-01 20:42:43 +0000292#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000293
Guido van Rossum65d5b571998-12-21 19:32:43 +0000294static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000295static long import_lock_thread = -1;
296static int import_lock_level = 0;
297
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000298void
299_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 long me = PyThread_get_thread_ident();
302 if (me == -1)
303 return; /* Too bad */
304 if (import_lock == NULL) {
305 import_lock = PyThread_allocate_lock();
306 if (import_lock == NULL)
307 return; /* Nothing much we can do. */
308 }
309 if (import_lock_thread == me) {
310 import_lock_level++;
311 return;
312 }
313 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
314 {
315 PyThreadState *tstate = PyEval_SaveThread();
316 PyThread_acquire_lock(import_lock, 1);
317 PyEval_RestoreThread(tstate);
318 }
319 import_lock_thread = me;
320 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000321}
322
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000323int
324_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 long me = PyThread_get_thread_ident();
327 if (me == -1 || import_lock == NULL)
328 return 0; /* Too bad */
329 if (import_lock_thread != me)
330 return -1;
331 import_lock_level--;
332 if (import_lock_level == 0) {
333 import_lock_thread = -1;
334 PyThread_release_lock(import_lock);
335 }
336 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000337}
338
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000339/* This function is called from PyOS_AfterFork to ensure that newly
340 created child processes do not share locks with the parent.
341 We now acquire the import lock around fork() calls but on some platforms
342 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000343
344void
345_PyImport_ReInitLock(void)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (import_lock != NULL)
348 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000349 if (import_lock_level > 1) {
350 /* Forked as a side effect of import */
351 long me = PyThread_get_thread_ident();
352 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100353 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000354 import_lock_thread = me;
355 import_lock_level--;
356 } else {
357 import_lock_thread = -1;
358 import_lock_level = 0;
359 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000360}
361
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000362#endif
363
Tim Peters69232342001-08-30 05:16:13 +0000364static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000365imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000366{
Tim Peters69232342001-08-30 05:16:13 +0000367#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000369#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000371#endif
372}
373
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000374static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000375imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000376{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000377#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000379#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 Py_INCREF(Py_None);
381 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000382}
383
384static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000385imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000386{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000387#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (_PyImport_ReleaseLock() < 0) {
389 PyErr_SetString(PyExc_RuntimeError,
390 "not holding the import lock");
391 return NULL;
392 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000393#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 Py_INCREF(Py_None);
395 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000396}
397
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100398void
399_PyImport_Fini(void)
400{
401 Py_XDECREF(extensions);
402 extensions = NULL;
403 PyMem_DEL(_PyImport_Filetab);
404 _PyImport_Filetab = NULL;
405#ifdef WITH_THREAD
406 if (import_lock != NULL) {
407 PyThread_free_lock(import_lock);
408 import_lock = NULL;
409 }
410#endif
411}
412
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413/* Helper for sys */
414
415PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000416PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyInterpreterState *interp = PyThreadState_GET()->interp;
419 if (interp->modules == NULL)
420 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
421 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000422}
423
Guido van Rossum3f5da241990-12-20 15:06:42 +0000424
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000425/* List of names to clear in sys */
426static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 "path", "argv", "ps1", "ps2",
428 "last_type", "last_value", "last_traceback",
429 "path_hooks", "path_importer_cache", "meta_path",
430 /* misc stuff */
431 "flags", "float_info",
432 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000433};
434
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000435static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 "stdin", "__stdin__",
437 "stdout", "__stdout__",
438 "stderr", "__stderr__",
439 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000440};
441
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000442
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000443/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000444
Guido van Rossum3f5da241990-12-20 15:06:42 +0000445void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000446PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 PyObject *key, *value, *dict;
450 PyInterpreterState *interp = PyThreadState_GET()->interp;
451 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (modules == NULL)
454 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Delete some special variables first. These are common
457 places where user values hide and people complain when their
458 destructors fail. Since the modules containing them are
459 deleted *last* of all, they would come too late in the normal
460 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 value = PyDict_GetItemString(modules, "builtins");
463 if (value != NULL && PyModule_Check(value)) {
464 dict = PyModule_GetDict(value);
465 if (Py_VerboseFlag)
466 PySys_WriteStderr("# clear builtins._\n");
467 PyDict_SetItemString(dict, "_", Py_None);
468 }
469 value = PyDict_GetItemString(modules, "sys");
470 if (value != NULL && PyModule_Check(value)) {
471 char **p;
472 PyObject *v;
473 dict = PyModule_GetDict(value);
474 for (p = sys_deletes; *p != NULL; p++) {
475 if (Py_VerboseFlag)
476 PySys_WriteStderr("# clear sys.%s\n", *p);
477 PyDict_SetItemString(dict, *p, Py_None);
478 }
479 for (p = sys_files; *p != NULL; p+=2) {
480 if (Py_VerboseFlag)
481 PySys_WriteStderr("# restore sys.%s\n", *p);
482 v = PyDict_GetItemString(dict, *(p+1));
483 if (v == NULL)
484 v = Py_None;
485 PyDict_SetItemString(dict, *p, v);
486 }
487 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* First, delete __main__ */
490 value = PyDict_GetItemString(modules, "__main__");
491 if (value != NULL && PyModule_Check(value)) {
492 if (Py_VerboseFlag)
493 PySys_WriteStderr("# cleanup __main__\n");
494 _PyModule_Clear(value);
495 PyDict_SetItemString(modules, "__main__", Py_None);
496 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* The special treatment of "builtins" here is because even
499 when it's not referenced as a module, its dictionary is
500 referenced by almost every module's __builtins__. Since
501 deleting a module clears its dictionary (even if there are
502 references left to it), we need to delete the "builtins"
503 module last. Likewise, we don't delete sys until the very
504 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Also note that we 'delete' modules by replacing their entry
507 in the modules dict with None, rather than really deleting
508 them; this avoids a rehash of the modules dictionary and
509 also marks them as "non existent" so they won't be
510 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Next, repeatedly delete modules with a reference count of
513 one (skipping builtins and sys) and delete them */
514 do {
515 ndone = 0;
516 pos = 0;
517 while (PyDict_Next(modules, &pos, &key, &value)) {
518 if (value->ob_refcnt != 1)
519 continue;
520 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100521 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100523 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 continue;
525 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100526 PySys_FormatStderr(
527 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 _PyModule_Clear(value);
529 PyDict_SetItem(modules, key, Py_None);
530 ndone++;
531 }
532 }
533 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 /* Next, delete all modules (still skipping builtins and sys) */
536 pos = 0;
537 while (PyDict_Next(modules, &pos, &key, &value)) {
538 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100539 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100541 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 continue;
543 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100544 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 _PyModule_Clear(value);
546 PyDict_SetItem(modules, key, Py_None);
547 }
548 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* Next, delete sys and builtins (in that order) */
551 value = PyDict_GetItemString(modules, "sys");
552 if (value != NULL && PyModule_Check(value)) {
553 if (Py_VerboseFlag)
554 PySys_WriteStderr("# cleanup sys\n");
555 _PyModule_Clear(value);
556 PyDict_SetItemString(modules, "sys", Py_None);
557 }
558 value = PyDict_GetItemString(modules, "builtins");
559 if (value != NULL && PyModule_Check(value)) {
560 if (Py_VerboseFlag)
561 PySys_WriteStderr("# cleanup builtins\n");
562 _PyModule_Clear(value);
563 PyDict_SetItemString(modules, "builtins", Py_None);
564 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* Finally, clear and delete the modules directory */
567 PyDict_Clear(modules);
568 interp->modules = NULL;
569 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000570}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000571
572
Barry Warsaw28a691b2010-04-17 00:19:56 +0000573/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000574
575long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000576PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000579}
580
581
Barry Warsaw28a691b2010-04-17 00:19:56 +0000582const char *
583PyImport_GetMagicTag(void)
584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000586}
587
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588/* Magic for extension modules (built-in as well as dynamically
589 loaded). To prevent initializing an extension module more than
590 once, we keep a static dictionary 'extensions' keyed by module name
591 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000592 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100593 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594 immediately after the module initialization function succeeds. A
595 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100596 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000597
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000598 Modules which do support multiple initialization set their m_size
599 field to a non-negative number (indicating the size of the
600 module-specific state). They are still recorded in the extensions
601 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000602*/
603
604int
Victor Stinner95872862011-03-07 18:20:56 +0100605_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
606 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyObject *modules, *dict;
609 struct PyModuleDef *def;
610 if (extensions == NULL) {
611 extensions = PyDict_New();
612 if (extensions == NULL)
613 return -1;
614 }
615 if (mod == NULL || !PyModule_Check(mod)) {
616 PyErr_BadInternalCall();
617 return -1;
618 }
619 def = PyModule_GetDef(mod);
620 if (!def) {
621 PyErr_BadInternalCall();
622 return -1;
623 }
624 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100625 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return -1;
627 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100628 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return -1;
630 }
631 if (def->m_size == -1) {
632 if (def->m_base.m_copy) {
633 /* Somebody already imported the module,
634 likely under a different name.
635 XXX this should really not happen. */
636 Py_DECREF(def->m_base.m_copy);
637 def->m_base.m_copy = NULL;
638 }
639 dict = PyModule_GetDict(mod);
640 if (dict == NULL)
641 return -1;
642 def->m_base.m_copy = PyDict_Copy(dict);
643 if (def->m_base.m_copy == NULL)
644 return -1;
645 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000646 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648}
649
Victor Stinner49d3f252010-10-17 01:24:53 +0000650int
651_PyImport_FixupBuiltin(PyObject *mod, char *name)
652{
653 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100654 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100655 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100656 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000657 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100658 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
659 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000660 return res;
661}
662
Guido van Rossum25ce5661997-08-02 03:10:38 +0000663PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100664_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyObject *mod, *mdict;
667 PyModuleDef* def;
668 if (extensions == NULL)
669 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000670 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (def == NULL)
672 return NULL;
673 if (def->m_size == -1) {
674 /* Module does not support repeated initialization */
675 if (def->m_base.m_copy == NULL)
676 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100677 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (mod == NULL)
679 return NULL;
680 mdict = PyModule_GetDict(mod);
681 if (mdict == NULL)
682 return NULL;
683 if (PyDict_Update(mdict, def->m_base.m_copy))
684 return NULL;
685 }
686 else {
687 if (def->m_base.m_init == NULL)
688 return NULL;
689 mod = def->m_base.m_init();
690 if (mod == NULL)
691 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100692 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_DECREF(mod);
694 }
695 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100696 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 Py_DECREF(mod);
698 return NULL;
699 }
700 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100701 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 name, filename);
703 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000704
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705}
706
Victor Stinner49d3f252010-10-17 01:24:53 +0000707PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000708_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000709{
Victor Stinner95872862011-03-07 18:20:56 +0100710 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100711 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100712 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000713 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100714 res = _PyImport_FindExtensionObject(nameobj, nameobj);
715 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000716 return res;
717}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718
719/* Get the module object corresponding to a module name.
720 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000721 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000722 Because the former action is most common, THIS DOES NOT RETURN A
723 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724
Guido van Rossum79f25d91997-04-29 20:08:16 +0000725PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000726PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyObject *modules = PyImport_GetModuleDict();
729 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000730
Victor Stinner27ee0892011-03-04 12:57:09 +0000731 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyModule_Check(m))
733 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000734 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (m == NULL)
736 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000737 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 Py_DECREF(m);
739 return NULL;
740 }
741 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000744}
745
Victor Stinner27ee0892011-03-04 12:57:09 +0000746PyObject *
747PyImport_AddModule(const char *name)
748{
749 PyObject *nameobj, *module;
750 nameobj = PyUnicode_FromString(name);
751 if (nameobj == NULL)
752 return NULL;
753 module = PyImport_AddModuleObject(nameobj);
754 Py_DECREF(nameobj);
755 return module;
756}
757
758
Tim Peters1cd70172004-08-02 03:52:12 +0000759/* Remove name from sys.modules, if it's there. */
760static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000761remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000764 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000766 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 Py_FatalError("import: deleting existing key in"
768 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000769}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000770
Victor Stinnerc9abda02011-03-14 13:33:46 -0400771static PyObject * get_sourcefile(PyObject *filename);
772static PyObject *make_source_pathname(PyObject *pathname);
Christian Heimes3b06e532008-01-07 20:12:44 +0000773
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000774/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000775 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
776 * removed from sys.modules, to avoid leaving damaged module objects
777 * in sys.modules. The caller may wish to restore the original
778 * module object (if any) in this case; PyImport_ReloadModule is an
779 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000780 *
781 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
782 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000783 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000785PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return PyImport_ExecCodeModuleWithPathnames(
788 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000789}
790
791PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000792PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 return PyImport_ExecCodeModuleWithPathnames(
795 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000796}
797
798PyObject *
799PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000801{
Victor Stinner27ee0892011-03-04 12:57:09 +0000802 PyObject *m = NULL;
803 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
804
805 nameobj = PyUnicode_FromString(name);
806 if (nameobj == NULL)
807 return NULL;
808
809 if (pathname != NULL) {
810 pathobj = PyUnicode_DecodeFSDefault(pathname);
811 if (pathobj == NULL)
812 goto error;
813 } else
814 pathobj = NULL;
815 if (cpathname != NULL) {
816 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
817 if (cpathobj == NULL)
818 goto error;
819 } else
820 cpathobj = NULL;
821 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
822error:
823 Py_DECREF(nameobj);
824 Py_XDECREF(pathobj);
825 Py_XDECREF(cpathobj);
826 return m;
827}
828
829PyObject*
830PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
831 PyObject *cpathname)
832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject *modules = PyImport_GetModuleDict();
834 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835
Victor Stinner27ee0892011-03-04 12:57:09 +0000836 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (m == NULL)
838 return NULL;
839 /* If the module is being reloaded, we get the old module back
840 and re-use its dict to exec the new code. */
841 d = PyModule_GetDict(m);
842 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
843 if (PyDict_SetItemString(d, "__builtins__",
844 PyEval_GetBuiltins()) != 0)
845 goto error;
846 }
847 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400849 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (v == NULL)
851 PyErr_Clear();
852 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000853 else
854 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (v == NULL) {
856 v = ((PyCodeObject *)co)->co_filename;
857 Py_INCREF(v);
858 }
859 if (PyDict_SetItemString(d, "__file__", v) != 0)
860 PyErr_Clear(); /* Not important enough to report */
861 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000864 if (cpathname != NULL)
865 v = cpathname;
866 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (PyDict_SetItemString(d, "__cached__", v) != 0)
869 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000870
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000871 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (v == NULL)
873 goto error;
874 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000875
Victor Stinner27ee0892011-03-04 12:57:09 +0000876 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000878 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 name);
880 return NULL;
881 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000886
887 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 remove_module(name);
889 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000890}
891
892
Martin v. Löwis2db72862011-10-23 17:29:08 +0200893/* Like rightmost_sep, but operate on unicode objects. */
894static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200895rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200896{
897 Py_ssize_t found, i;
898 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200899 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200900 c = PyUnicode_READ_CHAR(o, i);
901 if (c == SEP
902#ifdef ALTSEP
903 || c == ALTSEP
904#endif
905 )
906 {
907 found = i;
908 }
909 }
910 return found;
911}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400912
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000913
Barry Warsaw28a691b2010-04-17 00:19:56 +0000914/* Given a pathname to a Python byte compiled file, return the path to the
915 source file, if the path matches the PEP 3147 format. This does not check
916 for any file existence, however, if the pyc file name does not match PEP
917 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400918 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919
Victor Stinnerc9abda02011-03-14 13:33:46 -0400920 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
921
922static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200923make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000924{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200925 Py_ssize_t left, right, dot0, dot1, len;
926 Py_ssize_t i, j;
927 PyObject *result;
928 int kind;
929 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400930
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200931 len = PyUnicode_GET_LENGTH(path);
932 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200933 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Look back two slashes from the end. In between these two slashes
936 must be the string __pycache__ or this is not a PEP 3147 style
937 path. It's possible for there to be only one slash.
938 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200939 right = rightmost_sep_obj(path, 0, len);
940 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200942 left = rightmost_sep_obj(path, 0, right);
943 if (left == -1)
944 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 else
946 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200947 if (right-left != sizeof(CACHEDIR)-1)
948 return NULL;
949 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
950 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
951 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Now verify that the path component to the right of the last slash
954 has two dots in it.
955 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200956 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
957 if (dot0 < 0)
958 return NULL;
959 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
960 if (dot1 < 0)
961 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200963 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
964 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* This is a PEP 3147 path. Start by copying everything from the
967 start of pathname up to and including the leftmost slash. Then
968 copy the file's basename, removing the magic tag and adding a .py
969 suffix.
970 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200971 result = PyUnicode_New(left + (dot0-right) + 2,
972 PyUnicode_MAX_CHAR_VALUE(path));
973 if (!result)
974 return NULL;
975 kind = PyUnicode_KIND(result);
976 data = PyUnicode_DATA(result);
977 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
978 PyUnicode_CopyCharacters(result, left, path, right+1,
979 (j = dot0-right));
980 PyUnicode_WRITE(kind, data, i+j, 'p');
981 PyUnicode_WRITE(kind, data, i+j+1, 'y');
Victor Stinner8f825062012-04-27 13:55:39 +0200982 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200983 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000984}
985
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000986
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000987static void
988update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyObject *constants, *tmp;
991 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (PyUnicode_Compare(co->co_filename, oldname))
994 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 tmp = co->co_filename;
997 co->co_filename = newname;
998 Py_INCREF(co->co_filename);
999 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 constants = co->co_consts;
1002 n = PyTuple_GET_SIZE(constants);
1003 for (i = 0; i < n; i++) {
1004 tmp = PyTuple_GET_ITEM(constants, i);
1005 if (PyCode_Check(tmp))
1006 update_code_filenames((PyCodeObject *)tmp,
1007 oldname, newname);
1008 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001009}
1010
Victor Stinner2f42ae52011-03-20 00:41:24 +01001011static void
1012update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001013{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001014 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001015
Victor Stinner2f42ae52011-03-20 00:41:24 +01001016 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1017 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 oldname = co->co_filename;
1020 Py_INCREF(oldname);
1021 update_code_filenames(co, oldname, newname);
1022 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001023}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001024
Brett Cannon442c9b92011-03-23 16:14:42 -07001025static PyObject *
1026imp_fix_co_filename(PyObject *self, PyObject *args)
1027{
1028 PyObject *co;
1029 PyObject *file_path;
1030
1031 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1032 return NULL;
1033
1034 if (!PyCode_Check(co)) {
1035 PyErr_SetString(PyExc_TypeError,
1036 "first argument must be a code object");
1037 return NULL;
1038 }
1039
1040 if (!PyUnicode_Check(file_path)) {
1041 PyErr_SetString(PyExc_TypeError,
1042 "second argument must be a string");
1043 return NULL;
1044 }
1045
1046 update_compiled_module((PyCodeObject*)co, file_path);
1047
1048 Py_RETURN_NONE;
1049}
1050
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001051
Christian Heimes3b06e532008-01-07 20:12:44 +00001052/* Get source file -> unicode or None
1053 * Returns the path to the py file if available, else the given path
1054 */
1055static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001056get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001060 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001062 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001064 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001065 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001067
Victor Stinnerc9abda02011-03-14 13:33:46 -04001068 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001069 fileuni = PyUnicode_AsUCS4Copy(filename);
1070 if (!fileuni)
1071 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001072 if (len < 5
1073 || fileuni[len-4] != '.'
1074 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1075 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1076 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 /* Start by trying to turn PEP 3147 path into source path. If that
1079 * fails, just chop off the trailing character, i.e. legacy pyc path
1080 * to py.
1081 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001082 py = make_source_pathname(filename);
1083 if (py == NULL) {
1084 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001087 if (py == NULL)
1088 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001089
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001090 err = _Py_stat(py, &statbuf);
1091 if (err == -2)
1092 goto error;
1093 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001094 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001095 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001096 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001097 Py_DECREF(py);
1098 goto unchanged;
1099
1100error:
1101 PyErr_Clear();
1102unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001103 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001104 Py_INCREF(filename);
1105 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001106}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001107
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001108/* Forward */
Victor Stinner53dc7352011-03-20 01:50:21 +01001109static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001110
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001111
1112/* Helper to test for built-in module */
1113
1114static int
Victor Stinner95872862011-03-07 18:20:56 +01001115is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001116{
Victor Stinner95872862011-03-07 18:20:56 +01001117 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001119 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1120 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (PyImport_Inittab[i].initfunc == NULL)
1122 return -1;
1123 else
1124 return 1;
1125 }
1126 }
1127 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001128}
1129
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001130
Just van Rossum52e14d62002-12-30 22:08:05 +00001131/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1132 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001133 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001134 that can handle the path item. Return None if no hook could;
1135 this tells our caller it should fall back to the builtin
1136 import mechanism. Cache the result in path_importer_cache.
1137 Returns a borrowed reference. */
1138
1139static PyObject *
1140get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *importer;
1144 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 /* These conditions are the caller's responsibility: */
1147 assert(PyList_Check(path_hooks));
1148 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 nhooks = PyList_Size(path_hooks);
1151 if (nhooks < 0)
1152 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 importer = PyDict_GetItem(path_importer_cache, p);
1155 if (importer != NULL)
1156 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 /* set path_importer_cache[p] to None to avoid recursion */
1159 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1160 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 for (j = 0; j < nhooks; j++) {
1163 PyObject *hook = PyList_GetItem(path_hooks, j);
1164 if (hook == NULL)
1165 return NULL;
1166 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1167 if (importer != NULL)
1168 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1171 return NULL;
1172 }
1173 PyErr_Clear();
1174 }
1175 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001176 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 }
1178 if (importer != NULL) {
1179 int err = PyDict_SetItem(path_importer_cache, p, importer);
1180 Py_DECREF(importer);
1181 if (err != 0)
1182 return NULL;
1183 }
1184 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001185}
1186
Christian Heimes9cd17752007-11-18 19:35:23 +00001187PyAPI_FUNC(PyObject *)
1188PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1192 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1193 importer = get_path_importer(path_importer_cache,
1194 path_hooks, path);
1195 }
1196 }
1197 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1198 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001199}
1200
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001201
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001202#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001203extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1204 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001205#endif
1206
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001207
Victor Stinner95872862011-03-07 18:20:56 +01001208static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001209
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001210/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001211 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001212 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001213
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001214static int
Victor Stinner95872862011-03-07 18:20:56 +01001215init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001218
Victor Stinner95872862011-03-07 18:20:56 +01001219 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 for (p = PyImport_Inittab; p->name != NULL; p++) {
1223 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001224 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001225 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (p->initfunc == NULL) {
1227 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001228 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 name);
1230 return -1;
1231 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 mod = (*p->initfunc)();
1233 if (mod == 0)
1234 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001235 /* Remember pointer to module init function. */
1236 def = PyModule_GetDef(mod);
1237 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001238 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return -1;
1240 /* FixupExtension has put the module into sys.modules,
1241 so we can release our own reference. */
1242 Py_DECREF(mod);
1243 return 1;
1244 }
1245 }
1246 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001247}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001248
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001249
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001250/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001251
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001252static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001253find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001256
Victor Stinner53dc7352011-03-20 01:50:21 +01001257 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 for (p = PyImport_FrozenModules; ; p++) {
1261 if (p->name == NULL)
1262 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001263 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 break;
1265 }
1266 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001267}
1268
Guido van Rossum79f25d91997-04-29 20:08:16 +00001269static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001270get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 struct _frozen *p = find_frozen(name);
1273 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (p == NULL) {
1276 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001277 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 name);
1279 return NULL;
1280 }
1281 if (p->code == NULL) {
1282 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001283 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 name);
1285 return NULL;
1286 }
1287 size = p->size;
1288 if (size < 0)
1289 size = -size;
1290 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001291}
1292
Brett Cannon8d110132009-03-15 02:20:16 +00001293static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001294is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 struct _frozen *p = find_frozen(name);
1297 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (p == NULL) {
1300 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001301 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 name);
1303 return NULL;
1304 }
Brett Cannon8d110132009-03-15 02:20:16 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (size < 0)
1309 Py_RETURN_TRUE;
1310 else
1311 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001312}
1313
1314
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001315/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001316 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001317 an exception set if the initialization failed.
1318 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001319
1320int
Victor Stinner53dc7352011-03-20 01:50:21 +01001321PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001322{
Victor Stinner53dc7352011-03-20 01:50:21 +01001323 struct _frozen *p;
1324 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 int ispackage;
1326 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001327
Victor Stinner53dc7352011-03-20 01:50:21 +01001328 p = find_frozen(name);
1329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (p == NULL)
1331 return 0;
1332 if (p->code == NULL) {
1333 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001334 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 name);
1336 return -1;
1337 }
1338 size = p->size;
1339 ispackage = (size < 0);
1340 if (ispackage)
1341 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1343 if (co == NULL)
1344 return -1;
1345 if (!PyCode_Check(co)) {
1346 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001347 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 name);
1349 goto err_return;
1350 }
1351 if (ispackage) {
1352 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01001353 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001355 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 if (m == NULL)
1357 goto err_return;
1358 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 l = PyList_New(1);
1360 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 goto err_return;
1362 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001363 Py_INCREF(name);
1364 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 err = PyDict_SetItemString(d, "__path__", l);
1366 Py_DECREF(l);
1367 if (err != 0)
1368 goto err_return;
1369 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001370 path = PyUnicode_FromString("<frozen>");
1371 if (path == NULL)
1372 goto err_return;
1373 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1374 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (m == NULL)
1376 goto err_return;
1377 Py_DECREF(co);
1378 Py_DECREF(m);
1379 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001380err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 Py_DECREF(co);
1382 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001383}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001384
Victor Stinner53dc7352011-03-20 01:50:21 +01001385int
1386PyImport_ImportFrozenModule(char *name)
1387{
1388 PyObject *nameobj;
1389 int ret;
1390 nameobj = PyUnicode_InternFromString(name);
1391 if (nameobj == NULL)
1392 return -1;
1393 ret = PyImport_ImportFrozenModuleObject(nameobj);
1394 Py_DECREF(nameobj);
1395 return ret;
1396}
1397
Guido van Rossum74e6a111994-08-29 12:54:38 +00001398
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001399/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001400 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001401
Guido van Rossum79f25d91997-04-29 20:08:16 +00001402PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001403PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyObject *pname;
1406 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 pname = PyUnicode_FromString(name);
1409 if (pname == NULL)
1410 return NULL;
1411 result = PyImport_Import(pname);
1412 Py_DECREF(pname);
1413 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001414}
1415
Christian Heimes072c0f12008-01-03 23:01:04 +00001416/* Import a module without blocking
1417 *
1418 * At first it tries to fetch the module from sys.modules. If the module was
1419 * never loaded before it loads it with PyImport_ImportModule() unless another
1420 * thread holds the import lock. In the latter case the function raises an
1421 * ImportError instead of blocking.
1422 *
1423 * Returns the module object with incremented ref count.
1424 */
1425PyObject *
1426PyImport_ImportModuleNoBlock(const char *name)
1427{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001428 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02001429#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02001431#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 /* Try to get the module from sys.modules[name] */
1434 modules = PyImport_GetModuleDict();
1435 if (modules == NULL)
1436 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001437
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001438 nameobj = PyUnicode_FromString(name);
1439 if (nameobj == NULL)
1440 return NULL;
1441 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001443 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 Py_INCREF(result);
1445 return result;
1446 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001447 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001448#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 /* check the import lock
1450 * me might be -1 but I ignore the error here, the lock function
1451 * takes care of the problem */
1452 me = PyThread_get_thread_ident();
1453 if (import_lock_thread == -1 || import_lock_thread == me) {
1454 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001455 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 }
1457 else {
1458 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04001459 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001461 nameobj);
1462 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001464#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001465 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001466#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001467 Py_DECREF(nameobj);
1468 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00001469}
1470
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001471
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001472PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001473PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1474 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001475 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001476{
Brett Cannonfd074152012-04-14 14:10:13 -04001477 _Py_IDENTIFIER(__import__);
1478 _Py_IDENTIFIER(__package__);
1479 _Py_IDENTIFIER(__path__);
1480 _Py_IDENTIFIER(__name__);
1481 _Py_IDENTIFIER(_find_and_load);
1482 _Py_IDENTIFIER(_handle_fromlist);
1483 _Py_static_string(single_dot, ".");
1484 PyObject *abs_name = NULL;
1485 PyObject *builtins_import = NULL;
1486 PyObject *final_mod = NULL;
1487 PyObject *mod = NULL;
1488 PyObject *package = NULL;
1489 PyObject *globals = NULL;
1490 PyObject *fromlist = NULL;
1491 PyInterpreterState *interp = PyThreadState_GET()->interp;
1492
1493 /* Make sure to use default values so as to not have
1494 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1495 NULL argument. */
1496 if (given_globals == NULL) {
1497 globals = PyDict_New();
1498 if (globals == NULL) {
1499 goto error;
1500 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 }
Brett Cannonfd074152012-04-14 14:10:13 -04001502 else {
1503 /* Only have to care what given_globals is if it will be used
1504 fortsomething. */
1505 if (level > 0 && !PyDict_Check(given_globals)) {
1506 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1507 goto error;
1508 }
1509 globals = given_globals;
1510 Py_INCREF(globals);
1511 }
1512
1513 if (given_fromlist == NULL) {
1514 fromlist = PyList_New(0);
1515 if (fromlist == NULL) {
1516 goto error;
1517 }
1518 }
1519 else {
1520 fromlist = given_fromlist;
1521 Py_INCREF(fromlist);
1522 }
1523 if (name == NULL) {
1524 PyErr_SetString(PyExc_ValueError, "Empty module name");
1525 goto error;
1526 }
1527
1528 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1529 for added performance. */
1530
1531 if (!PyUnicode_Check(name)) {
1532 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1533 goto error;
1534 }
1535 else if (PyUnicode_READY(name) < 0) {
1536 goto error;
1537 }
1538 if (level < 0) {
1539 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1540 goto error;
1541 }
1542 else if (level > 0) {
1543 package = _PyDict_GetItemId(globals, &PyId___package__);
1544 if (package != NULL && package != Py_None) {
1545 Py_INCREF(package);
1546 if (!PyUnicode_Check(package)) {
1547 PyErr_SetString(PyExc_TypeError, "package must be a string");
1548 goto error;
1549 }
1550 }
1551 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001552 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001553 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001554 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001555 goto error;
1556 }
1557 else if (!PyUnicode_Check(package)) {
1558 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1559 }
1560 Py_INCREF(package);
1561
1562 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001563 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001564 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1565 if (borrowed_dot == NULL) {
1566 goto error;
1567 }
Brett Cannon740fce02012-04-14 14:23:49 -04001568 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001569 Py_DECREF(package);
1570 if (partition == NULL) {
1571 goto error;
1572 }
1573 package = PyTuple_GET_ITEM(partition, 0);
1574 Py_INCREF(package);
1575 Py_DECREF(partition);
1576 }
1577 }
1578
1579 if (PyDict_GetItem(interp->modules, package) == NULL) {
1580 PyErr_Format(PyExc_SystemError,
1581 "Parent module %R not loaded, cannot perform relative "
1582 "import", package);
1583 goto error;
1584 }
1585 }
1586 else { /* level == 0 */
1587 if (PyUnicode_GET_LENGTH(name) == 0) {
1588 PyErr_SetString(PyExc_ValueError, "Empty module name");
1589 goto error;
1590 }
1591 package = Py_None;
1592 Py_INCREF(package);
1593 }
1594
1595 if (level > 0) {
1596 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1597 PyObject *base = NULL;
1598 int level_up = 1;
1599
1600 for (level_up = 1; level_up < level; level_up += 1) {
1601 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1602 if (last_dot == -2) {
1603 goto error;
1604 }
1605 else if (last_dot == -1) {
1606 PyErr_SetString(PyExc_ValueError,
1607 "attempted relative import beyond top-level "
1608 "package");
1609 goto error;
1610 }
1611 }
1612 base = PyUnicode_Substring(package, 0, last_dot);
1613 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001614 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001615
1616 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001617 seq = PyTuple_Pack(2, base, name);
1618 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001619 if (borrowed_dot == NULL || seq == NULL) {
1620 goto error;
1621 }
1622
1623 abs_name = PyUnicode_Join(borrowed_dot, seq);
1624 Py_DECREF(seq);
1625 if (abs_name == NULL) {
1626 goto error;
1627 }
1628 }
1629 else {
1630 abs_name = base;
1631 }
1632 }
1633 else {
1634 abs_name = name;
1635 Py_INCREF(abs_name);
1636 }
1637
Brian Curtine6b299f2012-04-14 14:19:33 -05001638#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001639 _PyImport_AcquireLock();
1640#endif
1641 /* From this point forward, goto error_with_unlock! */
1642 if (PyDict_Check(globals)) {
1643 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1644 }
1645 if (builtins_import == NULL) {
1646 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1647 if (builtins_import == NULL) {
1648 Py_FatalError("__import__ missing");
1649 }
1650 }
1651 Py_INCREF(builtins_import);
1652
1653 mod = PyDict_GetItem(interp->modules, abs_name);
1654 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001655 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1656 "None in sys.modules", abs_name);
1657 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05001658 PyErr_SetImportError(msg, abs_name, NULL);
1659 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001660 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001661 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001662 goto error_with_unlock;
1663 }
1664 else if (mod != NULL) {
1665 Py_INCREF(mod);
1666 }
1667 else {
1668 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1669 &PyId__find_and_load, abs_name,
1670 builtins_import, NULL);
1671 if (mod == NULL) {
1672 goto error_with_unlock;
1673 }
1674 }
1675
1676 if (PyObject_Not(fromlist)) {
1677 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1678 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001679 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001680 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1681
1682 if (borrowed_dot == NULL) {
1683 goto error_with_unlock;
1684 }
1685
Brian Curtine6b299f2012-04-14 14:19:33 -05001686 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001687 if (partition == NULL) {
1688 goto error_with_unlock;
1689 }
1690
1691 front = PyTuple_GET_ITEM(partition, 0);
1692 Py_INCREF(front);
1693 Py_DECREF(partition);
1694
1695 if (level == 0) {
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001696 final_mod = PyDict_GetItem(interp->modules, front);
Brett Cannon881535b2012-04-15 15:24:04 -04001697 Py_DECREF(front);
1698 if (final_mod == NULL) {
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001699 PyErr_Format(PyExc_KeyError,
1700 "%R not in sys.modules as expected", front);
Brett Cannon881535b2012-04-15 15:24:04 -04001701 }
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001702 else {
1703 Py_INCREF(final_mod);
1704 }
Brett Cannonfd074152012-04-14 14:10:13 -04001705 }
1706 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001707 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1708 PyUnicode_GET_LENGTH(front);
1709 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001710 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001711 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001712 Py_DECREF(front);
1713 if (to_return == NULL) {
1714 goto error_with_unlock;
1715 }
Brett Cannonfd074152012-04-14 14:10:13 -04001716
1717 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001718 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001719 if (final_mod == NULL) {
1720 PyErr_Format(PyExc_KeyError,
1721 "%R not in sys.modules as expected",
1722 to_return);
1723 }
1724 else {
1725 Py_INCREF(final_mod);
1726 }
Brett Cannonfd074152012-04-14 14:10:13 -04001727 }
1728 }
1729 else {
1730 final_mod = mod;
1731 Py_INCREF(mod);
1732 }
1733 }
1734 else {
1735 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1736 &PyId__handle_fromlist, mod,
1737 fromlist, builtins_import,
1738 NULL);
1739 }
1740 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001741#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001742 if (_PyImport_ReleaseLock() < 0) {
1743 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1744 }
1745#endif
1746 error:
1747 Py_XDECREF(abs_name);
1748 Py_XDECREF(builtins_import);
1749 Py_XDECREF(mod);
1750 Py_XDECREF(package);
1751 Py_XDECREF(globals);
1752 Py_XDECREF(fromlist);
1753 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001754}
1755
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001756PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001757PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001758 PyObject *fromlist, int level)
1759{
1760 PyObject *nameobj, *mod;
1761 nameobj = PyUnicode_FromString(name);
1762 if (nameobj == NULL)
1763 return NULL;
1764 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1765 fromlist, level);
1766 Py_DECREF(nameobj);
1767 return mod;
1768}
1769
1770
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001771/* Re-import a module of any kind and return its module object, WITH
1772 INCREMENTED REFERENCE COUNT */
1773
Guido van Rossum79f25d91997-04-29 20:08:16 +00001774PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001775PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776{
Brett Cannon62228db2012-04-29 14:38:11 -04001777 _Py_IDENTIFIER(reload);
1778 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001780 PyObject *imp = PyDict_GetItemString(modules, "imp");
1781 if (imp == NULL) {
1782 imp = PyImport_ImportModule("imp");
1783 if (imp == NULL) {
1784 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
Brett Cannon62228db2012-04-29 14:38:11 -04001787 else {
1788 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001790
Brett Cannon62228db2012-04-29 14:38:11 -04001791 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1792 Py_DECREF(imp);
1793 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001794}
1795
1796
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001797/* Higher-level import emulator which emulates the "import" statement
1798 more accurately -- it invokes the __import__() function from the
1799 builtins of the current globals. This means that the import is
1800 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001801 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001802 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001803 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001804 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001805
1806PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001807PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 static PyObject *silly_list = NULL;
1810 static PyObject *builtins_str = NULL;
1811 static PyObject *import_str = NULL;
1812 PyObject *globals = NULL;
1813 PyObject *import = NULL;
1814 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001815 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 /* Initialize constant string objects */
1819 if (silly_list == NULL) {
1820 import_str = PyUnicode_InternFromString("__import__");
1821 if (import_str == NULL)
1822 return NULL;
1823 builtins_str = PyUnicode_InternFromString("__builtins__");
1824 if (builtins_str == NULL)
1825 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001826 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (silly_list == NULL)
1828 return NULL;
1829 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* Get the builtins from current globals */
1832 globals = PyEval_GetGlobals();
1833 if (globals != NULL) {
1834 Py_INCREF(globals);
1835 builtins = PyObject_GetItem(globals, builtins_str);
1836 if (builtins == NULL)
1837 goto err;
1838 }
1839 else {
1840 /* No globals -- use standard builtins, and fake globals */
1841 builtins = PyImport_ImportModuleLevel("builtins",
1842 NULL, NULL, NULL, 0);
1843 if (builtins == NULL)
1844 return NULL;
1845 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1846 if (globals == NULL)
1847 goto err;
1848 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 /* Get the __import__ function from the builtins */
1851 if (PyDict_Check(builtins)) {
1852 import = PyObject_GetItem(builtins, import_str);
1853 if (import == NULL)
1854 PyErr_SetObject(PyExc_KeyError, import_str);
1855 }
1856 else
1857 import = PyObject_GetAttr(builtins, import_str);
1858 if (import == NULL)
1859 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001862 Always use absolute import here.
1863 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1865 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001866 if (r == NULL)
1867 goto err;
1868 Py_DECREF(r);
1869
1870 modules = PyImport_GetModuleDict();
1871 r = PyDict_GetItem(modules, module_name);
1872 if (r != NULL)
1873 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001874
1875 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 Py_XDECREF(globals);
1877 Py_XDECREF(builtins);
1878 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001881}
1882
1883
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001884/* Module 'imp' provides Python access to the primitives used for
1885 importing modules.
1886*/
1887
Guido van Rossum79f25d91997-04-29 20:08:16 +00001888static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001889imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 buf[0] = (char) ((magic >> 0) & 0xff);
1894 buf[1] = (char) ((magic >> 8) & 0xff);
1895 buf[2] = (char) ((magic >> 16) & 0xff);
1896 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00001899}
Barry Warsaw28a691b2010-04-17 00:19:56 +00001900
1901static PyObject *
1902imp_get_magic(PyObject *self, PyObject *noargs)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001905}
1906
1907static PyObject *
1908imp_get_tag(PyObject *self, PyObject *noargs)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001911}
1912
Guido van Rossum79f25d91997-04-29 20:08:16 +00001913static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00001914imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 PyObject *list;
1917 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 list = PyList_New(0);
1920 if (list == NULL)
1921 return NULL;
1922 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1923 PyObject *item = Py_BuildValue("ssi",
1924 fdp->suffix, fdp->mode, fdp->type);
1925 if (item == NULL) {
1926 Py_DECREF(list);
1927 return NULL;
1928 }
1929 if (PyList_Append(list, item) < 0) {
1930 Py_DECREF(list);
1931 Py_DECREF(item);
1932 return NULL;
1933 }
1934 Py_DECREF(item);
1935 }
1936 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001937}
1938
Guido van Rossum79f25d91997-04-29 20:08:16 +00001939static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001940imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001941{
Victor Stinner95872862011-03-07 18:20:56 +01001942 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 int ret;
1944 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01001945 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 return NULL;
1947 ret = init_builtin(name);
1948 if (ret < 0)
1949 return NULL;
1950 if (ret == 0) {
1951 Py_INCREF(Py_None);
1952 return Py_None;
1953 }
Victor Stinner95872862011-03-07 18:20:56 +01001954 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 Py_XINCREF(m);
1956 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001957}
1958
Guido van Rossum79f25d91997-04-29 20:08:16 +00001959static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001960imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001961{
Victor Stinner53dc7352011-03-20 01:50:21 +01001962 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 int ret;
1964 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01001965 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001967 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 if (ret < 0)
1969 return NULL;
1970 if (ret == 0) {
1971 Py_INCREF(Py_None);
1972 return Py_None;
1973 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001974 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 Py_XINCREF(m);
1976 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001977}
1978
Guido van Rossum79f25d91997-04-29 20:08:16 +00001979static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001980imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001981{
Victor Stinner53dc7352011-03-20 01:50:21 +01001982 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00001983
Victor Stinner53dc7352011-03-20 01:50:21 +01001984 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 return NULL;
1986 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001987}
1988
Guido van Rossum79f25d91997-04-29 20:08:16 +00001989static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00001990imp_is_frozen_package(PyObject *self, PyObject *args)
1991{
Victor Stinner53dc7352011-03-20 01:50:21 +01001992 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00001993
Victor Stinner53dc7352011-03-20 01:50:21 +01001994 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 return NULL;
1996 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001997}
1998
1999static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002000imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002001{
Victor Stinner95872862011-03-07 18:20:56 +01002002 PyObject *name;
2003 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 return NULL;
2005 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002006}
2007
Guido van Rossum79f25d91997-04-29 20:08:16 +00002008static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002009imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002010{
Victor Stinner53dc7352011-03-20 01:50:21 +01002011 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01002013 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 return NULL;
2015 p = find_frozen(name);
2016 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002017}
2018
2019static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01002020get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 FILE *fp;
2023 if (mode[0] == 'U')
2024 mode = "r" PY_STDIOTEXTMODE;
2025 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01002026 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01002027 if (!fp) {
2028 if (!PyErr_Occurred())
2029 PyErr_SetFromErrno(PyExc_IOError);
2030 return NULL;
2031 }
2032 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 }
2034 else {
2035 int fd = PyObject_AsFileDescriptor(fob);
2036 if (fd == -1)
2037 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01002038 if (!_PyVerify_fd(fd)) {
2039 PyErr_SetFromErrno(PyExc_IOError);
2040 return NULL;
2041 }
2042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 /* the FILE struct gets a new fd, so that it can be closed
2044 * independently of the file descriptor given
2045 */
2046 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01002047 if (fd == -1) {
2048 PyErr_SetFromErrno(PyExc_IOError);
2049 return NULL;
2050 }
2051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01002053 if (!fp) {
2054 PyErr_SetFromErrno(PyExc_IOError);
2055 return NULL;
2056 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01002058 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002059}
2060
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002061#ifdef HAVE_DYNAMIC_LOADING
2062
Guido van Rossum79f25d91997-04-29 20:08:16 +00002063static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002064imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002065{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002066 PyObject *name, *pathname, *fob = NULL, *mod;
2067 FILE *fp;
2068
2069 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
2070 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002072 if (fob != NULL) {
2073 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002074 if (fp == NULL) {
2075 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002079 else
2080 fp = NULL;
2081 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002082 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (fp)
2084 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002085 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002086}
2087
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002088#endif /* HAVE_DYNAMIC_LOADING */
2089
Barry Warsaw28a691b2010-04-17 00:19:56 +00002090
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002091/* Doc strings */
2092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002093PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002094"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002096PyDoc_STRVAR(doc_get_magic,
2097"get_magic() -> string\n\
2098Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002099
Barry Warsaw28a691b2010-04-17 00:19:56 +00002100PyDoc_STRVAR(doc_get_tag,
2101"get_tag() -> string\n\
2102Return the magic tag for .pyc or .pyo files.");
2103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002104PyDoc_STRVAR(doc_get_suffixes,
2105"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002106Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002107that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002108
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002109PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002110"lock_held() -> boolean\n\
2111Return True if the import lock is currently held, else False.\n\
2112On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002113
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002114PyDoc_STRVAR(doc_acquire_lock,
2115"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002116Acquires the interpreter's import lock for the current thread.\n\
2117This lock should be used by import hooks to ensure thread-safety\n\
2118when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002119On platforms without threads, this function does nothing.");
2120
2121PyDoc_STRVAR(doc_release_lock,
2122"release_lock() -> None\n\
2123Release the interpreter's import lock.\n\
2124On platforms without threads, this function does nothing.");
2125
Guido van Rossum79f25d91997-04-29 20:08:16 +00002126static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2128 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
2129 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2131 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2132 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2134 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
2135 {"init_builtin", imp_init_builtin, METH_VARARGS},
2136 {"init_frozen", imp_init_frozen, METH_VARARGS},
2137 {"is_builtin", imp_is_builtin, METH_VARARGS},
2138 {"is_frozen", imp_is_frozen, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002139#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002141#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07002142 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002144};
2145
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002146static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002147setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyObject *v;
2150 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 v = PyLong_FromLong((long)value);
2153 err = PyDict_SetItemString(d, name, v);
2154 Py_XDECREF(v);
2155 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002156}
2157
Martin v. Löwis1a214512008-06-11 05:26:20 +00002158static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002160 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 doc_imp,
2162 0,
2163 imp_methods,
2164 NULL,
2165 NULL,
2166 NULL,
2167 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002168};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002169
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002170PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002171PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 m = PyModule_Create(&impmodule);
2176 if (m == NULL)
2177 goto failure;
2178 d = PyModule_GetDict(m);
2179 if (d == NULL)
2180 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2183 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2184 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2185 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2186 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2187 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2188 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2189 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2190 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2191 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002194 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 Py_XDECREF(m);
2196 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002197}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002198
2199
Guido van Rossumb18618d2000-05-03 23:44:39 +00002200/* API for embedding applications that want to add their own entries
2201 to the table of built-in modules. This should normally be called
2202 *before* Py_Initialize(). When the table resize fails, -1 is
2203 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002204
2205 After a similar function by Just van Rossum. */
2206
2207int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002208PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 static struct _inittab *our_copy = NULL;
2211 struct _inittab *p;
2212 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 /* Count the number of entries in both tables */
2215 for (n = 0; newtab[n].name != NULL; n++)
2216 ;
2217 if (n == 0)
2218 return 0; /* Nothing to do */
2219 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2220 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Allocate new memory for the combined table */
2223 p = our_copy;
2224 PyMem_RESIZE(p, struct _inittab, i+n+1);
2225 if (p == NULL)
2226 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Copy the tables into the new memory */
2229 if (our_copy != PyImport_Inittab)
2230 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2231 PyImport_Inittab = our_copy = p;
2232 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002235}
2236
2237/* Shorthand to add a single entry given a name and a function */
2238
2239int
Brett Cannona826f322009-04-02 03:41:46 +00002240PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 newtab[0].name = (char *)name;
2247 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002250}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002251
2252#ifdef __cplusplus
2253}
2254#endif