blob: 15920458962a7af3051531d4e6d9ab6eec7669af [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"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Christian Heimesd3eb5a152008-02-24 00:38:49 +000022#ifdef MS_WINDOWS
23/* for stat.st_mode */
24typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000025/* for _mkdir */
26#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000027#endif
28
Guido van Rossum21d335e1993-10-15 13:01:11 +000029
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000030/* Magic word to reject .pyc files generated by other Python versions.
31 It should change for each incompatible change to the bytecode.
32
33 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000034 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000035 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000036
Guido van Rossum45aecf42006-03-15 04:58:47 +000037 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000038 -U interpeter flag will cause MAGIC+1 being used. They have been
39 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000040
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000041 There were a variety of old schemes for setting the magic number.
42 The current working scheme is to increment the previous value by
43 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000044
Barry Warsaw28a691b2010-04-17 00:19:56 +000045 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
46 number also includes a new "magic tag", i.e. a human readable string used
47 to represent the magic number in __pycache__ directories. When you change
48 the magic number, you must also set a new unique magic tag. Generally this
49 can be named after the Python major version of the magic number bump, but
50 it can really be anything, as long as it's different than anything else
51 that's come before. The tags are included in the following table, starting
52 with Python 3.2a0.
53
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000054 Known values:
55 Python 1.5: 20121
56 Python 1.5.1: 20121
57 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000059 Python 2.0: 50823
60 Python 2.0.1: 50823
61 Python 2.1: 60202
62 Python 2.1.1: 60202
63 Python 2.1.2: 60202
64 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000065 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000066 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000067 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000068 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000069 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000070 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000071 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000072 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000073 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000074 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
76 Python 2.5b3: 62111 (fix wrong code: x += yield)
77 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000079 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000080 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000081 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000082 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 3010 (removed UNARY_CONVERT)
84 3020 (added BUILD_SET)
85 3030 (added keyword-only parameters)
86 3040 (added signature annotations)
87 3050 (print becomes a function)
88 3060 (PEP 3115 metaclass syntax)
89 3061 (string literals become unicode)
90 3071 (PEP 3109 raise changes)
91 3081 (PEP 3137 make __file__ and __name__ unicode)
92 3091 (kill str8 interning)
93 3101 (merge from 2.6a0, see 62151)
94 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000095 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
96 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
97 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000099 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000101 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000103 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
104 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000105 Python 3.2a2 3180 (add DELETE_DEREF)
Benjamin Petersone7c15fa2011-06-19 19:54:45 -0500106 Python 3.3a0 3190 __class__ super closure changed
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100107 Python 3.3a0 3200 (__qualname__ added)
Benjamin Petersonabdb5522012-03-15 15:40:37 -0500108 3210 (added size modulo 2**32 to the pyc header)
109 Python 3.3a1 3220 (changed PEP 380 implementation)
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000110 Python 3.3a4 3230 (revert changes to implicit __class__ closure)
Tim Peters36515e22001-11-18 04:06:29 +0000111*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000112
Nick Coghlancd419ab2010-09-11 00:39:25 +0000113/* MAGIC must change whenever the bytecode emitted by the compiler may no
114 longer be understood by older implementations of the eval loop (usually
115 due to the addition of new opcodes)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116*/
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000117#define MAGIC (3230 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118#define CACHEDIR "__pycache__"
Brett Cannon3adc7b72012-07-09 14:22:12 -0400119/* Current magic word as global. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000120static long pyc_magic = MAGIC;
121
Victor Stinner95872862011-03-07 18:20:56 +0100122/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000124
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200125/* Function from Parser/tokenizer.c */
126extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
127
Guido van Rossum771c6c81997-10-31 18:37:24 +0000128/* This table is defined in config.c: */
129extern struct _inittab _PyImport_Inittab[];
130
131struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000132
Victor Stinnerd0296212011-03-14 14:04:10 -0400133static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000134
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000135/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136
137void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000138_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Victor Stinnerd0296212011-03-14 14:04:10 -0400140 initstr = PyUnicode_InternFromString("__init__");
141 if (initstr == NULL)
142 Py_FatalError("Can't initialize import variables");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143}
144
Guido van Rossum25ce5661997-08-02 03:10:38 +0000145void
Just van Rossum52e14d62002-12-30 22:08:05 +0000146_PyImportHooks_Init(void)
147{
Brett Cannonfd074152012-04-14 14:10:13 -0400148 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000150
Brett Cannonfd074152012-04-14 14:10:13 -0400151 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 v = PyList_New(0);
153 if (v == NULL)
154 goto error;
155 err = PySys_SetObject("meta_path", v);
156 Py_DECREF(v);
157 if (err)
158 goto error;
159 v = PyDict_New();
160 if (v == NULL)
161 goto error;
162 err = PySys_SetObject("path_importer_cache", v);
163 Py_DECREF(v);
164 if (err)
165 goto error;
166 path_hooks = PyList_New(0);
167 if (path_hooks == NULL)
168 goto error;
169 err = PySys_SetObject("path_hooks", path_hooks);
170 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000171 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400172 PyErr_Print();
173 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +0200174 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
Brett Cannonfd074152012-04-14 14:10:13 -0400176 Py_DECREF(path_hooks);
177}
178
179void
180_PyImportZip_Init(void)
181{
182 PyObject *path_hooks, *zimpimport;
183 int err = 0;
184
185 path_hooks = PySys_GetObject("path_hooks");
186 if (path_hooks == NULL)
187 goto error;
188
189 if (Py_VerboseFlag)
190 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 zimpimport = PyImport_ImportModule("zipimport");
193 if (zimpimport == NULL) {
194 PyErr_Clear(); /* No zip import module -- okay */
195 if (Py_VerboseFlag)
196 PySys_WriteStderr("# can't import zipimport\n");
197 }
198 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200199 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200200 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
201 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 Py_DECREF(zimpimport);
203 if (zipimporter == NULL) {
204 PyErr_Clear(); /* No zipimporter object -- okay */
205 if (Py_VerboseFlag)
206 PySys_WriteStderr(
207 "# can't import zipimport.zipimporter\n");
208 }
209 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400210 /* sys.path_hooks.insert(0, zipimporter) */
211 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400213 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 if (Py_VerboseFlag)
217 PySys_WriteStderr(
218 "# installed zipimport hook\n");
219 }
220 }
Brett Cannonfd074152012-04-14 14:10:13 -0400221
222 return;
223
224 error:
225 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400226 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000227}
228
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000229/* Locking primitives to prevent parallel imports of the same module
230 in different threads to return with a partially loaded module.
231 These calls are serialized by the global interpreter lock. */
232
233#ifdef WITH_THREAD
234
Guido van Rossum49b56061998-10-01 20:42:43 +0000235#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000236
Guido van Rossum65d5b571998-12-21 19:32:43 +0000237static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000238static long import_lock_thread = -1;
239static int import_lock_level = 0;
240
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000241void
242_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 long me = PyThread_get_thread_ident();
245 if (me == -1)
246 return; /* Too bad */
247 if (import_lock == NULL) {
248 import_lock = PyThread_allocate_lock();
249 if (import_lock == NULL)
250 return; /* Nothing much we can do. */
251 }
252 if (import_lock_thread == me) {
253 import_lock_level++;
254 return;
255 }
256 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
257 {
258 PyThreadState *tstate = PyEval_SaveThread();
259 PyThread_acquire_lock(import_lock, 1);
260 PyEval_RestoreThread(tstate);
261 }
262 import_lock_thread = me;
263 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000264}
265
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000266int
267_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 long me = PyThread_get_thread_ident();
270 if (me == -1 || import_lock == NULL)
271 return 0; /* Too bad */
272 if (import_lock_thread != me)
273 return -1;
274 import_lock_level--;
275 if (import_lock_level == 0) {
276 import_lock_thread = -1;
277 PyThread_release_lock(import_lock);
278 }
279 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280}
281
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000282/* This function is called from PyOS_AfterFork to ensure that newly
283 created child processes do not share locks with the parent.
284 We now acquire the import lock around fork() calls but on some platforms
285 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000286
287void
288_PyImport_ReInitLock(void)
289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 if (import_lock != NULL)
291 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000292 if (import_lock_level > 1) {
293 /* Forked as a side effect of import */
294 long me = PyThread_get_thread_ident();
295 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100296 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000297 import_lock_thread = me;
298 import_lock_level--;
299 } else {
300 import_lock_thread = -1;
301 import_lock_level = 0;
302 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000303}
304
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000305#endif
306
Tim Peters69232342001-08-30 05:16:13 +0000307static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000308imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000309{
Tim Peters69232342001-08-30 05:16:13 +0000310#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000312#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000314#endif
315}
316
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000317static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000318imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000319{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000320#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000322#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_INCREF(Py_None);
324 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000325}
326
327static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000328imp_release_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 if (_PyImport_ReleaseLock() < 0) {
332 PyErr_SetString(PyExc_RuntimeError,
333 "not holding the import lock");
334 return NULL;
335 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000336#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 Py_INCREF(Py_None);
338 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000339}
340
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100341void
342_PyImport_Fini(void)
343{
344 Py_XDECREF(extensions);
345 extensions = NULL;
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100346#ifdef WITH_THREAD
347 if (import_lock != NULL) {
348 PyThread_free_lock(import_lock);
349 import_lock = NULL;
350 }
351#endif
352}
353
Guido van Rossum25ce5661997-08-02 03:10:38 +0000354/* Helper for sys */
355
356PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000357PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyInterpreterState *interp = PyThreadState_GET()->interp;
360 if (interp->modules == NULL)
361 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
362 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363}
364
Guido van Rossum3f5da241990-12-20 15:06:42 +0000365
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000366/* List of names to clear in sys */
367static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 "path", "argv", "ps1", "ps2",
369 "last_type", "last_value", "last_traceback",
370 "path_hooks", "path_importer_cache", "meta_path",
371 /* misc stuff */
372 "flags", "float_info",
373 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000374};
375
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000376static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 "stdin", "__stdin__",
378 "stdout", "__stdout__",
379 "stderr", "__stderr__",
380 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000381};
382
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000383
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000384/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000385
Guido van Rossum3f5da241990-12-20 15:06:42 +0000386void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000387PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyObject *key, *value, *dict;
391 PyInterpreterState *interp = PyThreadState_GET()->interp;
392 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (modules == NULL)
395 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 /* Delete some special variables first. These are common
398 places where user values hide and people complain when their
399 destructors fail. Since the modules containing them are
400 deleted *last* of all, they would come too late in the normal
401 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 value = PyDict_GetItemString(modules, "builtins");
404 if (value != NULL && PyModule_Check(value)) {
405 dict = PyModule_GetDict(value);
406 if (Py_VerboseFlag)
407 PySys_WriteStderr("# clear builtins._\n");
408 PyDict_SetItemString(dict, "_", Py_None);
409 }
410 value = PyDict_GetItemString(modules, "sys");
411 if (value != NULL && PyModule_Check(value)) {
412 char **p;
413 PyObject *v;
414 dict = PyModule_GetDict(value);
415 for (p = sys_deletes; *p != NULL; p++) {
416 if (Py_VerboseFlag)
417 PySys_WriteStderr("# clear sys.%s\n", *p);
418 PyDict_SetItemString(dict, *p, Py_None);
419 }
420 for (p = sys_files; *p != NULL; p+=2) {
421 if (Py_VerboseFlag)
422 PySys_WriteStderr("# restore sys.%s\n", *p);
423 v = PyDict_GetItemString(dict, *(p+1));
424 if (v == NULL)
425 v = Py_None;
426 PyDict_SetItemString(dict, *p, v);
427 }
428 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* First, delete __main__ */
431 value = PyDict_GetItemString(modules, "__main__");
432 if (value != NULL && PyModule_Check(value)) {
433 if (Py_VerboseFlag)
434 PySys_WriteStderr("# cleanup __main__\n");
435 _PyModule_Clear(value);
436 PyDict_SetItemString(modules, "__main__", Py_None);
437 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 /* The special treatment of "builtins" here is because even
440 when it's not referenced as a module, its dictionary is
441 referenced by almost every module's __builtins__. Since
442 deleting a module clears its dictionary (even if there are
443 references left to it), we need to delete the "builtins"
444 module last. Likewise, we don't delete sys until the very
445 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 Also note that we 'delete' modules by replacing their entry
448 in the modules dict with None, rather than really deleting
449 them; this avoids a rehash of the modules dictionary and
450 also marks them as "non existent" so they won't be
451 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Next, repeatedly delete modules with a reference count of
454 one (skipping builtins and sys) and delete them */
455 do {
456 ndone = 0;
457 pos = 0;
458 while (PyDict_Next(modules, &pos, &key, &value)) {
459 if (value->ob_refcnt != 1)
460 continue;
461 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100462 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100464 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 continue;
466 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100467 PySys_FormatStderr(
468 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 _PyModule_Clear(value);
470 PyDict_SetItem(modules, key, Py_None);
471 ndone++;
472 }
473 }
474 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Next, delete all modules (still skipping builtins and sys) */
477 pos = 0;
478 while (PyDict_Next(modules, &pos, &key, &value)) {
479 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100480 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100482 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 continue;
484 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100485 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 _PyModule_Clear(value);
487 PyDict_SetItem(modules, key, Py_None);
488 }
489 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 /* Next, delete sys and builtins (in that order) */
492 value = PyDict_GetItemString(modules, "sys");
493 if (value != NULL && PyModule_Check(value)) {
494 if (Py_VerboseFlag)
495 PySys_WriteStderr("# cleanup sys\n");
496 _PyModule_Clear(value);
497 PyDict_SetItemString(modules, "sys", Py_None);
498 }
499 value = PyDict_GetItemString(modules, "builtins");
500 if (value != NULL && PyModule_Check(value)) {
501 if (Py_VerboseFlag)
502 PySys_WriteStderr("# cleanup builtins\n");
503 _PyModule_Clear(value);
504 PyDict_SetItemString(modules, "builtins", Py_None);
505 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Finally, clear and delete the modules directory */
508 PyDict_Clear(modules);
509 interp->modules = NULL;
510 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000511}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000512
513
Barry Warsaw28a691b2010-04-17 00:19:56 +0000514/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000515
516long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000517PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000520}
521
522
Brett Cannon3adc7b72012-07-09 14:22:12 -0400523extern const char * _PySys_ImplCacheTag;
524
Barry Warsaw28a691b2010-04-17 00:19:56 +0000525const char *
526PyImport_GetMagicTag(void)
527{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400528 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000529}
530
Brett Cannon98979b82012-07-02 15:13:11 -0400531
Guido van Rossum25ce5661997-08-02 03:10:38 +0000532/* Magic for extension modules (built-in as well as dynamically
533 loaded). To prevent initializing an extension module more than
534 once, we keep a static dictionary 'extensions' keyed by module name
535 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000536 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100537 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538 immediately after the module initialization function succeeds. A
539 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100540 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000541
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000542 Modules which do support multiple initialization set their m_size
543 field to a non-negative number (indicating the size of the
544 module-specific state). They are still recorded in the extensions
545 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000546*/
547
548int
Victor Stinner95872862011-03-07 18:20:56 +0100549_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
550 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyObject *modules, *dict;
553 struct PyModuleDef *def;
554 if (extensions == NULL) {
555 extensions = PyDict_New();
556 if (extensions == NULL)
557 return -1;
558 }
559 if (mod == NULL || !PyModule_Check(mod)) {
560 PyErr_BadInternalCall();
561 return -1;
562 }
563 def = PyModule_GetDef(mod);
564 if (!def) {
565 PyErr_BadInternalCall();
566 return -1;
567 }
568 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100569 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 return -1;
571 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100572 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 return -1;
574 }
575 if (def->m_size == -1) {
576 if (def->m_base.m_copy) {
577 /* Somebody already imported the module,
578 likely under a different name.
579 XXX this should really not happen. */
580 Py_DECREF(def->m_base.m_copy);
581 def->m_base.m_copy = NULL;
582 }
583 dict = PyModule_GetDict(mod);
584 if (dict == NULL)
585 return -1;
586 def->m_base.m_copy = PyDict_Copy(dict);
587 if (def->m_base.m_copy == NULL)
588 return -1;
589 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000590 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592}
593
Victor Stinner49d3f252010-10-17 01:24:53 +0000594int
595_PyImport_FixupBuiltin(PyObject *mod, char *name)
596{
597 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100598 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100599 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100600 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000601 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100602 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
603 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000604 return res;
605}
606
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100608_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 PyObject *mod, *mdict;
611 PyModuleDef* def;
612 if (extensions == NULL)
613 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000614 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (def == NULL)
616 return NULL;
617 if (def->m_size == -1) {
618 /* Module does not support repeated initialization */
619 if (def->m_base.m_copy == NULL)
620 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100621 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (mod == NULL)
623 return NULL;
624 mdict = PyModule_GetDict(mod);
625 if (mdict == NULL)
626 return NULL;
627 if (PyDict_Update(mdict, def->m_base.m_copy))
628 return NULL;
629 }
630 else {
631 if (def->m_base.m_init == NULL)
632 return NULL;
633 mod = def->m_base.m_init();
634 if (mod == NULL)
635 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100636 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 Py_DECREF(mod);
638 }
639 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100640 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 Py_DECREF(mod);
642 return NULL;
643 }
644 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100645 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 name, filename);
647 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000648
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000649}
650
Victor Stinner49d3f252010-10-17 01:24:53 +0000651PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000652_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000653{
Victor Stinner95872862011-03-07 18:20:56 +0100654 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100655 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100656 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000657 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100658 res = _PyImport_FindExtensionObject(nameobj, nameobj);
659 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000660 return res;
661}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662
663/* Get the module object corresponding to a module name.
664 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000665 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000666 Because the former action is most common, THIS DOES NOT RETURN A
667 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000668
Guido van Rossum79f25d91997-04-29 20:08:16 +0000669PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000670PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyObject *modules = PyImport_GetModuleDict();
673 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000674
Victor Stinner27ee0892011-03-04 12:57:09 +0000675 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyModule_Check(m))
677 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000678 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (m == NULL)
680 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000681 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 Py_DECREF(m);
683 return NULL;
684 }
685 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000688}
689
Victor Stinner27ee0892011-03-04 12:57:09 +0000690PyObject *
691PyImport_AddModule(const char *name)
692{
693 PyObject *nameobj, *module;
694 nameobj = PyUnicode_FromString(name);
695 if (nameobj == NULL)
696 return NULL;
697 module = PyImport_AddModuleObject(nameobj);
698 Py_DECREF(nameobj);
699 return module;
700}
701
702
Tim Peters1cd70172004-08-02 03:52:12 +0000703/* Remove name from sys.modules, if it's there. */
704static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000705remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000708 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000710 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 Py_FatalError("import: deleting existing key in"
712 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000713}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
Victor Stinnerc9abda02011-03-14 13:33:46 -0400715static PyObject * get_sourcefile(PyObject *filename);
716static PyObject *make_source_pathname(PyObject *pathname);
Christian Heimes3b06e532008-01-07 20:12:44 +0000717
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000718/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000719 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
720 * removed from sys.modules, to avoid leaving damaged module objects
721 * in sys.modules. The caller may wish to restore the original
722 * module object (if any) in this case; PyImport_ReloadModule is an
723 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000724 *
725 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
726 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000727 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000728PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000729PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 return PyImport_ExecCodeModuleWithPathnames(
732 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000733}
734
735PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000736PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 return PyImport_ExecCodeModuleWithPathnames(
739 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000740}
741
742PyObject *
743PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000745{
Victor Stinner27ee0892011-03-04 12:57:09 +0000746 PyObject *m = NULL;
747 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
748
749 nameobj = PyUnicode_FromString(name);
750 if (nameobj == NULL)
751 return NULL;
752
753 if (pathname != NULL) {
754 pathobj = PyUnicode_DecodeFSDefault(pathname);
755 if (pathobj == NULL)
756 goto error;
757 } else
758 pathobj = NULL;
759 if (cpathname != NULL) {
760 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
761 if (cpathobj == NULL)
762 goto error;
763 } else
764 cpathobj = NULL;
765 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
766error:
767 Py_DECREF(nameobj);
768 Py_XDECREF(pathobj);
769 Py_XDECREF(cpathobj);
770 return m;
771}
772
773PyObject*
774PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
775 PyObject *cpathname)
776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyObject *modules = PyImport_GetModuleDict();
778 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000779
Victor Stinner27ee0892011-03-04 12:57:09 +0000780 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (m == NULL)
782 return NULL;
783 /* If the module is being reloaded, we get the old module back
784 and re-use its dict to exec the new code. */
785 d = PyModule_GetDict(m);
786 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
787 if (PyDict_SetItemString(d, "__builtins__",
788 PyEval_GetBuiltins()) != 0)
789 goto error;
790 }
791 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400793 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 if (v == NULL)
795 PyErr_Clear();
796 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000797 else
798 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (v == NULL) {
800 v = ((PyCodeObject *)co)->co_filename;
801 Py_INCREF(v);
802 }
803 if (PyDict_SetItemString(d, "__file__", v) != 0)
804 PyErr_Clear(); /* Not important enough to report */
805 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000808 if (cpathname != NULL)
809 v = cpathname;
810 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (PyDict_SetItemString(d, "__cached__", v) != 0)
813 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000814
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000815 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (v == NULL)
817 goto error;
818 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000819
Victor Stinner27ee0892011-03-04 12:57:09 +0000820 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000822 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 name);
824 return NULL;
825 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000830
831 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 remove_module(name);
833 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000834}
835
836
Martin v. Löwis2db72862011-10-23 17:29:08 +0200837/* Like rightmost_sep, but operate on unicode objects. */
838static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200839rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200840{
841 Py_ssize_t found, i;
842 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200843 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200844 c = PyUnicode_READ_CHAR(o, i);
845 if (c == SEP
846#ifdef ALTSEP
847 || c == ALTSEP
848#endif
849 )
850 {
851 found = i;
852 }
853 }
854 return found;
855}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400856
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857
Barry Warsaw28a691b2010-04-17 00:19:56 +0000858/* Given a pathname to a Python byte compiled file, return the path to the
859 source file, if the path matches the PEP 3147 format. This does not check
860 for any file existence, however, if the pyc file name does not match PEP
861 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400862 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863
Victor Stinnerc9abda02011-03-14 13:33:46 -0400864 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
865
866static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200867make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000868{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200869 Py_ssize_t left, right, dot0, dot1, len;
870 Py_ssize_t i, j;
871 PyObject *result;
872 int kind;
873 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400874
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200875 len = PyUnicode_GET_LENGTH(path);
876 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Look back two slashes from the end. In between these two slashes
880 must be the string __pycache__ or this is not a PEP 3147 style
881 path. It's possible for there to be only one slash.
882 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200883 right = rightmost_sep_obj(path, 0, len);
884 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200886 left = rightmost_sep_obj(path, 0, right);
887 if (left == -1)
888 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 else
890 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200891 if (right-left != sizeof(CACHEDIR)-1)
892 return NULL;
893 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
894 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
895 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* Now verify that the path component to the right of the last slash
898 has two dots in it.
899 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200900 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
901 if (dot0 < 0)
902 return NULL;
903 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
904 if (dot1 < 0)
905 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200907 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
908 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* This is a PEP 3147 path. Start by copying everything from the
911 start of pathname up to and including the leftmost slash. Then
912 copy the file's basename, removing the magic tag and adding a .py
913 suffix.
914 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200915 result = PyUnicode_New(left + (dot0-right) + 2,
916 PyUnicode_MAX_CHAR_VALUE(path));
917 if (!result)
918 return NULL;
919 kind = PyUnicode_KIND(result);
920 data = PyUnicode_DATA(result);
921 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
922 PyUnicode_CopyCharacters(result, left, path, right+1,
923 (j = dot0-right));
924 PyUnicode_WRITE(kind, data, i+j, 'p');
925 PyUnicode_WRITE(kind, data, i+j+1, 'y');
Victor Stinner8f825062012-04-27 13:55:39 +0200926 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200927 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000928}
929
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000930
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000931static void
932update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *constants, *tmp;
935 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (PyUnicode_Compare(co->co_filename, oldname))
938 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 tmp = co->co_filename;
941 co->co_filename = newname;
942 Py_INCREF(co->co_filename);
943 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 constants = co->co_consts;
946 n = PyTuple_GET_SIZE(constants);
947 for (i = 0; i < n; i++) {
948 tmp = PyTuple_GET_ITEM(constants, i);
949 if (PyCode_Check(tmp))
950 update_code_filenames((PyCodeObject *)tmp,
951 oldname, newname);
952 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000953}
954
Victor Stinner2f42ae52011-03-20 00:41:24 +0100955static void
956update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000957{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100958 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000959
Victor Stinner2f42ae52011-03-20 00:41:24 +0100960 if (PyUnicode_Compare(co->co_filename, newname) == 0)
961 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 oldname = co->co_filename;
964 Py_INCREF(oldname);
965 update_code_filenames(co, oldname, newname);
966 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000967}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000968
Brett Cannon442c9b92011-03-23 16:14:42 -0700969static PyObject *
970imp_fix_co_filename(PyObject *self, PyObject *args)
971{
972 PyObject *co;
973 PyObject *file_path;
974
975 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
976 return NULL;
977
978 if (!PyCode_Check(co)) {
979 PyErr_SetString(PyExc_TypeError,
980 "first argument must be a code object");
981 return NULL;
982 }
983
984 if (!PyUnicode_Check(file_path)) {
985 PyErr_SetString(PyExc_TypeError,
986 "second argument must be a string");
987 return NULL;
988 }
989
990 update_compiled_module((PyCodeObject*)co, file_path);
991
992 Py_RETURN_NONE;
993}
994
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000995
Christian Heimes3b06e532008-01-07 20:12:44 +0000996/* Get source file -> unicode or None
997 * Returns the path to the py file if available, else the given path
998 */
999static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001000get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 Py_ssize_t len;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001003 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001005 int err;
Victor Stinner81c39a82012-06-16 03:22:05 +02001006 void *data;
1007 unsigned int kind;
Christian Heimes3b06e532008-01-07 20:12:44 +00001008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001009 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001010 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001012
Victor Stinnerc9abda02011-03-14 13:33:46 -04001013 /* don't match *.pyc or *.pyo? */
Victor Stinner81c39a82012-06-16 03:22:05 +02001014 data = PyUnicode_DATA(filename);
1015 kind = PyUnicode_KIND(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001016 if (len < 5
Victor Stinner81c39a82012-06-16 03:22:05 +02001017 || PyUnicode_READ(kind, data, len-4) != '.'
1018 || (PyUnicode_READ(kind, data, len-3) != 'p'
1019 && PyUnicode_READ(kind, data, len-3) != 'P')
1020 || (PyUnicode_READ(kind, data, len-2) != 'y'
1021 && PyUnicode_READ(kind, data, len-2) != 'Y'))
Victor Stinnerc9abda02011-03-14 13:33:46 -04001022 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 /* Start by trying to turn PEP 3147 path into source path. If that
1025 * fails, just chop off the trailing character, i.e. legacy pyc path
1026 * to py.
1027 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001028 py = make_source_pathname(filename);
1029 if (py == NULL) {
1030 PyErr_Clear();
Victor Stinner81c39a82012-06-16 03:22:05 +02001031 py = PyUnicode_Substring(filename, 0, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001033 if (py == NULL)
1034 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001035
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001036 err = _Py_stat(py, &statbuf);
1037 if (err == -2)
1038 goto error;
Victor Stinner81c39a82012-06-16 03:22:05 +02001039 if (err == 0 && S_ISREG(statbuf.st_mode))
Victor Stinnerc9abda02011-03-14 13:33:46 -04001040 return py;
1041 Py_DECREF(py);
1042 goto unchanged;
1043
1044error:
1045 PyErr_Clear();
1046unchanged:
1047 Py_INCREF(filename);
1048 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001049}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001050
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001051/* Forward */
Victor Stinner53dc7352011-03-20 01:50:21 +01001052static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001053
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001054
1055/* Helper to test for built-in module */
1056
1057static int
Victor Stinner95872862011-03-07 18:20:56 +01001058is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001059{
Victor Stinner95872862011-03-07 18:20:56 +01001060 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001062 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1063 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (PyImport_Inittab[i].initfunc == NULL)
1065 return -1;
1066 else
1067 return 1;
1068 }
1069 }
1070 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001071}
1072
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001073
Just van Rossum52e14d62002-12-30 22:08:05 +00001074/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1075 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001076 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001077 that can handle the path item. Return None if no hook could;
1078 this tells our caller it should fall back to the builtin
1079 import mechanism. Cache the result in path_importer_cache.
1080 Returns a borrowed reference. */
1081
1082static PyObject *
1083get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyObject *importer;
1087 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* These conditions are the caller's responsibility: */
1090 assert(PyList_Check(path_hooks));
1091 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 nhooks = PyList_Size(path_hooks);
1094 if (nhooks < 0)
1095 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 importer = PyDict_GetItem(path_importer_cache, p);
1098 if (importer != NULL)
1099 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 /* set path_importer_cache[p] to None to avoid recursion */
1102 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1103 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 for (j = 0; j < nhooks; j++) {
1106 PyObject *hook = PyList_GetItem(path_hooks, j);
1107 if (hook == NULL)
1108 return NULL;
1109 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1110 if (importer != NULL)
1111 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1114 return NULL;
1115 }
1116 PyErr_Clear();
1117 }
1118 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001119 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 }
1121 if (importer != NULL) {
1122 int err = PyDict_SetItem(path_importer_cache, p, importer);
1123 Py_DECREF(importer);
1124 if (err != 0)
1125 return NULL;
1126 }
1127 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001128}
1129
Christian Heimes9cd17752007-11-18 19:35:23 +00001130PyAPI_FUNC(PyObject *)
1131PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1135 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1136 importer = get_path_importer(path_importer_cache,
1137 path_hooks, path);
1138 }
1139 }
1140 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1141 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001142}
1143
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001144
Victor Stinner95872862011-03-07 18:20:56 +01001145static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001146
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001147/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001148 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001149 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001150
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001151static int
Victor Stinner95872862011-03-07 18:20:56 +01001152init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001155
Victor Stinner95872862011-03-07 18:20:56 +01001156 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 for (p = PyImport_Inittab; p->name != NULL; p++) {
1160 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001161 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001162 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (p->initfunc == NULL) {
1164 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001165 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 name);
1167 return -1;
1168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 mod = (*p->initfunc)();
1170 if (mod == 0)
1171 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001172 /* Remember pointer to module init function. */
1173 def = PyModule_GetDef(mod);
1174 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001175 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 return -1;
1177 /* FixupExtension has put the module into sys.modules,
1178 so we can release our own reference. */
1179 Py_DECREF(mod);
1180 return 1;
1181 }
1182 }
1183 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001184}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001185
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001186
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001187/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001188
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001189static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001190find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001193
Victor Stinner53dc7352011-03-20 01:50:21 +01001194 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 for (p = PyImport_FrozenModules; ; p++) {
1198 if (p->name == NULL)
1199 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001200 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 break;
1202 }
1203 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001204}
1205
Guido van Rossum79f25d91997-04-29 20:08:16 +00001206static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001207get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 struct _frozen *p = find_frozen(name);
1210 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (p == NULL) {
1213 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001214 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 name);
1216 return NULL;
1217 }
1218 if (p->code == NULL) {
1219 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001220 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 name);
1222 return NULL;
1223 }
1224 size = p->size;
1225 if (size < 0)
1226 size = -size;
1227 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001228}
1229
Brett Cannon8d110132009-03-15 02:20:16 +00001230static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001231is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 struct _frozen *p = find_frozen(name);
1234 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (p == NULL) {
1237 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001238 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 name);
1240 return NULL;
1241 }
Brett Cannon8d110132009-03-15 02:20:16 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (size < 0)
1246 Py_RETURN_TRUE;
1247 else
1248 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001249}
1250
1251
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001252/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001253 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001254 an exception set if the initialization failed.
1255 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001256
1257int
Victor Stinner53dc7352011-03-20 01:50:21 +01001258PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001259{
Victor Stinner53dc7352011-03-20 01:50:21 +01001260 struct _frozen *p;
1261 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 int ispackage;
1263 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001264
Victor Stinner53dc7352011-03-20 01:50:21 +01001265 p = find_frozen(name);
1266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (p == NULL)
1268 return 0;
1269 if (p->code == NULL) {
1270 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001271 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 name);
1273 return -1;
1274 }
1275 size = p->size;
1276 ispackage = (size < 0);
1277 if (ispackage)
1278 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1280 if (co == NULL)
1281 return -1;
1282 if (!PyCode_Check(co)) {
1283 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001284 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 name);
1286 goto err_return;
1287 }
1288 if (ispackage) {
1289 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01001290 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001292 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (m == NULL)
1294 goto err_return;
1295 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 l = PyList_New(1);
1297 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 goto err_return;
1299 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001300 Py_INCREF(name);
1301 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 err = PyDict_SetItemString(d, "__path__", l);
1303 Py_DECREF(l);
1304 if (err != 0)
1305 goto err_return;
1306 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001307 path = PyUnicode_FromString("<frozen>");
1308 if (path == NULL)
1309 goto err_return;
1310 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1311 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (m == NULL)
1313 goto err_return;
1314 Py_DECREF(co);
1315 Py_DECREF(m);
1316 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001317err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 Py_DECREF(co);
1319 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001320}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001321
Victor Stinner53dc7352011-03-20 01:50:21 +01001322int
1323PyImport_ImportFrozenModule(char *name)
1324{
1325 PyObject *nameobj;
1326 int ret;
1327 nameobj = PyUnicode_InternFromString(name);
1328 if (nameobj == NULL)
1329 return -1;
1330 ret = PyImport_ImportFrozenModuleObject(nameobj);
1331 Py_DECREF(nameobj);
1332 return ret;
1333}
1334
Guido van Rossum74e6a111994-08-29 12:54:38 +00001335
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001336/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001337 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001338
Guido van Rossum79f25d91997-04-29 20:08:16 +00001339PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001340PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyObject *pname;
1343 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 pname = PyUnicode_FromString(name);
1346 if (pname == NULL)
1347 return NULL;
1348 result = PyImport_Import(pname);
1349 Py_DECREF(pname);
1350 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001351}
1352
Christian Heimes072c0f12008-01-03 23:01:04 +00001353/* Import a module without blocking
1354 *
1355 * At first it tries to fetch the module from sys.modules. If the module was
1356 * never loaded before it loads it with PyImport_ImportModule() unless another
1357 * thread holds the import lock. In the latter case the function raises an
1358 * ImportError instead of blocking.
1359 *
1360 * Returns the module object with incremented ref count.
1361 */
1362PyObject *
1363PyImport_ImportModuleNoBlock(const char *name)
1364{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001365 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001366}
1367
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001368
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001369/* Remove importlib frames from the traceback,
1370 * except in Verbose mode. */
1371static void
1372remove_importlib_frames(void)
1373{
1374 const char *importlib_filename = "<frozen importlib._bootstrap>";
1375 const char *exec_funcname = "_exec_module";
1376 int always_trim = 0;
1377 int in_importlib;
1378 PyObject *exception, *value, *base_tb, *tb;
1379 PyObject **prev_link, **outer_link;
1380
1381 /* Synopsis: if it's an ImportError, we trim all importlib chunks
1382 from the traceback. Otherwise, we trim only those chunks which
1383 end with a call to "_exec_module". */
1384
1385 PyErr_Fetch(&exception, &value, &base_tb);
1386 if (!exception || Py_VerboseFlag)
1387 goto done;
1388 if (PyType_IsSubtype((PyTypeObject *) exception,
1389 (PyTypeObject *) PyExc_ImportError))
1390 always_trim = 1;
1391
1392 prev_link = &base_tb;
1393 tb = base_tb;
1394 in_importlib = 0;
1395 while (tb != NULL) {
1396 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1397 PyObject *next = (PyObject *) traceback->tb_next;
1398 PyFrameObject *frame = traceback->tb_frame;
1399 PyCodeObject *code = frame->f_code;
1400 int now_in_importlib;
1401
1402 assert(PyTraceBack_Check(tb));
1403 now_in_importlib = (PyUnicode_CompareWithASCIIString(
1404 code->co_filename,
1405 importlib_filename) == 0);
1406 if (now_in_importlib && !in_importlib) {
1407 /* This is the link to this chunk of importlib tracebacks */
1408 outer_link = prev_link;
1409 }
1410 in_importlib = now_in_importlib;
1411
1412 if (in_importlib &&
1413 (always_trim ||
1414 PyUnicode_CompareWithASCIIString(code->co_name,
1415 exec_funcname) == 0)) {
1416 PyObject *tmp = *outer_link;
1417 *outer_link = next;
1418 Py_XINCREF(next);
1419 Py_DECREF(tmp);
1420 prev_link = outer_link;
1421 }
1422 else {
1423 prev_link = (PyObject **) &traceback->tb_next;
1424 }
1425 tb = next;
1426 }
1427done:
1428 PyErr_Restore(exception, value, base_tb);
1429}
1430
1431
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001432PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001433PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1434 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001435 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001436{
Brett Cannonfd074152012-04-14 14:10:13 -04001437 _Py_IDENTIFIER(__import__);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001438 _Py_IDENTIFIER(__initializing__);
Brett Cannonfd074152012-04-14 14:10:13 -04001439 _Py_IDENTIFIER(__package__);
1440 _Py_IDENTIFIER(__path__);
1441 _Py_IDENTIFIER(__name__);
1442 _Py_IDENTIFIER(_find_and_load);
1443 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001444 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001445 _Py_static_string(single_dot, ".");
1446 PyObject *abs_name = NULL;
1447 PyObject *builtins_import = NULL;
1448 PyObject *final_mod = NULL;
1449 PyObject *mod = NULL;
1450 PyObject *package = NULL;
1451 PyObject *globals = NULL;
1452 PyObject *fromlist = NULL;
1453 PyInterpreterState *interp = PyThreadState_GET()->interp;
1454
1455 /* Make sure to use default values so as to not have
1456 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1457 NULL argument. */
1458 if (given_globals == NULL) {
1459 globals = PyDict_New();
1460 if (globals == NULL) {
1461 goto error;
1462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 }
Brett Cannonfd074152012-04-14 14:10:13 -04001464 else {
1465 /* Only have to care what given_globals is if it will be used
1466 fortsomething. */
1467 if (level > 0 && !PyDict_Check(given_globals)) {
1468 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1469 goto error;
1470 }
1471 globals = given_globals;
1472 Py_INCREF(globals);
1473 }
1474
1475 if (given_fromlist == NULL) {
1476 fromlist = PyList_New(0);
1477 if (fromlist == NULL) {
1478 goto error;
1479 }
1480 }
1481 else {
1482 fromlist = given_fromlist;
1483 Py_INCREF(fromlist);
1484 }
1485 if (name == NULL) {
1486 PyErr_SetString(PyExc_ValueError, "Empty module name");
1487 goto error;
1488 }
1489
1490 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1491 for added performance. */
1492
1493 if (!PyUnicode_Check(name)) {
1494 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1495 goto error;
1496 }
1497 else if (PyUnicode_READY(name) < 0) {
1498 goto error;
1499 }
1500 if (level < 0) {
1501 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1502 goto error;
1503 }
1504 else if (level > 0) {
1505 package = _PyDict_GetItemId(globals, &PyId___package__);
1506 if (package != NULL && package != Py_None) {
1507 Py_INCREF(package);
1508 if (!PyUnicode_Check(package)) {
1509 PyErr_SetString(PyExc_TypeError, "package must be a string");
1510 goto error;
1511 }
1512 }
1513 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001514 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001515 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001516 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001517 goto error;
1518 }
1519 else if (!PyUnicode_Check(package)) {
1520 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1521 }
1522 Py_INCREF(package);
1523
1524 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001525 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001526 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1527 if (borrowed_dot == NULL) {
1528 goto error;
1529 }
Brett Cannon740fce02012-04-14 14:23:49 -04001530 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001531 Py_DECREF(package);
1532 if (partition == NULL) {
1533 goto error;
1534 }
1535 package = PyTuple_GET_ITEM(partition, 0);
1536 Py_INCREF(package);
1537 Py_DECREF(partition);
1538 }
1539 }
1540
1541 if (PyDict_GetItem(interp->modules, package) == NULL) {
1542 PyErr_Format(PyExc_SystemError,
1543 "Parent module %R not loaded, cannot perform relative "
1544 "import", package);
1545 goto error;
1546 }
1547 }
1548 else { /* level == 0 */
1549 if (PyUnicode_GET_LENGTH(name) == 0) {
1550 PyErr_SetString(PyExc_ValueError, "Empty module name");
1551 goto error;
1552 }
1553 package = Py_None;
1554 Py_INCREF(package);
1555 }
1556
1557 if (level > 0) {
1558 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1559 PyObject *base = NULL;
1560 int level_up = 1;
1561
1562 for (level_up = 1; level_up < level; level_up += 1) {
1563 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1564 if (last_dot == -2) {
1565 goto error;
1566 }
1567 else if (last_dot == -1) {
1568 PyErr_SetString(PyExc_ValueError,
1569 "attempted relative import beyond top-level "
1570 "package");
1571 goto error;
1572 }
1573 }
1574 base = PyUnicode_Substring(package, 0, last_dot);
1575 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001576 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001577
1578 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001579 seq = PyTuple_Pack(2, base, name);
1580 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001581 if (borrowed_dot == NULL || seq == NULL) {
1582 goto error;
1583 }
1584
1585 abs_name = PyUnicode_Join(borrowed_dot, seq);
1586 Py_DECREF(seq);
1587 if (abs_name == NULL) {
1588 goto error;
1589 }
1590 }
1591 else {
1592 abs_name = base;
1593 }
1594 }
1595 else {
1596 abs_name = name;
1597 Py_INCREF(abs_name);
1598 }
1599
Brian Curtine6b299f2012-04-14 14:19:33 -05001600#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001601 _PyImport_AcquireLock();
1602#endif
1603 /* From this point forward, goto error_with_unlock! */
1604 if (PyDict_Check(globals)) {
1605 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1606 }
1607 if (builtins_import == NULL) {
1608 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1609 if (builtins_import == NULL) {
1610 Py_FatalError("__import__ missing");
1611 }
1612 }
1613 Py_INCREF(builtins_import);
1614
1615 mod = PyDict_GetItem(interp->modules, abs_name);
1616 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001617 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1618 "None in sys.modules", abs_name);
1619 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05001620 PyErr_SetImportError(msg, abs_name, NULL);
1621 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001622 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001623 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001624 goto error_with_unlock;
1625 }
1626 else if (mod != NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001627 PyObject *value;
1628 int initializing = 0;
1629
Brett Cannonfd074152012-04-14 14:10:13 -04001630 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001631 /* Only call _bootstrap._lock_unlock_module() if __initializing__ is true. */
1632 value = _PyObject_GetAttrId(mod, &PyId___initializing__);
1633 if (value == NULL)
1634 PyErr_Clear();
1635 else {
1636 initializing = PyObject_IsTrue(value);
1637 Py_DECREF(value);
1638 if (initializing == -1)
1639 PyErr_Clear();
1640 }
1641 if (initializing > 0) {
1642 /* _bootstrap._lock_unlock_module() releases the import lock */
1643 value = _PyObject_CallMethodObjIdArgs(interp->importlib,
1644 &PyId__lock_unlock_module, abs_name,
1645 NULL);
1646 if (value == NULL)
1647 goto error;
1648 Py_DECREF(value);
1649 }
1650 else {
1651#ifdef WITH_THREAD
1652 if (_PyImport_ReleaseLock() < 0) {
1653 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1654 goto error;
1655 }
1656#endif
1657 }
Brett Cannonfd074152012-04-14 14:10:13 -04001658 }
1659 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001660 /* _bootstrap._find_and_load() releases the import lock */
Brett Cannonfd074152012-04-14 14:10:13 -04001661 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1662 &PyId__find_and_load, abs_name,
1663 builtins_import, NULL);
1664 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001665 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001666 }
1667 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001668 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001669
1670 if (PyObject_Not(fromlist)) {
1671 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1672 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001673 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001674 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1675
1676 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001677 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001678 }
1679
Brian Curtine6b299f2012-04-14 14:19:33 -05001680 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001681 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001682 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001683 }
1684
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001685 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1686 /* No dot in module name, simple exit */
1687 Py_DECREF(partition);
1688 final_mod = mod;
1689 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001690 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001691 }
1692
Brett Cannonfd074152012-04-14 14:10:13 -04001693 front = PyTuple_GET_ITEM(partition, 0);
1694 Py_INCREF(front);
1695 Py_DECREF(partition);
1696
1697 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001698 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001699 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001700 }
1701 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001702 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1703 PyUnicode_GET_LENGTH(front);
1704 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001705 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001706 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001707 Py_DECREF(front);
1708 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001709 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001710 }
Brett Cannonfd074152012-04-14 14:10:13 -04001711
1712 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001713 if (final_mod == NULL) {
1714 PyErr_Format(PyExc_KeyError,
1715 "%R not in sys.modules as expected",
1716 to_return);
1717 }
1718 else {
1719 Py_INCREF(final_mod);
1720 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001721 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001722 }
1723 }
1724 else {
1725 final_mod = mod;
1726 Py_INCREF(mod);
1727 }
1728 }
1729 else {
1730 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1731 &PyId__handle_fromlist, mod,
1732 fromlist, builtins_import,
1733 NULL);
1734 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001735 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001736
Brett Cannonfd074152012-04-14 14:10:13 -04001737 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001738#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001739 if (_PyImport_ReleaseLock() < 0) {
1740 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1741 }
1742#endif
1743 error:
1744 Py_XDECREF(abs_name);
1745 Py_XDECREF(builtins_import);
1746 Py_XDECREF(mod);
1747 Py_XDECREF(package);
1748 Py_XDECREF(globals);
1749 Py_XDECREF(fromlist);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001750 if (final_mod == NULL)
1751 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001752 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001753}
1754
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001755PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001756PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001757 PyObject *fromlist, int level)
1758{
1759 PyObject *nameobj, *mod;
1760 nameobj = PyUnicode_FromString(name);
1761 if (nameobj == NULL)
1762 return NULL;
1763 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1764 fromlist, level);
1765 Py_DECREF(nameobj);
1766 return mod;
1767}
1768
1769
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001770/* Re-import a module of any kind and return its module object, WITH
1771 INCREMENTED REFERENCE COUNT */
1772
Guido van Rossum79f25d91997-04-29 20:08:16 +00001773PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001774PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001775{
Brett Cannon62228db2012-04-29 14:38:11 -04001776 _Py_IDENTIFIER(reload);
1777 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001779 PyObject *imp = PyDict_GetItemString(modules, "imp");
1780 if (imp == NULL) {
1781 imp = PyImport_ImportModule("imp");
1782 if (imp == NULL) {
1783 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 }
Brett Cannon62228db2012-04-29 14:38:11 -04001786 else {
1787 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001789
Brett Cannon62228db2012-04-29 14:38:11 -04001790 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1791 Py_DECREF(imp);
1792 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001793}
1794
1795
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001796/* Higher-level import emulator which emulates the "import" statement
1797 more accurately -- it invokes the __import__() function from the
1798 builtins of the current globals. This means that the import is
1799 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001800 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001801 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001802 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001803 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001804
1805PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001806PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 static PyObject *silly_list = NULL;
1809 static PyObject *builtins_str = NULL;
1810 static PyObject *import_str = NULL;
1811 PyObject *globals = NULL;
1812 PyObject *import = NULL;
1813 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001814 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* Initialize constant string objects */
1818 if (silly_list == NULL) {
1819 import_str = PyUnicode_InternFromString("__import__");
1820 if (import_str == NULL)
1821 return NULL;
1822 builtins_str = PyUnicode_InternFromString("__builtins__");
1823 if (builtins_str == NULL)
1824 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001825 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (silly_list == NULL)
1827 return NULL;
1828 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 /* Get the builtins from current globals */
1831 globals = PyEval_GetGlobals();
1832 if (globals != NULL) {
1833 Py_INCREF(globals);
1834 builtins = PyObject_GetItem(globals, builtins_str);
1835 if (builtins == NULL)
1836 goto err;
1837 }
1838 else {
1839 /* No globals -- use standard builtins, and fake globals */
1840 builtins = PyImport_ImportModuleLevel("builtins",
1841 NULL, NULL, NULL, 0);
1842 if (builtins == NULL)
1843 return NULL;
1844 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1845 if (globals == NULL)
1846 goto err;
1847 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* Get the __import__ function from the builtins */
1850 if (PyDict_Check(builtins)) {
1851 import = PyObject_GetItem(builtins, import_str);
1852 if (import == NULL)
1853 PyErr_SetObject(PyExc_KeyError, import_str);
1854 }
1855 else
1856 import = PyObject_GetAttr(builtins, import_str);
1857 if (import == NULL)
1858 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001861 Always use absolute import here.
1862 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1864 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001865 if (r == NULL)
1866 goto err;
1867 Py_DECREF(r);
1868
1869 modules = PyImport_GetModuleDict();
1870 r = PyDict_GetItem(modules, module_name);
1871 if (r != NULL)
1872 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001873
1874 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 Py_XDECREF(globals);
1876 Py_XDECREF(builtins);
1877 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001880}
1881
1882
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001883/* Module 'imp' provides Python access to the primitives used for
1884 importing modules.
1885*/
1886
Guido van Rossum79f25d91997-04-29 20:08:16 +00001887static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001888imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 buf[0] = (char) ((magic >> 0) & 0xff);
1893 buf[1] = (char) ((magic >> 8) & 0xff);
1894 buf[2] = (char) ((magic >> 16) & 0xff);
1895 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00001898}
Barry Warsaw28a691b2010-04-17 00:19:56 +00001899
1900static PyObject *
1901imp_get_magic(PyObject *self, PyObject *noargs)
1902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001904}
1905
1906static PyObject *
Brett Cannon2657df42012-05-04 15:20:40 -04001907imp_extension_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001910 const char *suffix;
1911 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 list = PyList_New(0);
1914 if (list == NULL)
1915 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001916#ifdef HAVE_DYNAMIC_LOADING
1917 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1918 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (item == NULL) {
1920 Py_DECREF(list);
1921 return NULL;
1922 }
1923 if (PyList_Append(list, item) < 0) {
1924 Py_DECREF(list);
1925 Py_DECREF(item);
1926 return NULL;
1927 }
1928 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001929 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 }
Brett Cannon2657df42012-05-04 15:20:40 -04001931#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001933}
1934
Guido van Rossum79f25d91997-04-29 20:08:16 +00001935static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001936imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001937{
Victor Stinner95872862011-03-07 18:20:56 +01001938 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 int ret;
1940 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01001941 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 return NULL;
1943 ret = init_builtin(name);
1944 if (ret < 0)
1945 return NULL;
1946 if (ret == 0) {
1947 Py_INCREF(Py_None);
1948 return Py_None;
1949 }
Victor Stinner95872862011-03-07 18:20:56 +01001950 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 Py_XINCREF(m);
1952 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001953}
1954
Guido van Rossum79f25d91997-04-29 20:08:16 +00001955static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001956imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001957{
Victor Stinner53dc7352011-03-20 01:50:21 +01001958 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 int ret;
1960 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01001961 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001963 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (ret < 0)
1965 return NULL;
1966 if (ret == 0) {
1967 Py_INCREF(Py_None);
1968 return Py_None;
1969 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001970 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 Py_XINCREF(m);
1972 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001973}
1974
Guido van Rossum79f25d91997-04-29 20:08:16 +00001975static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001976imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001977{
Victor Stinner53dc7352011-03-20 01:50:21 +01001978 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00001979
Victor Stinner53dc7352011-03-20 01:50:21 +01001980 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 return NULL;
1982 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001983}
1984
Guido van Rossum79f25d91997-04-29 20:08:16 +00001985static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00001986imp_is_frozen_package(PyObject *self, PyObject *args)
1987{
Victor Stinner53dc7352011-03-20 01:50:21 +01001988 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00001989
Victor Stinner53dc7352011-03-20 01:50:21 +01001990 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 return NULL;
1992 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001993}
1994
1995static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001996imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001997{
Victor Stinner95872862011-03-07 18:20:56 +01001998 PyObject *name;
1999 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 return NULL;
2001 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002002}
2003
Guido van Rossum79f25d91997-04-29 20:08:16 +00002004static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002005imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002006{
Victor Stinner53dc7352011-03-20 01:50:21 +01002007 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01002009 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 return NULL;
2011 p = find_frozen(name);
2012 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
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) {
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002027 fp = _Py_fopen(pathname, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002028 if (fp == NULL) {
2029 Py_DECREF(pathname);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02002030 if (!PyErr_Occurred())
2031 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002033 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002035 else
2036 fp = NULL;
2037 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002038 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (fp)
2040 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002041 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002042}
2043
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002044#endif /* HAVE_DYNAMIC_LOADING */
2045
Barry Warsaw28a691b2010-04-17 00:19:56 +00002046
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002047/* Doc strings */
2048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002049PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002050"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002051
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002052PyDoc_STRVAR(doc_get_magic,
2053"get_magic() -> string\n\
2054Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002055
Brett Cannon2657df42012-05-04 15:20:40 -04002056PyDoc_STRVAR(doc_extension_suffixes,
2057"extension_suffixes() -> list of strings\n\
2058Returns the list of file suffixes used to identify extension modules.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002060PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002061"lock_held() -> boolean\n\
2062Return True if the import lock is currently held, else False.\n\
2063On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002064
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002065PyDoc_STRVAR(doc_acquire_lock,
2066"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002067Acquires the interpreter's import lock for the current thread.\n\
2068This lock should be used by import hooks to ensure thread-safety\n\
2069when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002070On platforms without threads, this function does nothing.");
2071
2072PyDoc_STRVAR(doc_release_lock,
2073"release_lock() -> None\n\
2074Release the interpreter's import lock.\n\
2075On platforms without threads, this function does nothing.");
2076
Guido van Rossum79f25d91997-04-29 20:08:16 +00002077static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
Brett Cannon2657df42012-05-04 15:20:40 -04002079 {"extension_suffixes", imp_extension_suffixes, METH_NOARGS,
2080 doc_extension_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2082 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2083 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2085 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
2086 {"init_builtin", imp_init_builtin, METH_VARARGS},
2087 {"init_frozen", imp_init_frozen, METH_VARARGS},
2088 {"is_builtin", imp_is_builtin, METH_VARARGS},
2089 {"is_frozen", imp_is_frozen, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002090#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002092#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07002093 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002095};
2096
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002097
Martin v. Löwis1a214512008-06-11 05:26:20 +00002098static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002100 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 doc_imp,
2102 0,
2103 imp_methods,
2104 NULL,
2105 NULL,
2106 NULL,
2107 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002108};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002109
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002110PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002111PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 m = PyModule_Create(&impmodule);
2116 if (m == NULL)
2117 goto failure;
2118 d = PyModule_GetDict(m);
2119 if (d == NULL)
2120 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002123 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_XDECREF(m);
2125 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002126}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002127
2128
Guido van Rossumb18618d2000-05-03 23:44:39 +00002129/* API for embedding applications that want to add their own entries
2130 to the table of built-in modules. This should normally be called
2131 *before* Py_Initialize(). When the table resize fails, -1 is
2132 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002133
2134 After a similar function by Just van Rossum. */
2135
2136int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002137PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 static struct _inittab *our_copy = NULL;
2140 struct _inittab *p;
2141 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* Count the number of entries in both tables */
2144 for (n = 0; newtab[n].name != NULL; n++)
2145 ;
2146 if (n == 0)
2147 return 0; /* Nothing to do */
2148 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2149 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Allocate new memory for the combined table */
2152 p = our_copy;
2153 PyMem_RESIZE(p, struct _inittab, i+n+1);
2154 if (p == NULL)
2155 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /* Copy the tables into the new memory */
2158 if (our_copy != PyImport_Inittab)
2159 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2160 PyImport_Inittab = our_copy = p;
2161 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002164}
2165
2166/* Shorthand to add a single entry given a name and a function */
2167
2168int
Brett Cannona826f322009-04-02 03:41:46 +00002169PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 newtab[0].name = (char *)name;
2176 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002179}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002180
2181#ifdef __cplusplus
2182}
2183#endif