blob: 8349b776c60be1e51cdd3dd3b04cccd964923408 [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
Victor Stinnerd0296212011-03-14 14:04:10 -0400143static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000145/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146
147void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000148_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Victor Stinnerd0296212011-03-14 14:04:10 -0400150 initstr = PyUnicode_InternFromString("__init__");
151 if (initstr == NULL)
152 Py_FatalError("Can't initialize import variables");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Guido van Rossum25ce5661997-08-02 03:10:38 +0000155void
Just van Rossum52e14d62002-12-30 22:08:05 +0000156_PyImportHooks_Init(void)
157{
Brett Cannonfd074152012-04-14 14:10:13 -0400158 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000160
Brett Cannonfd074152012-04-14 14:10:13 -0400161 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 v = PyList_New(0);
163 if (v == NULL)
164 goto error;
165 err = PySys_SetObject("meta_path", v);
166 Py_DECREF(v);
167 if (err)
168 goto error;
169 v = PyDict_New();
170 if (v == NULL)
171 goto error;
172 err = PySys_SetObject("path_importer_cache", v);
173 Py_DECREF(v);
174 if (err)
175 goto error;
176 path_hooks = PyList_New(0);
177 if (path_hooks == NULL)
178 goto error;
179 err = PySys_SetObject("path_hooks", path_hooks);
180 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000181 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400182 PyErr_Print();
183 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Brett Cannonacf85cd2012-04-29 12:50:03 -0400184 "or path_importer_cache");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 }
Brett Cannonfd074152012-04-14 14:10:13 -0400186 Py_DECREF(path_hooks);
187}
188
189void
190_PyImportZip_Init(void)
191{
192 PyObject *path_hooks, *zimpimport;
193 int err = 0;
194
195 path_hooks = PySys_GetObject("path_hooks");
196 if (path_hooks == NULL)
197 goto error;
198
199 if (Py_VerboseFlag)
200 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 zimpimport = PyImport_ImportModule("zipimport");
203 if (zimpimport == NULL) {
204 PyErr_Clear(); /* No zip import module -- okay */
205 if (Py_VerboseFlag)
206 PySys_WriteStderr("# can't import zipimport\n");
207 }
208 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200209 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200210 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
211 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_DECREF(zimpimport);
213 if (zipimporter == NULL) {
214 PyErr_Clear(); /* No zipimporter object -- okay */
215 if (Py_VerboseFlag)
216 PySys_WriteStderr(
217 "# can't import zipimport.zipimporter\n");
218 }
219 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400220 /* sys.path_hooks.insert(0, zipimporter) */
221 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400223 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400225 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (Py_VerboseFlag)
227 PySys_WriteStderr(
228 "# installed zipimport hook\n");
229 }
230 }
Brett Cannonfd074152012-04-14 14:10:13 -0400231
232 return;
233
234 error:
235 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400236 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000237}
238
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000239/* Locking primitives to prevent parallel imports of the same module
240 in different threads to return with a partially loaded module.
241 These calls are serialized by the global interpreter lock. */
242
243#ifdef WITH_THREAD
244
Guido van Rossum49b56061998-10-01 20:42:43 +0000245#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000246
Guido van Rossum65d5b571998-12-21 19:32:43 +0000247static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000248static long import_lock_thread = -1;
249static int import_lock_level = 0;
250
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000251void
252_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 long me = PyThread_get_thread_ident();
255 if (me == -1)
256 return; /* Too bad */
257 if (import_lock == NULL) {
258 import_lock = PyThread_allocate_lock();
259 if (import_lock == NULL)
260 return; /* Nothing much we can do. */
261 }
262 if (import_lock_thread == me) {
263 import_lock_level++;
264 return;
265 }
266 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
267 {
268 PyThreadState *tstate = PyEval_SaveThread();
269 PyThread_acquire_lock(import_lock, 1);
270 PyEval_RestoreThread(tstate);
271 }
272 import_lock_thread = me;
273 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000274}
275
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000276int
277_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 long me = PyThread_get_thread_ident();
280 if (me == -1 || import_lock == NULL)
281 return 0; /* Too bad */
282 if (import_lock_thread != me)
283 return -1;
284 import_lock_level--;
285 if (import_lock_level == 0) {
286 import_lock_thread = -1;
287 PyThread_release_lock(import_lock);
288 }
289 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290}
291
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000292/* This function is called from PyOS_AfterFork to ensure that newly
293 created child processes do not share locks with the parent.
294 We now acquire the import lock around fork() calls but on some platforms
295 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000296
297void
298_PyImport_ReInitLock(void)
299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (import_lock != NULL)
301 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000302 if (import_lock_level > 1) {
303 /* Forked as a side effect of import */
304 long me = PyThread_get_thread_ident();
305 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100306 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000307 import_lock_thread = me;
308 import_lock_level--;
309 } else {
310 import_lock_thread = -1;
311 import_lock_level = 0;
312 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000313}
314
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000315#endif
316
Tim Peters69232342001-08-30 05:16:13 +0000317static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000318imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000319{
Tim Peters69232342001-08-30 05:16:13 +0000320#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000322#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000324#endif
325}
326
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000327static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000328imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000329{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000330#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 Py_INCREF(Py_None);
334 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000335}
336
337static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000338imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000339{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000340#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (_PyImport_ReleaseLock() < 0) {
342 PyErr_SetString(PyExc_RuntimeError,
343 "not holding the import lock");
344 return NULL;
345 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000346#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 Py_INCREF(Py_None);
348 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000349}
350
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100351void
352_PyImport_Fini(void)
353{
354 Py_XDECREF(extensions);
355 extensions = NULL;
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100356#ifdef WITH_THREAD
357 if (import_lock != NULL) {
358 PyThread_free_lock(import_lock);
359 import_lock = NULL;
360 }
361#endif
362}
363
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364/* Helper for sys */
365
366PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000367PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 PyInterpreterState *interp = PyThreadState_GET()->interp;
370 if (interp->modules == NULL)
371 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
372 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373}
374
Guido van Rossum3f5da241990-12-20 15:06:42 +0000375
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000376/* List of names to clear in sys */
377static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 "path", "argv", "ps1", "ps2",
379 "last_type", "last_value", "last_traceback",
380 "path_hooks", "path_importer_cache", "meta_path",
381 /* misc stuff */
382 "flags", "float_info",
383 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000384};
385
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000386static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 "stdin", "__stdin__",
388 "stdout", "__stdout__",
389 "stderr", "__stderr__",
390 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000391};
392
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000393
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000394/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000395
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000397PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyObject *key, *value, *dict;
401 PyInterpreterState *interp = PyThreadState_GET()->interp;
402 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (modules == NULL)
405 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 /* Delete some special variables first. These are common
408 places where user values hide and people complain when their
409 destructors fail. Since the modules containing them are
410 deleted *last* of all, they would come too late in the normal
411 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 value = PyDict_GetItemString(modules, "builtins");
414 if (value != NULL && PyModule_Check(value)) {
415 dict = PyModule_GetDict(value);
416 if (Py_VerboseFlag)
417 PySys_WriteStderr("# clear builtins._\n");
418 PyDict_SetItemString(dict, "_", Py_None);
419 }
420 value = PyDict_GetItemString(modules, "sys");
421 if (value != NULL && PyModule_Check(value)) {
422 char **p;
423 PyObject *v;
424 dict = PyModule_GetDict(value);
425 for (p = sys_deletes; *p != NULL; p++) {
426 if (Py_VerboseFlag)
427 PySys_WriteStderr("# clear sys.%s\n", *p);
428 PyDict_SetItemString(dict, *p, Py_None);
429 }
430 for (p = sys_files; *p != NULL; p+=2) {
431 if (Py_VerboseFlag)
432 PySys_WriteStderr("# restore sys.%s\n", *p);
433 v = PyDict_GetItemString(dict, *(p+1));
434 if (v == NULL)
435 v = Py_None;
436 PyDict_SetItemString(dict, *p, v);
437 }
438 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 /* First, delete __main__ */
441 value = PyDict_GetItemString(modules, "__main__");
442 if (value != NULL && PyModule_Check(value)) {
443 if (Py_VerboseFlag)
444 PySys_WriteStderr("# cleanup __main__\n");
445 _PyModule_Clear(value);
446 PyDict_SetItemString(modules, "__main__", Py_None);
447 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 /* The special treatment of "builtins" here is because even
450 when it's not referenced as a module, its dictionary is
451 referenced by almost every module's __builtins__. Since
452 deleting a module clears its dictionary (even if there are
453 references left to it), we need to delete the "builtins"
454 module last. Likewise, we don't delete sys until the very
455 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 Also note that we 'delete' modules by replacing their entry
458 in the modules dict with None, rather than really deleting
459 them; this avoids a rehash of the modules dictionary and
460 also marks them as "non existent" so they won't be
461 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* Next, repeatedly delete modules with a reference count of
464 one (skipping builtins and sys) and delete them */
465 do {
466 ndone = 0;
467 pos = 0;
468 while (PyDict_Next(modules, &pos, &key, &value)) {
469 if (value->ob_refcnt != 1)
470 continue;
471 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100472 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100474 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 continue;
476 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100477 PySys_FormatStderr(
478 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 _PyModule_Clear(value);
480 PyDict_SetItem(modules, key, Py_None);
481 ndone++;
482 }
483 }
484 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 /* Next, delete all modules (still skipping builtins and sys) */
487 pos = 0;
488 while (PyDict_Next(modules, &pos, &key, &value)) {
489 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100490 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100492 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 continue;
494 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100495 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 _PyModule_Clear(value);
497 PyDict_SetItem(modules, key, Py_None);
498 }
499 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Next, delete sys and builtins (in that order) */
502 value = PyDict_GetItemString(modules, "sys");
503 if (value != NULL && PyModule_Check(value)) {
504 if (Py_VerboseFlag)
505 PySys_WriteStderr("# cleanup sys\n");
506 _PyModule_Clear(value);
507 PyDict_SetItemString(modules, "sys", Py_None);
508 }
509 value = PyDict_GetItemString(modules, "builtins");
510 if (value != NULL && PyModule_Check(value)) {
511 if (Py_VerboseFlag)
512 PySys_WriteStderr("# cleanup builtins\n");
513 _PyModule_Clear(value);
514 PyDict_SetItemString(modules, "builtins", Py_None);
515 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Finally, clear and delete the modules directory */
518 PyDict_Clear(modules);
519 interp->modules = NULL;
520 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000521}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000522
523
Barry Warsaw28a691b2010-04-17 00:19:56 +0000524/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000525
526long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000527PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000530}
531
532
Barry Warsaw28a691b2010-04-17 00:19:56 +0000533const char *
534PyImport_GetMagicTag(void)
535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000537}
538
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539/* Magic for extension modules (built-in as well as dynamically
540 loaded). To prevent initializing an extension module more than
541 once, we keep a static dictionary 'extensions' keyed by module name
542 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000543 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100544 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545 immediately after the module initialization function succeeds. A
546 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100547 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000548
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000549 Modules which do support multiple initialization set their m_size
550 field to a non-negative number (indicating the size of the
551 module-specific state). They are still recorded in the extensions
552 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000553*/
554
555int
Victor Stinner95872862011-03-07 18:20:56 +0100556_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
557 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 PyObject *modules, *dict;
560 struct PyModuleDef *def;
561 if (extensions == NULL) {
562 extensions = PyDict_New();
563 if (extensions == NULL)
564 return -1;
565 }
566 if (mod == NULL || !PyModule_Check(mod)) {
567 PyErr_BadInternalCall();
568 return -1;
569 }
570 def = PyModule_GetDef(mod);
571 if (!def) {
572 PyErr_BadInternalCall();
573 return -1;
574 }
575 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100576 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return -1;
578 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100579 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return -1;
581 }
582 if (def->m_size == -1) {
583 if (def->m_base.m_copy) {
584 /* Somebody already imported the module,
585 likely under a different name.
586 XXX this should really not happen. */
587 Py_DECREF(def->m_base.m_copy);
588 def->m_base.m_copy = NULL;
589 }
590 dict = PyModule_GetDict(mod);
591 if (dict == NULL)
592 return -1;
593 def->m_base.m_copy = PyDict_Copy(dict);
594 if (def->m_base.m_copy == NULL)
595 return -1;
596 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000597 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599}
600
Victor Stinner49d3f252010-10-17 01:24:53 +0000601int
602_PyImport_FixupBuiltin(PyObject *mod, char *name)
603{
604 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100605 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100606 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100607 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000608 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100609 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
610 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000611 return res;
612}
613
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100615_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyObject *mod, *mdict;
618 PyModuleDef* def;
619 if (extensions == NULL)
620 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000621 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (def == NULL)
623 return NULL;
624 if (def->m_size == -1) {
625 /* Module does not support repeated initialization */
626 if (def->m_base.m_copy == NULL)
627 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100628 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (mod == NULL)
630 return NULL;
631 mdict = PyModule_GetDict(mod);
632 if (mdict == NULL)
633 return NULL;
634 if (PyDict_Update(mdict, def->m_base.m_copy))
635 return NULL;
636 }
637 else {
638 if (def->m_base.m_init == NULL)
639 return NULL;
640 mod = def->m_base.m_init();
641 if (mod == NULL)
642 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100643 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 Py_DECREF(mod);
645 }
646 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100647 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 Py_DECREF(mod);
649 return NULL;
650 }
651 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100652 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 name, filename);
654 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000655
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656}
657
Victor Stinner49d3f252010-10-17 01:24:53 +0000658PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000659_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000660{
Victor Stinner95872862011-03-07 18:20:56 +0100661 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100662 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100663 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000664 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100665 res = _PyImport_FindExtensionObject(nameobj, nameobj);
666 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000667 return res;
668}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000669
670/* Get the module object corresponding to a module name.
671 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000672 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000673 Because the former action is most common, THIS DOES NOT RETURN A
674 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000675
Guido van Rossum79f25d91997-04-29 20:08:16 +0000676PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000677PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *modules = PyImport_GetModuleDict();
680 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000681
Victor Stinner27ee0892011-03-04 12:57:09 +0000682 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 PyModule_Check(m))
684 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000685 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if (m == NULL)
687 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000688 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_DECREF(m);
690 return NULL;
691 }
692 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695}
696
Victor Stinner27ee0892011-03-04 12:57:09 +0000697PyObject *
698PyImport_AddModule(const char *name)
699{
700 PyObject *nameobj, *module;
701 nameobj = PyUnicode_FromString(name);
702 if (nameobj == NULL)
703 return NULL;
704 module = PyImport_AddModuleObject(nameobj);
705 Py_DECREF(nameobj);
706 return module;
707}
708
709
Tim Peters1cd70172004-08-02 03:52:12 +0000710/* Remove name from sys.modules, if it's there. */
711static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000712remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000715 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000717 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 Py_FatalError("import: deleting existing key in"
719 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000720}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721
Victor Stinnerc9abda02011-03-14 13:33:46 -0400722static PyObject * get_sourcefile(PyObject *filename);
723static PyObject *make_source_pathname(PyObject *pathname);
Christian Heimes3b06e532008-01-07 20:12:44 +0000724
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000725/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000726 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
727 * removed from sys.modules, to avoid leaving damaged module objects
728 * in sys.modules. The caller may wish to restore the original
729 * module object (if any) in this case; PyImport_ReloadModule is an
730 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000731 *
732 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
733 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000734 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000735PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000736PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 return PyImport_ExecCodeModuleWithPathnames(
739 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000740}
741
742PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000743PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return PyImport_ExecCodeModuleWithPathnames(
746 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000747}
748
749PyObject *
750PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000752{
Victor Stinner27ee0892011-03-04 12:57:09 +0000753 PyObject *m = NULL;
754 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
755
756 nameobj = PyUnicode_FromString(name);
757 if (nameobj == NULL)
758 return NULL;
759
760 if (pathname != NULL) {
761 pathobj = PyUnicode_DecodeFSDefault(pathname);
762 if (pathobj == NULL)
763 goto error;
764 } else
765 pathobj = NULL;
766 if (cpathname != NULL) {
767 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
768 if (cpathobj == NULL)
769 goto error;
770 } else
771 cpathobj = NULL;
772 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
773error:
774 Py_DECREF(nameobj);
775 Py_XDECREF(pathobj);
776 Py_XDECREF(cpathobj);
777 return m;
778}
779
780PyObject*
781PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
782 PyObject *cpathname)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyObject *modules = PyImport_GetModuleDict();
785 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786
Victor Stinner27ee0892011-03-04 12:57:09 +0000787 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (m == NULL)
789 return NULL;
790 /* If the module is being reloaded, we get the old module back
791 and re-use its dict to exec the new code. */
792 d = PyModule_GetDict(m);
793 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
794 if (PyDict_SetItemString(d, "__builtins__",
795 PyEval_GetBuiltins()) != 0)
796 goto error;
797 }
798 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400800 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 if (v == NULL)
802 PyErr_Clear();
803 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000804 else
805 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (v == NULL) {
807 v = ((PyCodeObject *)co)->co_filename;
808 Py_INCREF(v);
809 }
810 if (PyDict_SetItemString(d, "__file__", v) != 0)
811 PyErr_Clear(); /* Not important enough to report */
812 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000815 if (cpathname != NULL)
816 v = cpathname;
817 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (PyDict_SetItemString(d, "__cached__", v) != 0)
820 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000821
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000822 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (v == NULL)
824 goto error;
825 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000826
Victor Stinner27ee0892011-03-04 12:57:09 +0000827 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000829 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 name);
831 return NULL;
832 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000837
838 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 remove_module(name);
840 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000841}
842
843
Martin v. Löwis2db72862011-10-23 17:29:08 +0200844/* Like rightmost_sep, but operate on unicode objects. */
845static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200846rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200847{
848 Py_ssize_t found, i;
849 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200850 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200851 c = PyUnicode_READ_CHAR(o, i);
852 if (c == SEP
853#ifdef ALTSEP
854 || c == ALTSEP
855#endif
856 )
857 {
858 found = i;
859 }
860 }
861 return found;
862}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400863
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000864
Barry Warsaw28a691b2010-04-17 00:19:56 +0000865/* Given a pathname to a Python byte compiled file, return the path to the
866 source file, if the path matches the PEP 3147 format. This does not check
867 for any file existence, however, if the pyc file name does not match PEP
868 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400869 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870
Victor Stinnerc9abda02011-03-14 13:33:46 -0400871 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
872
873static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200874make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000875{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200876 Py_ssize_t left, right, dot0, dot1, len;
877 Py_ssize_t i, j;
878 PyObject *result;
879 int kind;
880 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400881
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200882 len = PyUnicode_GET_LENGTH(path);
883 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* Look back two slashes from the end. In between these two slashes
887 must be the string __pycache__ or this is not a PEP 3147 style
888 path. It's possible for there to be only one slash.
889 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200890 right = rightmost_sep_obj(path, 0, len);
891 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200893 left = rightmost_sep_obj(path, 0, right);
894 if (left == -1)
895 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 else
897 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200898 if (right-left != sizeof(CACHEDIR)-1)
899 return NULL;
900 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
901 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
902 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* Now verify that the path component to the right of the last slash
905 has two dots in it.
906 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200907 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
908 if (dot0 < 0)
909 return NULL;
910 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
911 if (dot1 < 0)
912 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200914 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
915 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* This is a PEP 3147 path. Start by copying everything from the
918 start of pathname up to and including the leftmost slash. Then
919 copy the file's basename, removing the magic tag and adding a .py
920 suffix.
921 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200922 result = PyUnicode_New(left + (dot0-right) + 2,
923 PyUnicode_MAX_CHAR_VALUE(path));
924 if (!result)
925 return NULL;
926 kind = PyUnicode_KIND(result);
927 data = PyUnicode_DATA(result);
928 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
929 PyUnicode_CopyCharacters(result, left, path, right+1,
930 (j = dot0-right));
931 PyUnicode_WRITE(kind, data, i+j, 'p');
932 PyUnicode_WRITE(kind, data, i+j+1, 'y');
Victor Stinner8f825062012-04-27 13:55:39 +0200933 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200934 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000935}
936
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000937
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000938static void
939update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyObject *constants, *tmp;
942 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (PyUnicode_Compare(co->co_filename, oldname))
945 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 tmp = co->co_filename;
948 co->co_filename = newname;
949 Py_INCREF(co->co_filename);
950 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 constants = co->co_consts;
953 n = PyTuple_GET_SIZE(constants);
954 for (i = 0; i < n; i++) {
955 tmp = PyTuple_GET_ITEM(constants, i);
956 if (PyCode_Check(tmp))
957 update_code_filenames((PyCodeObject *)tmp,
958 oldname, newname);
959 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000960}
961
Victor Stinner2f42ae52011-03-20 00:41:24 +0100962static void
963update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000964{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100965 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000966
Victor Stinner2f42ae52011-03-20 00:41:24 +0100967 if (PyUnicode_Compare(co->co_filename, newname) == 0)
968 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 oldname = co->co_filename;
971 Py_INCREF(oldname);
972 update_code_filenames(co, oldname, newname);
973 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000974}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000975
Brett Cannon442c9b92011-03-23 16:14:42 -0700976static PyObject *
977imp_fix_co_filename(PyObject *self, PyObject *args)
978{
979 PyObject *co;
980 PyObject *file_path;
981
982 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
983 return NULL;
984
985 if (!PyCode_Check(co)) {
986 PyErr_SetString(PyExc_TypeError,
987 "first argument must be a code object");
988 return NULL;
989 }
990
991 if (!PyUnicode_Check(file_path)) {
992 PyErr_SetString(PyExc_TypeError,
993 "second argument must be a string");
994 return NULL;
995 }
996
997 update_compiled_module((PyCodeObject*)co, file_path);
998
999 Py_RETURN_NONE;
1000}
1001
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001002
Christian Heimes3b06e532008-01-07 20:12:44 +00001003/* Get source file -> unicode or None
1004 * Returns the path to the py file if available, else the given path
1005 */
1006static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001007get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001010 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001011 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001013 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001016 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001018
Victor Stinnerc9abda02011-03-14 13:33:46 -04001019 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001020 fileuni = PyUnicode_AsUCS4Copy(filename);
1021 if (!fileuni)
1022 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001023 if (len < 5
1024 || fileuni[len-4] != '.'
1025 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1026 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1027 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 /* Start by trying to turn PEP 3147 path into source path. If that
1030 * fails, just chop off the trailing character, i.e. legacy pyc path
1031 * to py.
1032 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001033 py = make_source_pathname(filename);
1034 if (py == NULL) {
1035 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001036 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001038 if (py == NULL)
1039 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001040
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001041 err = _Py_stat(py, &statbuf);
1042 if (err == -2)
1043 goto error;
1044 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001045 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001046 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001047 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001048 Py_DECREF(py);
1049 goto unchanged;
1050
1051error:
1052 PyErr_Clear();
1053unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001055 Py_INCREF(filename);
1056 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001057}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001058
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001059/* Forward */
Victor Stinner53dc7352011-03-20 01:50:21 +01001060static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001061
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001062
1063/* Helper to test for built-in module */
1064
1065static int
Victor Stinner95872862011-03-07 18:20:56 +01001066is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067{
Victor Stinner95872862011-03-07 18:20:56 +01001068 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001070 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1071 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (PyImport_Inittab[i].initfunc == NULL)
1073 return -1;
1074 else
1075 return 1;
1076 }
1077 }
1078 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001079}
1080
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001081
Just van Rossum52e14d62002-12-30 22:08:05 +00001082/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1083 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001084 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001085 that can handle the path item. Return None if no hook could;
1086 this tells our caller it should fall back to the builtin
1087 import mechanism. Cache the result in path_importer_cache.
1088 Returns a borrowed reference. */
1089
1090static PyObject *
1091get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *importer;
1095 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 /* These conditions are the caller's responsibility: */
1098 assert(PyList_Check(path_hooks));
1099 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 nhooks = PyList_Size(path_hooks);
1102 if (nhooks < 0)
1103 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 importer = PyDict_GetItem(path_importer_cache, p);
1106 if (importer != NULL)
1107 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 /* set path_importer_cache[p] to None to avoid recursion */
1110 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1111 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 for (j = 0; j < nhooks; j++) {
1114 PyObject *hook = PyList_GetItem(path_hooks, j);
1115 if (hook == NULL)
1116 return NULL;
1117 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1118 if (importer != NULL)
1119 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1122 return NULL;
1123 }
1124 PyErr_Clear();
1125 }
1126 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001127 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
1129 if (importer != NULL) {
1130 int err = PyDict_SetItem(path_importer_cache, p, importer);
1131 Py_DECREF(importer);
1132 if (err != 0)
1133 return NULL;
1134 }
1135 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001136}
1137
Christian Heimes9cd17752007-11-18 19:35:23 +00001138PyAPI_FUNC(PyObject *)
1139PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1143 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1144 importer = get_path_importer(path_importer_cache,
1145 path_hooks, path);
1146 }
1147 }
1148 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1149 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001150}
1151
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001153#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001154extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1155 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001156#endif
1157
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001158
Victor Stinner95872862011-03-07 18:20:56 +01001159static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001160
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001161/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001162 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001163 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001164
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001165static int
Victor Stinner95872862011-03-07 18:20:56 +01001166init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001169
Victor Stinner95872862011-03-07 18:20:56 +01001170 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 for (p = PyImport_Inittab; p->name != NULL; p++) {
1174 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001175 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001176 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (p->initfunc == NULL) {
1178 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001179 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 name);
1181 return -1;
1182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 mod = (*p->initfunc)();
1184 if (mod == 0)
1185 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001186 /* Remember pointer to module init function. */
1187 def = PyModule_GetDef(mod);
1188 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001189 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 return -1;
1191 /* FixupExtension has put the module into sys.modules,
1192 so we can release our own reference. */
1193 Py_DECREF(mod);
1194 return 1;
1195 }
1196 }
1197 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001198}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001199
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001200
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001201/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001203static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001204find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001207
Victor Stinner53dc7352011-03-20 01:50:21 +01001208 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 for (p = PyImport_FrozenModules; ; p++) {
1212 if (p->name == NULL)
1213 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001214 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 break;
1216 }
1217 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001218}
1219
Guido van Rossum79f25d91997-04-29 20:08:16 +00001220static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001221get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 struct _frozen *p = find_frozen(name);
1224 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (p == NULL) {
1227 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001228 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 name);
1230 return NULL;
1231 }
1232 if (p->code == NULL) {
1233 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001234 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 name);
1236 return NULL;
1237 }
1238 size = p->size;
1239 if (size < 0)
1240 size = -size;
1241 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001242}
1243
Brett Cannon8d110132009-03-15 02:20:16 +00001244static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001245is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 struct _frozen *p = find_frozen(name);
1248 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (p == NULL) {
1251 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001252 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 name);
1254 return NULL;
1255 }
Brett Cannon8d110132009-03-15 02:20:16 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (size < 0)
1260 Py_RETURN_TRUE;
1261 else
1262 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001263}
1264
1265
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001266/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001267 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001268 an exception set if the initialization failed.
1269 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001270
1271int
Victor Stinner53dc7352011-03-20 01:50:21 +01001272PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001273{
Victor Stinner53dc7352011-03-20 01:50:21 +01001274 struct _frozen *p;
1275 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 int ispackage;
1277 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001278
Victor Stinner53dc7352011-03-20 01:50:21 +01001279 p = find_frozen(name);
1280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (p == NULL)
1282 return 0;
1283 if (p->code == NULL) {
1284 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001285 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 name);
1287 return -1;
1288 }
1289 size = p->size;
1290 ispackage = (size < 0);
1291 if (ispackage)
1292 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1294 if (co == NULL)
1295 return -1;
1296 if (!PyCode_Check(co)) {
1297 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001298 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 name);
1300 goto err_return;
1301 }
1302 if (ispackage) {
1303 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01001304 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001306 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (m == NULL)
1308 goto err_return;
1309 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 l = PyList_New(1);
1311 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 goto err_return;
1313 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001314 Py_INCREF(name);
1315 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 err = PyDict_SetItemString(d, "__path__", l);
1317 Py_DECREF(l);
1318 if (err != 0)
1319 goto err_return;
1320 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001321 path = PyUnicode_FromString("<frozen>");
1322 if (path == NULL)
1323 goto err_return;
1324 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1325 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (m == NULL)
1327 goto err_return;
1328 Py_DECREF(co);
1329 Py_DECREF(m);
1330 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001331err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_DECREF(co);
1333 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001334}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001335
Victor Stinner53dc7352011-03-20 01:50:21 +01001336int
1337PyImport_ImportFrozenModule(char *name)
1338{
1339 PyObject *nameobj;
1340 int ret;
1341 nameobj = PyUnicode_InternFromString(name);
1342 if (nameobj == NULL)
1343 return -1;
1344 ret = PyImport_ImportFrozenModuleObject(nameobj);
1345 Py_DECREF(nameobj);
1346 return ret;
1347}
1348
Guido van Rossum74e6a111994-08-29 12:54:38 +00001349
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001350/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001351 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001352
Guido van Rossum79f25d91997-04-29 20:08:16 +00001353PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001354PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyObject *pname;
1357 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 pname = PyUnicode_FromString(name);
1360 if (pname == NULL)
1361 return NULL;
1362 result = PyImport_Import(pname);
1363 Py_DECREF(pname);
1364 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001365}
1366
Christian Heimes072c0f12008-01-03 23:01:04 +00001367/* Import a module without blocking
1368 *
1369 * At first it tries to fetch the module from sys.modules. If the module was
1370 * never loaded before it loads it with PyImport_ImportModule() unless another
1371 * thread holds the import lock. In the latter case the function raises an
1372 * ImportError instead of blocking.
1373 *
1374 * Returns the module object with incremented ref count.
1375 */
1376PyObject *
1377PyImport_ImportModuleNoBlock(const char *name)
1378{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001379 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02001380#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02001382#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* Try to get the module from sys.modules[name] */
1385 modules = PyImport_GetModuleDict();
1386 if (modules == NULL)
1387 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001388
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001389 nameobj = PyUnicode_FromString(name);
1390 if (nameobj == NULL)
1391 return NULL;
1392 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001394 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 Py_INCREF(result);
1396 return result;
1397 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001398 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001399#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* check the import lock
1401 * me might be -1 but I ignore the error here, the lock function
1402 * takes care of the problem */
1403 me = PyThread_get_thread_ident();
1404 if (import_lock_thread == -1 || import_lock_thread == me) {
1405 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001406 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 }
1408 else {
1409 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04001410 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001412 nameobj);
1413 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001415#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001416 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001417#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001418 Py_DECREF(nameobj);
1419 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00001420}
1421
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001422
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001423PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001424PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1425 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001426 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001427{
Brett Cannonfd074152012-04-14 14:10:13 -04001428 _Py_IDENTIFIER(__import__);
1429 _Py_IDENTIFIER(__package__);
1430 _Py_IDENTIFIER(__path__);
1431 _Py_IDENTIFIER(__name__);
1432 _Py_IDENTIFIER(_find_and_load);
1433 _Py_IDENTIFIER(_handle_fromlist);
1434 _Py_static_string(single_dot, ".");
1435 PyObject *abs_name = NULL;
1436 PyObject *builtins_import = NULL;
1437 PyObject *final_mod = NULL;
1438 PyObject *mod = NULL;
1439 PyObject *package = NULL;
1440 PyObject *globals = NULL;
1441 PyObject *fromlist = NULL;
1442 PyInterpreterState *interp = PyThreadState_GET()->interp;
1443
1444 /* Make sure to use default values so as to not have
1445 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1446 NULL argument. */
1447 if (given_globals == NULL) {
1448 globals = PyDict_New();
1449 if (globals == NULL) {
1450 goto error;
1451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 }
Brett Cannonfd074152012-04-14 14:10:13 -04001453 else {
1454 /* Only have to care what given_globals is if it will be used
1455 fortsomething. */
1456 if (level > 0 && !PyDict_Check(given_globals)) {
1457 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1458 goto error;
1459 }
1460 globals = given_globals;
1461 Py_INCREF(globals);
1462 }
1463
1464 if (given_fromlist == NULL) {
1465 fromlist = PyList_New(0);
1466 if (fromlist == NULL) {
1467 goto error;
1468 }
1469 }
1470 else {
1471 fromlist = given_fromlist;
1472 Py_INCREF(fromlist);
1473 }
1474 if (name == NULL) {
1475 PyErr_SetString(PyExc_ValueError, "Empty module name");
1476 goto error;
1477 }
1478
1479 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1480 for added performance. */
1481
1482 if (!PyUnicode_Check(name)) {
1483 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1484 goto error;
1485 }
1486 else if (PyUnicode_READY(name) < 0) {
1487 goto error;
1488 }
1489 if (level < 0) {
1490 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1491 goto error;
1492 }
1493 else if (level > 0) {
1494 package = _PyDict_GetItemId(globals, &PyId___package__);
1495 if (package != NULL && package != Py_None) {
1496 Py_INCREF(package);
1497 if (!PyUnicode_Check(package)) {
1498 PyErr_SetString(PyExc_TypeError, "package must be a string");
1499 goto error;
1500 }
1501 }
1502 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001503 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001504 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001505 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001506 goto error;
1507 }
1508 else if (!PyUnicode_Check(package)) {
1509 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1510 }
1511 Py_INCREF(package);
1512
1513 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001514 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001515 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1516 if (borrowed_dot == NULL) {
1517 goto error;
1518 }
Brett Cannon740fce02012-04-14 14:23:49 -04001519 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001520 Py_DECREF(package);
1521 if (partition == NULL) {
1522 goto error;
1523 }
1524 package = PyTuple_GET_ITEM(partition, 0);
1525 Py_INCREF(package);
1526 Py_DECREF(partition);
1527 }
1528 }
1529
1530 if (PyDict_GetItem(interp->modules, package) == NULL) {
1531 PyErr_Format(PyExc_SystemError,
1532 "Parent module %R not loaded, cannot perform relative "
1533 "import", package);
1534 goto error;
1535 }
1536 }
1537 else { /* level == 0 */
1538 if (PyUnicode_GET_LENGTH(name) == 0) {
1539 PyErr_SetString(PyExc_ValueError, "Empty module name");
1540 goto error;
1541 }
1542 package = Py_None;
1543 Py_INCREF(package);
1544 }
1545
1546 if (level > 0) {
1547 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1548 PyObject *base = NULL;
1549 int level_up = 1;
1550
1551 for (level_up = 1; level_up < level; level_up += 1) {
1552 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1553 if (last_dot == -2) {
1554 goto error;
1555 }
1556 else if (last_dot == -1) {
1557 PyErr_SetString(PyExc_ValueError,
1558 "attempted relative import beyond top-level "
1559 "package");
1560 goto error;
1561 }
1562 }
1563 base = PyUnicode_Substring(package, 0, last_dot);
1564 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001565 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001566
1567 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001568 seq = PyTuple_Pack(2, base, name);
1569 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001570 if (borrowed_dot == NULL || seq == NULL) {
1571 goto error;
1572 }
1573
1574 abs_name = PyUnicode_Join(borrowed_dot, seq);
1575 Py_DECREF(seq);
1576 if (abs_name == NULL) {
1577 goto error;
1578 }
1579 }
1580 else {
1581 abs_name = base;
1582 }
1583 }
1584 else {
1585 abs_name = name;
1586 Py_INCREF(abs_name);
1587 }
1588
Brian Curtine6b299f2012-04-14 14:19:33 -05001589#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001590 _PyImport_AcquireLock();
1591#endif
1592 /* From this point forward, goto error_with_unlock! */
1593 if (PyDict_Check(globals)) {
1594 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1595 }
1596 if (builtins_import == NULL) {
1597 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1598 if (builtins_import == NULL) {
1599 Py_FatalError("__import__ missing");
1600 }
1601 }
1602 Py_INCREF(builtins_import);
1603
1604 mod = PyDict_GetItem(interp->modules, abs_name);
1605 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001606 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1607 "None in sys.modules", abs_name);
1608 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05001609 PyErr_SetImportError(msg, abs_name, NULL);
1610 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001611 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001612 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001613 goto error_with_unlock;
1614 }
1615 else if (mod != NULL) {
1616 Py_INCREF(mod);
1617 }
1618 else {
1619 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1620 &PyId__find_and_load, abs_name,
1621 builtins_import, NULL);
1622 if (mod == NULL) {
1623 goto error_with_unlock;
1624 }
1625 }
1626
1627 if (PyObject_Not(fromlist)) {
1628 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1629 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001630 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001631 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1632
1633 if (borrowed_dot == NULL) {
1634 goto error_with_unlock;
1635 }
1636
Brian Curtine6b299f2012-04-14 14:19:33 -05001637 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001638 if (partition == NULL) {
1639 goto error_with_unlock;
1640 }
1641
1642 front = PyTuple_GET_ITEM(partition, 0);
1643 Py_INCREF(front);
1644 Py_DECREF(partition);
1645
1646 if (level == 0) {
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001647 final_mod = PyDict_GetItem(interp->modules, front);
Brett Cannon881535b2012-04-15 15:24:04 -04001648 Py_DECREF(front);
1649 if (final_mod == NULL) {
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001650 PyErr_Format(PyExc_KeyError,
1651 "%R not in sys.modules as expected", front);
Brett Cannon881535b2012-04-15 15:24:04 -04001652 }
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001653 else {
1654 Py_INCREF(final_mod);
1655 }
Brett Cannonfd074152012-04-14 14:10:13 -04001656 }
1657 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001658 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1659 PyUnicode_GET_LENGTH(front);
1660 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001661 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001662 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001663 Py_DECREF(front);
1664 if (to_return == NULL) {
1665 goto error_with_unlock;
1666 }
Brett Cannonfd074152012-04-14 14:10:13 -04001667
1668 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001669 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001670 if (final_mod == NULL) {
1671 PyErr_Format(PyExc_KeyError,
1672 "%R not in sys.modules as expected",
1673 to_return);
1674 }
1675 else {
1676 Py_INCREF(final_mod);
1677 }
Brett Cannonfd074152012-04-14 14:10:13 -04001678 }
1679 }
1680 else {
1681 final_mod = mod;
1682 Py_INCREF(mod);
1683 }
1684 }
1685 else {
1686 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1687 &PyId__handle_fromlist, mod,
1688 fromlist, builtins_import,
1689 NULL);
1690 }
1691 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001692#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001693 if (_PyImport_ReleaseLock() < 0) {
1694 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1695 }
1696#endif
1697 error:
1698 Py_XDECREF(abs_name);
1699 Py_XDECREF(builtins_import);
1700 Py_XDECREF(mod);
1701 Py_XDECREF(package);
1702 Py_XDECREF(globals);
1703 Py_XDECREF(fromlist);
1704 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001705}
1706
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001707PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001708PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001709 PyObject *fromlist, int level)
1710{
1711 PyObject *nameobj, *mod;
1712 nameobj = PyUnicode_FromString(name);
1713 if (nameobj == NULL)
1714 return NULL;
1715 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1716 fromlist, level);
1717 Py_DECREF(nameobj);
1718 return mod;
1719}
1720
1721
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001722/* Re-import a module of any kind and return its module object, WITH
1723 INCREMENTED REFERENCE COUNT */
1724
Guido van Rossum79f25d91997-04-29 20:08:16 +00001725PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001726PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001727{
Brett Cannon62228db2012-04-29 14:38:11 -04001728 _Py_IDENTIFIER(reload);
1729 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001731 PyObject *imp = PyDict_GetItemString(modules, "imp");
1732 if (imp == NULL) {
1733 imp = PyImport_ImportModule("imp");
1734 if (imp == NULL) {
1735 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Brett Cannon62228db2012-04-29 14:38:11 -04001738 else {
1739 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001741
Brett Cannon62228db2012-04-29 14:38:11 -04001742 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1743 Py_DECREF(imp);
1744 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001745}
1746
1747
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001748/* Higher-level import emulator which emulates the "import" statement
1749 more accurately -- it invokes the __import__() function from the
1750 builtins of the current globals. This means that the import is
1751 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001752 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001753 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001754 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001755 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001756
1757PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001758PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 static PyObject *silly_list = NULL;
1761 static PyObject *builtins_str = NULL;
1762 static PyObject *import_str = NULL;
1763 PyObject *globals = NULL;
1764 PyObject *import = NULL;
1765 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001766 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* Initialize constant string objects */
1770 if (silly_list == NULL) {
1771 import_str = PyUnicode_InternFromString("__import__");
1772 if (import_str == NULL)
1773 return NULL;
1774 builtins_str = PyUnicode_InternFromString("__builtins__");
1775 if (builtins_str == NULL)
1776 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001777 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (silly_list == NULL)
1779 return NULL;
1780 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /* Get the builtins from current globals */
1783 globals = PyEval_GetGlobals();
1784 if (globals != NULL) {
1785 Py_INCREF(globals);
1786 builtins = PyObject_GetItem(globals, builtins_str);
1787 if (builtins == NULL)
1788 goto err;
1789 }
1790 else {
1791 /* No globals -- use standard builtins, and fake globals */
1792 builtins = PyImport_ImportModuleLevel("builtins",
1793 NULL, NULL, NULL, 0);
1794 if (builtins == NULL)
1795 return NULL;
1796 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1797 if (globals == NULL)
1798 goto err;
1799 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 /* Get the __import__ function from the builtins */
1802 if (PyDict_Check(builtins)) {
1803 import = PyObject_GetItem(builtins, import_str);
1804 if (import == NULL)
1805 PyErr_SetObject(PyExc_KeyError, import_str);
1806 }
1807 else
1808 import = PyObject_GetAttr(builtins, import_str);
1809 if (import == NULL)
1810 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001813 Always use absolute import here.
1814 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1816 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001817 if (r == NULL)
1818 goto err;
1819 Py_DECREF(r);
1820
1821 modules = PyImport_GetModuleDict();
1822 r = PyDict_GetItem(modules, module_name);
1823 if (r != NULL)
1824 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001825
1826 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 Py_XDECREF(globals);
1828 Py_XDECREF(builtins);
1829 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001832}
1833
1834
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001835/* Module 'imp' provides Python access to the primitives used for
1836 importing modules.
1837*/
1838
Guido van Rossum79f25d91997-04-29 20:08:16 +00001839static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001840imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 buf[0] = (char) ((magic >> 0) & 0xff);
1845 buf[1] = (char) ((magic >> 8) & 0xff);
1846 buf[2] = (char) ((magic >> 16) & 0xff);
1847 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00001850}
Barry Warsaw28a691b2010-04-17 00:19:56 +00001851
1852static PyObject *
1853imp_get_magic(PyObject *self, PyObject *noargs)
1854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001856}
1857
1858static PyObject *
1859imp_get_tag(PyObject *self, PyObject *noargs)
1860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001862}
1863
Guido van Rossum79f25d91997-04-29 20:08:16 +00001864static PyObject *
Brett Cannon2657df42012-05-04 15:20:40 -04001865imp_extension_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001868 const char *suffix;
1869 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 list = PyList_New(0);
1872 if (list == NULL)
1873 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001874#ifdef HAVE_DYNAMIC_LOADING
1875 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1876 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (item == NULL) {
1878 Py_DECREF(list);
1879 return NULL;
1880 }
1881 if (PyList_Append(list, item) < 0) {
1882 Py_DECREF(list);
1883 Py_DECREF(item);
1884 return NULL;
1885 }
1886 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001887 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 }
Brett Cannon2657df42012-05-04 15:20:40 -04001889#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001891}
1892
Guido van Rossum79f25d91997-04-29 20:08:16 +00001893static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001894imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001895{
Victor Stinner95872862011-03-07 18:20:56 +01001896 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 int ret;
1898 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01001899 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 return NULL;
1901 ret = init_builtin(name);
1902 if (ret < 0)
1903 return NULL;
1904 if (ret == 0) {
1905 Py_INCREF(Py_None);
1906 return Py_None;
1907 }
Victor Stinner95872862011-03-07 18:20:56 +01001908 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 Py_XINCREF(m);
1910 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001911}
1912
Guido van Rossum79f25d91997-04-29 20:08:16 +00001913static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001914imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001915{
Victor Stinner53dc7352011-03-20 01:50:21 +01001916 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 int ret;
1918 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01001919 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001921 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (ret < 0)
1923 return NULL;
1924 if (ret == 0) {
1925 Py_INCREF(Py_None);
1926 return Py_None;
1927 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001928 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 Py_XINCREF(m);
1930 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001931}
1932
Guido van Rossum79f25d91997-04-29 20:08:16 +00001933static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001934imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001935{
Victor Stinner53dc7352011-03-20 01:50:21 +01001936 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00001937
Victor Stinner53dc7352011-03-20 01:50:21 +01001938 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 return NULL;
1940 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001941}
1942
Guido van Rossum79f25d91997-04-29 20:08:16 +00001943static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00001944imp_is_frozen_package(PyObject *self, PyObject *args)
1945{
Victor Stinner53dc7352011-03-20 01:50:21 +01001946 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00001947
Victor Stinner53dc7352011-03-20 01:50:21 +01001948 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 return NULL;
1950 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001951}
1952
1953static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001954imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001955{
Victor Stinner95872862011-03-07 18:20:56 +01001956 PyObject *name;
1957 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 return NULL;
1959 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001960}
1961
Guido van Rossum79f25d91997-04-29 20:08:16 +00001962static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001963imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001964{
Victor Stinner53dc7352011-03-20 01:50:21 +01001965 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01001967 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 return NULL;
1969 p = find_frozen(name);
1970 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001971}
1972
1973static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001974get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 FILE *fp;
1977 if (mode[0] == 'U')
1978 mode = "r" PY_STDIOTEXTMODE;
1979 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01001980 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01001981 if (!fp) {
1982 if (!PyErr_Occurred())
1983 PyErr_SetFromErrno(PyExc_IOError);
1984 return NULL;
1985 }
1986 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 }
1988 else {
1989 int fd = PyObject_AsFileDescriptor(fob);
1990 if (fd == -1)
1991 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01001992 if (!_PyVerify_fd(fd)) {
1993 PyErr_SetFromErrno(PyExc_IOError);
1994 return NULL;
1995 }
1996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 /* the FILE struct gets a new fd, so that it can be closed
1998 * independently of the file descriptor given
1999 */
2000 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01002001 if (fd == -1) {
2002 PyErr_SetFromErrno(PyExc_IOError);
2003 return NULL;
2004 }
2005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01002007 if (!fp) {
2008 PyErr_SetFromErrno(PyExc_IOError);
2009 return NULL;
2010 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01002012 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002013}
2014
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002015#ifdef HAVE_DYNAMIC_LOADING
2016
Guido van Rossum79f25d91997-04-29 20:08:16 +00002017static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002018imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002019{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002020 PyObject *name, *pathname, *fob = NULL, *mod;
2021 FILE *fp;
2022
2023 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
2024 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002026 if (fob != NULL) {
2027 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002028 if (fp == NULL) {
2029 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002031 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002033 else
2034 fp = NULL;
2035 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002036 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (fp)
2038 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002039 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002040}
2041
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002042#endif /* HAVE_DYNAMIC_LOADING */
2043
Barry Warsaw28a691b2010-04-17 00:19:56 +00002044
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002045/* Doc strings */
2046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002047PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002048"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002050PyDoc_STRVAR(doc_get_magic,
2051"get_magic() -> string\n\
2052Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002053
Barry Warsaw28a691b2010-04-17 00:19:56 +00002054PyDoc_STRVAR(doc_get_tag,
2055"get_tag() -> string\n\
2056Return the magic tag for .pyc or .pyo files.");
2057
Brett Cannon2657df42012-05-04 15:20:40 -04002058PyDoc_STRVAR(doc_extension_suffixes,
2059"extension_suffixes() -> list of strings\n\
2060Returns the list of file suffixes used to identify extension modules.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002061
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002062PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002063"lock_held() -> boolean\n\
2064Return True if the import lock is currently held, else False.\n\
2065On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002066
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002067PyDoc_STRVAR(doc_acquire_lock,
2068"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002069Acquires the interpreter's import lock for the current thread.\n\
2070This lock should be used by import hooks to ensure thread-safety\n\
2071when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002072On platforms without threads, this function does nothing.");
2073
2074PyDoc_STRVAR(doc_release_lock,
2075"release_lock() -> None\n\
2076Release the interpreter's import lock.\n\
2077On platforms without threads, this function does nothing.");
2078
Guido van Rossum79f25d91997-04-29 20:08:16 +00002079static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2081 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
Brett Cannon2657df42012-05-04 15:20:40 -04002082 {"extension_suffixes", imp_extension_suffixes, METH_NOARGS,
2083 doc_extension_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2085 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2086 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2088 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
2089 {"init_builtin", imp_init_builtin, METH_VARARGS},
2090 {"init_frozen", imp_init_frozen, METH_VARARGS},
2091 {"is_builtin", imp_is_builtin, METH_VARARGS},
2092 {"is_frozen", imp_is_frozen, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002093#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002095#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07002096 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002098};
2099
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002100static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002101setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *v;
2104 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 v = PyLong_FromLong((long)value);
2107 err = PyDict_SetItemString(d, name, v);
2108 Py_XDECREF(v);
2109 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002110}
2111
Martin v. Löwis1a214512008-06-11 05:26:20 +00002112static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002114 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 doc_imp,
2116 0,
2117 imp_methods,
2118 NULL,
2119 NULL,
2120 NULL,
2121 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002122};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002123
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002124PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002125PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 m = PyModule_Create(&impmodule);
2130 if (m == NULL)
2131 goto failure;
2132 d = PyModule_GetDict(m);
2133 if (d == NULL)
2134 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2137 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2138 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2139 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2140 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2141 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2142 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2143 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2144 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2145 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002148 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_XDECREF(m);
2150 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002151}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002152
2153
Guido van Rossumb18618d2000-05-03 23:44:39 +00002154/* API for embedding applications that want to add their own entries
2155 to the table of built-in modules. This should normally be called
2156 *before* Py_Initialize(). When the table resize fails, -1 is
2157 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002158
2159 After a similar function by Just van Rossum. */
2160
2161int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002162PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 static struct _inittab *our_copy = NULL;
2165 struct _inittab *p;
2166 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* Count the number of entries in both tables */
2169 for (n = 0; newtab[n].name != NULL; n++)
2170 ;
2171 if (n == 0)
2172 return 0; /* Nothing to do */
2173 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2174 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 /* Allocate new memory for the combined table */
2177 p = our_copy;
2178 PyMem_RESIZE(p, struct _inittab, i+n+1);
2179 if (p == NULL)
2180 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* Copy the tables into the new memory */
2183 if (our_copy != PyImport_Inittab)
2184 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2185 PyImport_Inittab = our_copy = p;
2186 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002189}
2190
2191/* Shorthand to add a single entry given a name and a function */
2192
2193int
Brett Cannona826f322009-04-02 03:41:46 +00002194PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 newtab[0].name = (char *)name;
2201 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002204}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002205
2206#ifdef __cplusplus
2207}
2208#endif