blob: c63f760d07f624b45155a324aa3940919620e62c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000011#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000012#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013
Guido van Rossum55a83382000-09-20 20:31:38 +000014#ifdef HAVE_FCNTL_H
15#include <fcntl.h>
16#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000018extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000020
Christian Heimesd3eb5a152008-02-24 00:38:49 +000021#ifdef MS_WINDOWS
22/* for stat.st_mode */
23typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000024/* for _mkdir */
25#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000026#endif
27
Guido van Rossum21d335e1993-10-15 13:01:11 +000028
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000029/* Magic word to reject .pyc files generated by other Python versions.
30 It should change for each incompatible change to the bytecode.
31
32 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000033 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000034 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000035
Guido van Rossum45aecf42006-03-15 04:58:47 +000036 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000037 -U interpeter flag will cause MAGIC+1 being used. They have been
38 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000040 There were a variety of old schemes for setting the magic number.
41 The current working scheme is to increment the previous value by
42 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000043
Barry Warsaw28a691b2010-04-17 00:19:56 +000044 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
45 number also includes a new "magic tag", i.e. a human readable string used
46 to represent the magic number in __pycache__ directories. When you change
47 the magic number, you must also set a new unique magic tag. Generally this
48 can be named after the Python major version of the magic number bump, but
49 it can really be anything, as long as it's different than anything else
50 that's come before. The tags are included in the following table, starting
51 with Python 3.2a0.
52
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Known values:
54 Python 1.5: 20121
55 Python 1.5.1: 20121
56 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000058 Python 2.0: 50823
59 Python 2.0.1: 50823
60 Python 2.1: 60202
61 Python 2.1.1: 60202
62 Python 2.1.2: 60202
63 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000064 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000065 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000066 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000067 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000068 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000069 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000070 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000071 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000072 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000073 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
75 Python 2.5b3: 62111 (fix wrong code: x += yield)
76 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000078 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000079 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000081 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 3010 (removed UNARY_CONVERT)
83 3020 (added BUILD_SET)
84 3030 (added keyword-only parameters)
85 3040 (added signature annotations)
86 3050 (print becomes a function)
87 3060 (PEP 3115 metaclass syntax)
88 3061 (string literals become unicode)
89 3071 (PEP 3109 raise changes)
90 3081 (PEP 3137 make __file__ and __name__ unicode)
91 3091 (kill str8 interning)
92 3101 (merge from 2.6a0, see 62151)
93 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000094 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
95 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
96 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000100 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000102 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
103 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000104 Python 3.2a2 3180 (add DELETE_DEREF)
Benjamin Petersone7c15fa2011-06-19 19:54:45 -0500105 Python 3.3a0 3190 __class__ super closure changed
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 Python 3.3a0 3200 (__qualname__ added)
Benjamin Petersonabdb5522012-03-15 15:40:37 -0500107 3210 (added size modulo 2**32 to the pyc header)
108 Python 3.3a1 3220 (changed PEP 380 implementation)
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000109 Python 3.3a4 3230 (revert changes to implicit __class__ closure)
Tim Peters36515e22001-11-18 04:06:29 +0000110*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000111
Nick Coghlancd419ab2010-09-11 00:39:25 +0000112/* MAGIC must change whenever the bytecode emitted by the compiler may no
113 longer be understood by older implementations of the eval loop (usually
114 due to the addition of new opcodes)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000115*/
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000116#define MAGIC (3230 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000117#define CACHEDIR "__pycache__"
118/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000119static long pyc_magic = MAGIC;
120
Victor Stinner95872862011-03-07 18:20:56 +0100121/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000123
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200124/* Function from Parser/tokenizer.c */
125extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
126
Guido van Rossum771c6c81997-10-31 18:37:24 +0000127/* This table is defined in config.c: */
128extern struct _inittab _PyImport_Inittab[];
129
130struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000131
Victor Stinnerd0296212011-03-14 14:04:10 -0400132static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000133
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000134/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135
136void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000137_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138{
Victor Stinnerd0296212011-03-14 14:04:10 -0400139 initstr = PyUnicode_InternFromString("__init__");
140 if (initstr == NULL)
141 Py_FatalError("Can't initialize import variables");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142}
143
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144void
Just van Rossum52e14d62002-12-30 22:08:05 +0000145_PyImportHooks_Init(void)
146{
Brett Cannonfd074152012-04-14 14:10:13 -0400147 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000149
Brett Cannonfd074152012-04-14 14:10:13 -0400150 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 v = PyList_New(0);
152 if (v == NULL)
153 goto error;
154 err = PySys_SetObject("meta_path", v);
155 Py_DECREF(v);
156 if (err)
157 goto error;
158 v = PyDict_New();
159 if (v == NULL)
160 goto error;
161 err = PySys_SetObject("path_importer_cache", v);
162 Py_DECREF(v);
163 if (err)
164 goto error;
165 path_hooks = PyList_New(0);
166 if (path_hooks == NULL)
167 goto error;
168 err = PySys_SetObject("path_hooks", path_hooks);
169 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000170 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400171 PyErr_Print();
172 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +0200173 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 }
Brett Cannonfd074152012-04-14 14:10:13 -0400175 Py_DECREF(path_hooks);
176}
177
178void
179_PyImportZip_Init(void)
180{
181 PyObject *path_hooks, *zimpimport;
182 int err = 0;
183
184 path_hooks = PySys_GetObject("path_hooks");
185 if (path_hooks == NULL)
186 goto error;
187
188 if (Py_VerboseFlag)
189 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 zimpimport = PyImport_ImportModule("zipimport");
192 if (zimpimport == NULL) {
193 PyErr_Clear(); /* No zip import module -- okay */
194 if (Py_VerboseFlag)
195 PySys_WriteStderr("# can't import zipimport\n");
196 }
197 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200198 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200199 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
200 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 Py_DECREF(zimpimport);
202 if (zipimporter == NULL) {
203 PyErr_Clear(); /* No zipimporter object -- okay */
204 if (Py_VerboseFlag)
205 PySys_WriteStderr(
206 "# can't import zipimport.zipimporter\n");
207 }
208 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400209 /* sys.path_hooks.insert(0, zipimporter) */
210 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400212 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400214 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 if (Py_VerboseFlag)
216 PySys_WriteStderr(
217 "# installed zipimport hook\n");
218 }
219 }
Brett Cannonfd074152012-04-14 14:10:13 -0400220
221 return;
222
223 error:
224 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400225 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000226}
227
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000228/* Locking primitives to prevent parallel imports of the same module
229 in different threads to return with a partially loaded module.
230 These calls are serialized by the global interpreter lock. */
231
232#ifdef WITH_THREAD
233
Guido van Rossum49b56061998-10-01 20:42:43 +0000234#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000235
Guido van Rossum65d5b571998-12-21 19:32:43 +0000236static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000237static long import_lock_thread = -1;
238static int import_lock_level = 0;
239
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000240void
241_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 long me = PyThread_get_thread_ident();
244 if (me == -1)
245 return; /* Too bad */
246 if (import_lock == NULL) {
247 import_lock = PyThread_allocate_lock();
248 if (import_lock == NULL)
249 return; /* Nothing much we can do. */
250 }
251 if (import_lock_thread == me) {
252 import_lock_level++;
253 return;
254 }
255 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
256 {
257 PyThreadState *tstate = PyEval_SaveThread();
258 PyThread_acquire_lock(import_lock, 1);
259 PyEval_RestoreThread(tstate);
260 }
261 import_lock_thread = me;
262 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000263}
264
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000265int
266_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 long me = PyThread_get_thread_ident();
269 if (me == -1 || import_lock == NULL)
270 return 0; /* Too bad */
271 if (import_lock_thread != me)
272 return -1;
273 import_lock_level--;
274 if (import_lock_level == 0) {
275 import_lock_thread = -1;
276 PyThread_release_lock(import_lock);
277 }
278 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279}
280
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000281/* This function is called from PyOS_AfterFork to ensure that newly
282 created child processes do not share locks with the parent.
283 We now acquire the import lock around fork() calls but on some platforms
284 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000285
286void
287_PyImport_ReInitLock(void)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (import_lock != NULL)
290 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000291 if (import_lock_level > 1) {
292 /* Forked as a side effect of import */
293 long me = PyThread_get_thread_ident();
294 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100295 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000296 import_lock_thread = me;
297 import_lock_level--;
298 } else {
299 import_lock_thread = -1;
300 import_lock_level = 0;
301 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000302}
303
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304#endif
305
Tim Peters69232342001-08-30 05:16:13 +0000306static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000307imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000308{
Tim Peters69232342001-08-30 05:16:13 +0000309#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000311#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000313#endif
314}
315
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000316static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000317imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000318{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000319#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000321#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 Py_INCREF(Py_None);
323 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000324}
325
326static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000327imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000328{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000329#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (_PyImport_ReleaseLock() < 0) {
331 PyErr_SetString(PyExc_RuntimeError,
332 "not holding the import lock");
333 return NULL;
334 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000335#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 Py_INCREF(Py_None);
337 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000338}
339
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100340void
341_PyImport_Fini(void)
342{
343 Py_XDECREF(extensions);
344 extensions = NULL;
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100345#ifdef WITH_THREAD
346 if (import_lock != NULL) {
347 PyThread_free_lock(import_lock);
348 import_lock = NULL;
349 }
350#endif
351}
352
Guido van Rossum25ce5661997-08-02 03:10:38 +0000353/* Helper for sys */
354
355PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000356PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 PyInterpreterState *interp = PyThreadState_GET()->interp;
359 if (interp->modules == NULL)
360 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
361 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362}
363
Guido van Rossum3f5da241990-12-20 15:06:42 +0000364
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000365/* List of names to clear in sys */
366static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 "path", "argv", "ps1", "ps2",
368 "last_type", "last_value", "last_traceback",
369 "path_hooks", "path_importer_cache", "meta_path",
370 /* misc stuff */
371 "flags", "float_info",
372 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000373};
374
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000375static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 "stdin", "__stdin__",
377 "stdout", "__stdout__",
378 "stderr", "__stderr__",
379 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000380};
381
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000382
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000383/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000384
Guido van Rossum3f5da241990-12-20 15:06:42 +0000385void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000386PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyObject *key, *value, *dict;
390 PyInterpreterState *interp = PyThreadState_GET()->interp;
391 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (modules == NULL)
394 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* Delete some special variables first. These are common
397 places where user values hide and people complain when their
398 destructors fail. Since the modules containing them are
399 deleted *last* of all, they would come too late in the normal
400 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 value = PyDict_GetItemString(modules, "builtins");
403 if (value != NULL && PyModule_Check(value)) {
404 dict = PyModule_GetDict(value);
405 if (Py_VerboseFlag)
406 PySys_WriteStderr("# clear builtins._\n");
407 PyDict_SetItemString(dict, "_", Py_None);
408 }
409 value = PyDict_GetItemString(modules, "sys");
410 if (value != NULL && PyModule_Check(value)) {
411 char **p;
412 PyObject *v;
413 dict = PyModule_GetDict(value);
414 for (p = sys_deletes; *p != NULL; p++) {
415 if (Py_VerboseFlag)
416 PySys_WriteStderr("# clear sys.%s\n", *p);
417 PyDict_SetItemString(dict, *p, Py_None);
418 }
419 for (p = sys_files; *p != NULL; p+=2) {
420 if (Py_VerboseFlag)
421 PySys_WriteStderr("# restore sys.%s\n", *p);
422 v = PyDict_GetItemString(dict, *(p+1));
423 if (v == NULL)
424 v = Py_None;
425 PyDict_SetItemString(dict, *p, v);
426 }
427 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* First, delete __main__ */
430 value = PyDict_GetItemString(modules, "__main__");
431 if (value != NULL && PyModule_Check(value)) {
432 if (Py_VerboseFlag)
433 PySys_WriteStderr("# cleanup __main__\n");
434 _PyModule_Clear(value);
435 PyDict_SetItemString(modules, "__main__", Py_None);
436 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* The special treatment of "builtins" here is because even
439 when it's not referenced as a module, its dictionary is
440 referenced by almost every module's __builtins__. Since
441 deleting a module clears its dictionary (even if there are
442 references left to it), we need to delete the "builtins"
443 module last. Likewise, we don't delete sys until the very
444 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 Also note that we 'delete' modules by replacing their entry
447 in the modules dict with None, rather than really deleting
448 them; this avoids a rehash of the modules dictionary and
449 also marks them as "non existent" so they won't be
450 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 /* Next, repeatedly delete modules with a reference count of
453 one (skipping builtins and sys) and delete them */
454 do {
455 ndone = 0;
456 pos = 0;
457 while (PyDict_Next(modules, &pos, &key, &value)) {
458 if (value->ob_refcnt != 1)
459 continue;
460 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100461 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100463 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 continue;
465 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100466 PySys_FormatStderr(
467 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 _PyModule_Clear(value);
469 PyDict_SetItem(modules, key, Py_None);
470 ndone++;
471 }
472 }
473 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* Next, delete all modules (still skipping builtins and sys) */
476 pos = 0;
477 while (PyDict_Next(modules, &pos, &key, &value)) {
478 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100479 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100481 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 continue;
483 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100484 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 _PyModule_Clear(value);
486 PyDict_SetItem(modules, key, Py_None);
487 }
488 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Next, delete sys and builtins (in that order) */
491 value = PyDict_GetItemString(modules, "sys");
492 if (value != NULL && PyModule_Check(value)) {
493 if (Py_VerboseFlag)
494 PySys_WriteStderr("# cleanup sys\n");
495 _PyModule_Clear(value);
496 PyDict_SetItemString(modules, "sys", Py_None);
497 }
498 value = PyDict_GetItemString(modules, "builtins");
499 if (value != NULL && PyModule_Check(value)) {
500 if (Py_VerboseFlag)
501 PySys_WriteStderr("# cleanup builtins\n");
502 _PyModule_Clear(value);
503 PyDict_SetItemString(modules, "builtins", Py_None);
504 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* Finally, clear and delete the modules directory */
507 PyDict_Clear(modules);
508 interp->modules = NULL;
509 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000510}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000511
512
Barry Warsaw28a691b2010-04-17 00:19:56 +0000513/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000514
515long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000516PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000519}
520
521
Barry Warsaw28a691b2010-04-17 00:19:56 +0000522const char *
523PyImport_GetMagicTag(void)
524{
Brett Cannon98979b82012-07-02 15:13:11 -0400525 PyObject *impl, *tag;
526 const char *raw_tag;
527
528 /* We could also pull it from imp or importlib. */
529 impl = PySys_GetObject("implementation");
530 if (impl == NULL)
531 return NULL;
532 tag = PyObject_GetAttrString(impl, "cache_tag");
533 if (tag == NULL)
534 return NULL;
535 raw_tag = PyUnicode_DATA(tag);
536 Py_DECREF(tag);
537 return raw_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000538}
539
Brett Cannon98979b82012-07-02 15:13:11 -0400540
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541/* Magic for extension modules (built-in as well as dynamically
542 loaded). To prevent initializing an extension module more than
543 once, we keep a static dictionary 'extensions' keyed by module name
544 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000545 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100546 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547 immediately after the module initialization function succeeds. A
548 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100549 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000551 Modules which do support multiple initialization set their m_size
552 field to a non-negative number (indicating the size of the
553 module-specific state). They are still recorded in the extensions
554 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000555*/
556
557int
Victor Stinner95872862011-03-07 18:20:56 +0100558_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
559 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 PyObject *modules, *dict;
562 struct PyModuleDef *def;
563 if (extensions == NULL) {
564 extensions = PyDict_New();
565 if (extensions == NULL)
566 return -1;
567 }
568 if (mod == NULL || !PyModule_Check(mod)) {
569 PyErr_BadInternalCall();
570 return -1;
571 }
572 def = PyModule_GetDef(mod);
573 if (!def) {
574 PyErr_BadInternalCall();
575 return -1;
576 }
577 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100578 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 return -1;
580 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100581 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return -1;
583 }
584 if (def->m_size == -1) {
585 if (def->m_base.m_copy) {
586 /* Somebody already imported the module,
587 likely under a different name.
588 XXX this should really not happen. */
589 Py_DECREF(def->m_base.m_copy);
590 def->m_base.m_copy = NULL;
591 }
592 dict = PyModule_GetDict(mod);
593 if (dict == NULL)
594 return -1;
595 def->m_base.m_copy = PyDict_Copy(dict);
596 if (def->m_base.m_copy == NULL)
597 return -1;
598 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000599 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601}
602
Victor Stinner49d3f252010-10-17 01:24:53 +0000603int
604_PyImport_FixupBuiltin(PyObject *mod, char *name)
605{
606 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100607 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100608 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100609 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000610 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100611 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
612 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000613 return res;
614}
615
Guido van Rossum25ce5661997-08-02 03:10:38 +0000616PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100617_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyObject *mod, *mdict;
620 PyModuleDef* def;
621 if (extensions == NULL)
622 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000623 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (def == NULL)
625 return NULL;
626 if (def->m_size == -1) {
627 /* Module does not support repeated initialization */
628 if (def->m_base.m_copy == NULL)
629 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100630 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (mod == NULL)
632 return NULL;
633 mdict = PyModule_GetDict(mod);
634 if (mdict == NULL)
635 return NULL;
636 if (PyDict_Update(mdict, def->m_base.m_copy))
637 return NULL;
638 }
639 else {
640 if (def->m_base.m_init == NULL)
641 return NULL;
642 mod = def->m_base.m_init();
643 if (mod == NULL)
644 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100645 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 Py_DECREF(mod);
647 }
648 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100649 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 Py_DECREF(mod);
651 return NULL;
652 }
653 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100654 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 name, filename);
656 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000657
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658}
659
Victor Stinner49d3f252010-10-17 01:24:53 +0000660PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000661_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000662{
Victor Stinner95872862011-03-07 18:20:56 +0100663 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100664 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100665 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000666 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100667 res = _PyImport_FindExtensionObject(nameobj, nameobj);
668 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000669 return res;
670}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000671
672/* Get the module object corresponding to a module name.
673 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000674 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000675 Because the former action is most common, THIS DOES NOT RETURN A
676 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677
Guido van Rossum79f25d91997-04-29 20:08:16 +0000678PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000679PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 PyObject *modules = PyImport_GetModuleDict();
682 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000683
Victor Stinner27ee0892011-03-04 12:57:09 +0000684 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyModule_Check(m))
686 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000687 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (m == NULL)
689 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000690 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 Py_DECREF(m);
692 return NULL;
693 }
694 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697}
698
Victor Stinner27ee0892011-03-04 12:57:09 +0000699PyObject *
700PyImport_AddModule(const char *name)
701{
702 PyObject *nameobj, *module;
703 nameobj = PyUnicode_FromString(name);
704 if (nameobj == NULL)
705 return NULL;
706 module = PyImport_AddModuleObject(nameobj);
707 Py_DECREF(nameobj);
708 return module;
709}
710
711
Tim Peters1cd70172004-08-02 03:52:12 +0000712/* Remove name from sys.modules, if it's there. */
713static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000714remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000717 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000719 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 Py_FatalError("import: deleting existing key in"
721 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000722}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000723
Victor Stinnerc9abda02011-03-14 13:33:46 -0400724static PyObject * get_sourcefile(PyObject *filename);
725static PyObject *make_source_pathname(PyObject *pathname);
Christian Heimes3b06e532008-01-07 20:12:44 +0000726
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000727/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000728 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
729 * removed from sys.modules, to avoid leaving damaged module objects
730 * in sys.modules. The caller may wish to restore the original
731 * module object (if any) in this case; PyImport_ReloadModule is an
732 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000733 *
734 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
735 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000736 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000737PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000738PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return PyImport_ExecCodeModuleWithPathnames(
741 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000742}
743
744PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000745PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return PyImport_ExecCodeModuleWithPathnames(
748 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000749}
750
751PyObject *
752PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000754{
Victor Stinner27ee0892011-03-04 12:57:09 +0000755 PyObject *m = NULL;
756 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
757
758 nameobj = PyUnicode_FromString(name);
759 if (nameobj == NULL)
760 return NULL;
761
762 if (pathname != NULL) {
763 pathobj = PyUnicode_DecodeFSDefault(pathname);
764 if (pathobj == NULL)
765 goto error;
766 } else
767 pathobj = NULL;
768 if (cpathname != NULL) {
769 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
770 if (cpathobj == NULL)
771 goto error;
772 } else
773 cpathobj = NULL;
774 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
775error:
776 Py_DECREF(nameobj);
777 Py_XDECREF(pathobj);
778 Py_XDECREF(cpathobj);
779 return m;
780}
781
782PyObject*
783PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
784 PyObject *cpathname)
785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *modules = PyImport_GetModuleDict();
787 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788
Victor Stinner27ee0892011-03-04 12:57:09 +0000789 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (m == NULL)
791 return NULL;
792 /* If the module is being reloaded, we get the old module back
793 and re-use its dict to exec the new code. */
794 d = PyModule_GetDict(m);
795 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
796 if (PyDict_SetItemString(d, "__builtins__",
797 PyEval_GetBuiltins()) != 0)
798 goto error;
799 }
800 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400802 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (v == NULL)
804 PyErr_Clear();
805 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000806 else
807 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (v == NULL) {
809 v = ((PyCodeObject *)co)->co_filename;
810 Py_INCREF(v);
811 }
812 if (PyDict_SetItemString(d, "__file__", v) != 0)
813 PyErr_Clear(); /* Not important enough to report */
814 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000817 if (cpathname != NULL)
818 v = cpathname;
819 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (PyDict_SetItemString(d, "__cached__", v) != 0)
822 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000823
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000824 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (v == NULL)
826 goto error;
827 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000828
Victor Stinner27ee0892011-03-04 12:57:09 +0000829 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000831 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 name);
833 return NULL;
834 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000839
840 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 remove_module(name);
842 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000843}
844
845
Martin v. Löwis2db72862011-10-23 17:29:08 +0200846/* Like rightmost_sep, but operate on unicode objects. */
847static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200848rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200849{
850 Py_ssize_t found, i;
851 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200852 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200853 c = PyUnicode_READ_CHAR(o, i);
854 if (c == SEP
855#ifdef ALTSEP
856 || c == ALTSEP
857#endif
858 )
859 {
860 found = i;
861 }
862 }
863 return found;
864}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400865
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000866
Barry Warsaw28a691b2010-04-17 00:19:56 +0000867/* Given a pathname to a Python byte compiled file, return the path to the
868 source file, if the path matches the PEP 3147 format. This does not check
869 for any file existence, however, if the pyc file name does not match PEP
870 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400871 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872
Victor Stinnerc9abda02011-03-14 13:33:46 -0400873 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
874
875static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200876make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000877{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200878 Py_ssize_t left, right, dot0, dot1, len;
879 Py_ssize_t i, j;
880 PyObject *result;
881 int kind;
882 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400883
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200884 len = PyUnicode_GET_LENGTH(path);
885 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200886 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Look back two slashes from the end. In between these two slashes
889 must be the string __pycache__ or this is not a PEP 3147 style
890 path. It's possible for there to be only one slash.
891 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200892 right = rightmost_sep_obj(path, 0, len);
893 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200895 left = rightmost_sep_obj(path, 0, right);
896 if (left == -1)
897 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 else
899 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200900 if (right-left != sizeof(CACHEDIR)-1)
901 return NULL;
902 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
903 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
904 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Now verify that the path component to the right of the last slash
907 has two dots in it.
908 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200909 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
910 if (dot0 < 0)
911 return NULL;
912 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
913 if (dot1 < 0)
914 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200916 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
917 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* This is a PEP 3147 path. Start by copying everything from the
920 start of pathname up to and including the leftmost slash. Then
921 copy the file's basename, removing the magic tag and adding a .py
922 suffix.
923 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200924 result = PyUnicode_New(left + (dot0-right) + 2,
925 PyUnicode_MAX_CHAR_VALUE(path));
926 if (!result)
927 return NULL;
928 kind = PyUnicode_KIND(result);
929 data = PyUnicode_DATA(result);
930 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
931 PyUnicode_CopyCharacters(result, left, path, right+1,
932 (j = dot0-right));
933 PyUnicode_WRITE(kind, data, i+j, 'p');
934 PyUnicode_WRITE(kind, data, i+j+1, 'y');
Victor Stinner8f825062012-04-27 13:55:39 +0200935 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200936 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000937}
938
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000939
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000940static void
941update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *constants, *tmp;
944 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (PyUnicode_Compare(co->co_filename, oldname))
947 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 tmp = co->co_filename;
950 co->co_filename = newname;
951 Py_INCREF(co->co_filename);
952 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 constants = co->co_consts;
955 n = PyTuple_GET_SIZE(constants);
956 for (i = 0; i < n; i++) {
957 tmp = PyTuple_GET_ITEM(constants, i);
958 if (PyCode_Check(tmp))
959 update_code_filenames((PyCodeObject *)tmp,
960 oldname, newname);
961 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000962}
963
Victor Stinner2f42ae52011-03-20 00:41:24 +0100964static void
965update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000966{
Victor Stinner2f42ae52011-03-20 00:41:24 +0100967 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000968
Victor Stinner2f42ae52011-03-20 00:41:24 +0100969 if (PyUnicode_Compare(co->co_filename, newname) == 0)
970 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 oldname = co->co_filename;
973 Py_INCREF(oldname);
974 update_code_filenames(co, oldname, newname);
975 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000976}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000977
Brett Cannon442c9b92011-03-23 16:14:42 -0700978static PyObject *
979imp_fix_co_filename(PyObject *self, PyObject *args)
980{
981 PyObject *co;
982 PyObject *file_path;
983
984 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
985 return NULL;
986
987 if (!PyCode_Check(co)) {
988 PyErr_SetString(PyExc_TypeError,
989 "first argument must be a code object");
990 return NULL;
991 }
992
993 if (!PyUnicode_Check(file_path)) {
994 PyErr_SetString(PyExc_TypeError,
995 "second argument must be a string");
996 return NULL;
997 }
998
999 update_compiled_module((PyCodeObject*)co, file_path);
1000
1001 Py_RETURN_NONE;
1002}
1003
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001004
Christian Heimes3b06e532008-01-07 20:12:44 +00001005/* Get source file -> unicode or None
1006 * Returns the path to the py file if available, else the given path
1007 */
1008static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001009get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 Py_ssize_t len;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001012 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001014 int err;
Victor Stinner81c39a82012-06-16 03:22:05 +02001015 void *data;
1016 unsigned int kind;
Christian Heimes3b06e532008-01-07 20:12:44 +00001017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001018 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001019 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001021
Victor Stinnerc9abda02011-03-14 13:33:46 -04001022 /* don't match *.pyc or *.pyo? */
Victor Stinner81c39a82012-06-16 03:22:05 +02001023 data = PyUnicode_DATA(filename);
1024 kind = PyUnicode_KIND(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001025 if (len < 5
Victor Stinner81c39a82012-06-16 03:22:05 +02001026 || PyUnicode_READ(kind, data, len-4) != '.'
1027 || (PyUnicode_READ(kind, data, len-3) != 'p'
1028 && PyUnicode_READ(kind, data, len-3) != 'P')
1029 || (PyUnicode_READ(kind, data, len-2) != 'y'
1030 && PyUnicode_READ(kind, data, len-2) != 'Y'))
Victor Stinnerc9abda02011-03-14 13:33:46 -04001031 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 /* Start by trying to turn PEP 3147 path into source path. If that
1034 * fails, just chop off the trailing character, i.e. legacy pyc path
1035 * to py.
1036 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001037 py = make_source_pathname(filename);
1038 if (py == NULL) {
1039 PyErr_Clear();
Victor Stinner81c39a82012-06-16 03:22:05 +02001040 py = PyUnicode_Substring(filename, 0, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001042 if (py == NULL)
1043 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001044
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001045 err = _Py_stat(py, &statbuf);
1046 if (err == -2)
1047 goto error;
Victor Stinner81c39a82012-06-16 03:22:05 +02001048 if (err == 0 && S_ISREG(statbuf.st_mode))
Victor Stinnerc9abda02011-03-14 13:33:46 -04001049 return py;
1050 Py_DECREF(py);
1051 goto unchanged;
1052
1053error:
1054 PyErr_Clear();
1055unchanged:
1056 Py_INCREF(filename);
1057 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001058}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001059
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001060/* Forward */
Victor Stinner53dc7352011-03-20 01:50:21 +01001061static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001062
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001063
1064/* Helper to test for built-in module */
1065
1066static int
Victor Stinner95872862011-03-07 18:20:56 +01001067is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001068{
Victor Stinner95872862011-03-07 18:20:56 +01001069 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001071 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1072 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (PyImport_Inittab[i].initfunc == NULL)
1074 return -1;
1075 else
1076 return 1;
1077 }
1078 }
1079 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001080}
1081
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001082
Just van Rossum52e14d62002-12-30 22:08:05 +00001083/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1084 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001085 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001086 that can handle the path item. Return None if no hook could;
1087 this tells our caller it should fall back to the builtin
1088 import mechanism. Cache the result in path_importer_cache.
1089 Returns a borrowed reference. */
1090
1091static PyObject *
1092get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyObject *importer;
1096 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 /* These conditions are the caller's responsibility: */
1099 assert(PyList_Check(path_hooks));
1100 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 nhooks = PyList_Size(path_hooks);
1103 if (nhooks < 0)
1104 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 importer = PyDict_GetItem(path_importer_cache, p);
1107 if (importer != NULL)
1108 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 /* set path_importer_cache[p] to None to avoid recursion */
1111 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1112 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 for (j = 0; j < nhooks; j++) {
1115 PyObject *hook = PyList_GetItem(path_hooks, j);
1116 if (hook == NULL)
1117 return NULL;
1118 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1119 if (importer != NULL)
1120 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1123 return NULL;
1124 }
1125 PyErr_Clear();
1126 }
1127 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001128 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
1130 if (importer != NULL) {
1131 int err = PyDict_SetItem(path_importer_cache, p, importer);
1132 Py_DECREF(importer);
1133 if (err != 0)
1134 return NULL;
1135 }
1136 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001137}
1138
Christian Heimes9cd17752007-11-18 19:35:23 +00001139PyAPI_FUNC(PyObject *)
1140PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1144 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1145 importer = get_path_importer(path_importer_cache,
1146 path_hooks, path);
1147 }
1148 }
1149 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1150 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001151}
1152
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001153
Victor Stinner95872862011-03-07 18:20:56 +01001154static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001155
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001156/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001157 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001158 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001159
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001160static int
Victor Stinner95872862011-03-07 18:20:56 +01001161init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001164
Victor Stinner95872862011-03-07 18:20:56 +01001165 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 for (p = PyImport_Inittab; p->name != NULL; p++) {
1169 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001170 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001171 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (p->initfunc == NULL) {
1173 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001174 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 name);
1176 return -1;
1177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 mod = (*p->initfunc)();
1179 if (mod == 0)
1180 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001181 /* Remember pointer to module init function. */
1182 def = PyModule_GetDef(mod);
1183 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001184 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 return -1;
1186 /* FixupExtension has put the module into sys.modules,
1187 so we can release our own reference. */
1188 Py_DECREF(mod);
1189 return 1;
1190 }
1191 }
1192 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001193}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001194
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001195
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001196/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001197
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001198static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001199find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001202
Victor Stinner53dc7352011-03-20 01:50:21 +01001203 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 for (p = PyImport_FrozenModules; ; p++) {
1207 if (p->name == NULL)
1208 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001209 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 break;
1211 }
1212 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001213}
1214
Guido van Rossum79f25d91997-04-29 20:08:16 +00001215static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001216get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 struct _frozen *p = find_frozen(name);
1219 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 if (p == NULL) {
1222 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001223 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 name);
1225 return NULL;
1226 }
1227 if (p->code == NULL) {
1228 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001229 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 name);
1231 return NULL;
1232 }
1233 size = p->size;
1234 if (size < 0)
1235 size = -size;
1236 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001237}
1238
Brett Cannon8d110132009-03-15 02:20:16 +00001239static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001240is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 struct _frozen *p = find_frozen(name);
1243 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (p == NULL) {
1246 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001247 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 name);
1249 return NULL;
1250 }
Brett Cannon8d110132009-03-15 02:20:16 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (size < 0)
1255 Py_RETURN_TRUE;
1256 else
1257 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001258}
1259
1260
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001261/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001262 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001263 an exception set if the initialization failed.
1264 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001265
1266int
Victor Stinner53dc7352011-03-20 01:50:21 +01001267PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001268{
Victor Stinner53dc7352011-03-20 01:50:21 +01001269 struct _frozen *p;
1270 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 int ispackage;
1272 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001273
Victor Stinner53dc7352011-03-20 01:50:21 +01001274 p = find_frozen(name);
1275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (p == NULL)
1277 return 0;
1278 if (p->code == NULL) {
1279 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001280 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 name);
1282 return -1;
1283 }
1284 size = p->size;
1285 ispackage = (size < 0);
1286 if (ispackage)
1287 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1289 if (co == NULL)
1290 return -1;
1291 if (!PyCode_Check(co)) {
1292 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001293 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 name);
1295 goto err_return;
1296 }
1297 if (ispackage) {
1298 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01001299 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001301 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (m == NULL)
1303 goto err_return;
1304 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 l = PyList_New(1);
1306 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 goto err_return;
1308 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001309 Py_INCREF(name);
1310 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 err = PyDict_SetItemString(d, "__path__", l);
1312 Py_DECREF(l);
1313 if (err != 0)
1314 goto err_return;
1315 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001316 path = PyUnicode_FromString("<frozen>");
1317 if (path == NULL)
1318 goto err_return;
1319 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1320 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (m == NULL)
1322 goto err_return;
1323 Py_DECREF(co);
1324 Py_DECREF(m);
1325 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001326err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 Py_DECREF(co);
1328 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001329}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001330
Victor Stinner53dc7352011-03-20 01:50:21 +01001331int
1332PyImport_ImportFrozenModule(char *name)
1333{
1334 PyObject *nameobj;
1335 int ret;
1336 nameobj = PyUnicode_InternFromString(name);
1337 if (nameobj == NULL)
1338 return -1;
1339 ret = PyImport_ImportFrozenModuleObject(nameobj);
1340 Py_DECREF(nameobj);
1341 return ret;
1342}
1343
Guido van Rossum74e6a111994-08-29 12:54:38 +00001344
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001345/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001346 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001347
Guido van Rossum79f25d91997-04-29 20:08:16 +00001348PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001349PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyObject *pname;
1352 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 pname = PyUnicode_FromString(name);
1355 if (pname == NULL)
1356 return NULL;
1357 result = PyImport_Import(pname);
1358 Py_DECREF(pname);
1359 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001360}
1361
Christian Heimes072c0f12008-01-03 23:01:04 +00001362/* Import a module without blocking
1363 *
1364 * At first it tries to fetch the module from sys.modules. If the module was
1365 * never loaded before it loads it with PyImport_ImportModule() unless another
1366 * thread holds the import lock. In the latter case the function raises an
1367 * ImportError instead of blocking.
1368 *
1369 * Returns the module object with incremented ref count.
1370 */
1371PyObject *
1372PyImport_ImportModuleNoBlock(const char *name)
1373{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001374 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001375}
1376
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001377
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001378PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001379PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1380 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001381 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001382{
Brett Cannonfd074152012-04-14 14:10:13 -04001383 _Py_IDENTIFIER(__import__);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001384 _Py_IDENTIFIER(__initializing__);
Brett Cannonfd074152012-04-14 14:10:13 -04001385 _Py_IDENTIFIER(__package__);
1386 _Py_IDENTIFIER(__path__);
1387 _Py_IDENTIFIER(__name__);
1388 _Py_IDENTIFIER(_find_and_load);
1389 _Py_IDENTIFIER(_handle_fromlist);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001390 _Py_IDENTIFIER(_lock_unlock_module);
Brett Cannonfd074152012-04-14 14:10:13 -04001391 _Py_static_string(single_dot, ".");
1392 PyObject *abs_name = NULL;
1393 PyObject *builtins_import = NULL;
1394 PyObject *final_mod = NULL;
1395 PyObject *mod = NULL;
1396 PyObject *package = NULL;
1397 PyObject *globals = NULL;
1398 PyObject *fromlist = NULL;
1399 PyInterpreterState *interp = PyThreadState_GET()->interp;
1400
1401 /* Make sure to use default values so as to not have
1402 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1403 NULL argument. */
1404 if (given_globals == NULL) {
1405 globals = PyDict_New();
1406 if (globals == NULL) {
1407 goto error;
1408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
Brett Cannonfd074152012-04-14 14:10:13 -04001410 else {
1411 /* Only have to care what given_globals is if it will be used
1412 fortsomething. */
1413 if (level > 0 && !PyDict_Check(given_globals)) {
1414 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1415 goto error;
1416 }
1417 globals = given_globals;
1418 Py_INCREF(globals);
1419 }
1420
1421 if (given_fromlist == NULL) {
1422 fromlist = PyList_New(0);
1423 if (fromlist == NULL) {
1424 goto error;
1425 }
1426 }
1427 else {
1428 fromlist = given_fromlist;
1429 Py_INCREF(fromlist);
1430 }
1431 if (name == NULL) {
1432 PyErr_SetString(PyExc_ValueError, "Empty module name");
1433 goto error;
1434 }
1435
1436 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1437 for added performance. */
1438
1439 if (!PyUnicode_Check(name)) {
1440 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1441 goto error;
1442 }
1443 else if (PyUnicode_READY(name) < 0) {
1444 goto error;
1445 }
1446 if (level < 0) {
1447 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1448 goto error;
1449 }
1450 else if (level > 0) {
1451 package = _PyDict_GetItemId(globals, &PyId___package__);
1452 if (package != NULL && package != Py_None) {
1453 Py_INCREF(package);
1454 if (!PyUnicode_Check(package)) {
1455 PyErr_SetString(PyExc_TypeError, "package must be a string");
1456 goto error;
1457 }
1458 }
1459 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001460 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001461 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001462 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001463 goto error;
1464 }
1465 else if (!PyUnicode_Check(package)) {
1466 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1467 }
1468 Py_INCREF(package);
1469
1470 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001471 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001472 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1473 if (borrowed_dot == NULL) {
1474 goto error;
1475 }
Brett Cannon740fce02012-04-14 14:23:49 -04001476 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001477 Py_DECREF(package);
1478 if (partition == NULL) {
1479 goto error;
1480 }
1481 package = PyTuple_GET_ITEM(partition, 0);
1482 Py_INCREF(package);
1483 Py_DECREF(partition);
1484 }
1485 }
1486
1487 if (PyDict_GetItem(interp->modules, package) == NULL) {
1488 PyErr_Format(PyExc_SystemError,
1489 "Parent module %R not loaded, cannot perform relative "
1490 "import", package);
1491 goto error;
1492 }
1493 }
1494 else { /* level == 0 */
1495 if (PyUnicode_GET_LENGTH(name) == 0) {
1496 PyErr_SetString(PyExc_ValueError, "Empty module name");
1497 goto error;
1498 }
1499 package = Py_None;
1500 Py_INCREF(package);
1501 }
1502
1503 if (level > 0) {
1504 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1505 PyObject *base = NULL;
1506 int level_up = 1;
1507
1508 for (level_up = 1; level_up < level; level_up += 1) {
1509 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1510 if (last_dot == -2) {
1511 goto error;
1512 }
1513 else if (last_dot == -1) {
1514 PyErr_SetString(PyExc_ValueError,
1515 "attempted relative import beyond top-level "
1516 "package");
1517 goto error;
1518 }
1519 }
1520 base = PyUnicode_Substring(package, 0, last_dot);
1521 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001522 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001523
1524 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001525 seq = PyTuple_Pack(2, base, name);
1526 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001527 if (borrowed_dot == NULL || seq == NULL) {
1528 goto error;
1529 }
1530
1531 abs_name = PyUnicode_Join(borrowed_dot, seq);
1532 Py_DECREF(seq);
1533 if (abs_name == NULL) {
1534 goto error;
1535 }
1536 }
1537 else {
1538 abs_name = base;
1539 }
1540 }
1541 else {
1542 abs_name = name;
1543 Py_INCREF(abs_name);
1544 }
1545
Brian Curtine6b299f2012-04-14 14:19:33 -05001546#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001547 _PyImport_AcquireLock();
1548#endif
1549 /* From this point forward, goto error_with_unlock! */
1550 if (PyDict_Check(globals)) {
1551 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1552 }
1553 if (builtins_import == NULL) {
1554 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1555 if (builtins_import == NULL) {
1556 Py_FatalError("__import__ missing");
1557 }
1558 }
1559 Py_INCREF(builtins_import);
1560
1561 mod = PyDict_GetItem(interp->modules, abs_name);
1562 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001563 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1564 "None in sys.modules", abs_name);
1565 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05001566 PyErr_SetImportError(msg, abs_name, NULL);
1567 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001568 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001569 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001570 goto error_with_unlock;
1571 }
1572 else if (mod != NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001573 PyObject *value;
1574 int initializing = 0;
1575
Brett Cannonfd074152012-04-14 14:10:13 -04001576 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001577 /* Only call _bootstrap._lock_unlock_module() if __initializing__ is true. */
1578 value = _PyObject_GetAttrId(mod, &PyId___initializing__);
1579 if (value == NULL)
1580 PyErr_Clear();
1581 else {
1582 initializing = PyObject_IsTrue(value);
1583 Py_DECREF(value);
1584 if (initializing == -1)
1585 PyErr_Clear();
1586 }
1587 if (initializing > 0) {
1588 /* _bootstrap._lock_unlock_module() releases the import lock */
1589 value = _PyObject_CallMethodObjIdArgs(interp->importlib,
1590 &PyId__lock_unlock_module, abs_name,
1591 NULL);
1592 if (value == NULL)
1593 goto error;
1594 Py_DECREF(value);
1595 }
1596 else {
1597#ifdef WITH_THREAD
1598 if (_PyImport_ReleaseLock() < 0) {
1599 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1600 goto error;
1601 }
1602#endif
1603 }
Brett Cannonfd074152012-04-14 14:10:13 -04001604 }
1605 else {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001606 /* _bootstrap._find_and_load() releases the import lock */
Brett Cannonfd074152012-04-14 14:10:13 -04001607 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1608 &PyId__find_and_load, abs_name,
1609 builtins_import, NULL);
1610 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001611 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001612 }
1613 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001614 /* From now on we don't hold the import lock anymore. */
Brett Cannonfd074152012-04-14 14:10:13 -04001615
1616 if (PyObject_Not(fromlist)) {
1617 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1618 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001619 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001620 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1621
1622 if (borrowed_dot == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001623 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001624 }
1625
Brian Curtine6b299f2012-04-14 14:19:33 -05001626 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001627 if (partition == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001628 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001629 }
1630
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001631 if (PyUnicode_GET_LENGTH(PyTuple_GET_ITEM(partition, 1)) == 0) {
1632 /* No dot in module name, simple exit */
1633 Py_DECREF(partition);
1634 final_mod = mod;
1635 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001636 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001637 }
1638
Brett Cannonfd074152012-04-14 14:10:13 -04001639 front = PyTuple_GET_ITEM(partition, 0);
1640 Py_INCREF(front);
1641 Py_DECREF(partition);
1642
1643 if (level == 0) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001644 final_mod = PyObject_CallFunctionObjArgs(builtins_import, front, NULL);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001645 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001646 }
1647 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001648 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1649 PyUnicode_GET_LENGTH(front);
1650 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001651 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001652 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001653 Py_DECREF(front);
1654 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001655 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001656 }
Brett Cannonfd074152012-04-14 14:10:13 -04001657
1658 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001659 if (final_mod == NULL) {
1660 PyErr_Format(PyExc_KeyError,
1661 "%R not in sys.modules as expected",
1662 to_return);
1663 }
1664 else {
1665 Py_INCREF(final_mod);
1666 }
Antoine Pitroub78174c2012-05-06 17:15:23 +02001667 Py_DECREF(to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001668 }
1669 }
1670 else {
1671 final_mod = mod;
1672 Py_INCREF(mod);
1673 }
1674 }
1675 else {
1676 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1677 &PyId__handle_fromlist, mod,
1678 fromlist, builtins_import,
1679 NULL);
1680 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001681 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001682
Brett Cannonfd074152012-04-14 14:10:13 -04001683 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001684#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001685 if (_PyImport_ReleaseLock() < 0) {
1686 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1687 }
1688#endif
1689 error:
1690 Py_XDECREF(abs_name);
1691 Py_XDECREF(builtins_import);
1692 Py_XDECREF(mod);
1693 Py_XDECREF(package);
1694 Py_XDECREF(globals);
1695 Py_XDECREF(fromlist);
1696 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001697}
1698
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001699PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001700PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001701 PyObject *fromlist, int level)
1702{
1703 PyObject *nameobj, *mod;
1704 nameobj = PyUnicode_FromString(name);
1705 if (nameobj == NULL)
1706 return NULL;
1707 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1708 fromlist, level);
1709 Py_DECREF(nameobj);
1710 return mod;
1711}
1712
1713
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001714/* Re-import a module of any kind and return its module object, WITH
1715 INCREMENTED REFERENCE COUNT */
1716
Guido van Rossum79f25d91997-04-29 20:08:16 +00001717PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001718PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001719{
Brett Cannon62228db2012-04-29 14:38:11 -04001720 _Py_IDENTIFIER(reload);
1721 PyObject *reloaded_module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon62228db2012-04-29 14:38:11 -04001723 PyObject *imp = PyDict_GetItemString(modules, "imp");
1724 if (imp == NULL) {
1725 imp = PyImport_ImportModule("imp");
1726 if (imp == NULL) {
1727 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 }
Brett Cannon62228db2012-04-29 14:38:11 -04001730 else {
1731 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001733
Brett Cannon62228db2012-04-29 14:38:11 -04001734 reloaded_module = _PyObject_CallMethodId(imp, &PyId_reload, "O", m);
1735 Py_DECREF(imp);
1736 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001737}
1738
1739
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001740/* Higher-level import emulator which emulates the "import" statement
1741 more accurately -- it invokes the __import__() function from the
1742 builtins of the current globals. This means that the import is
1743 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001744 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001745 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001746 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001747 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001748
1749PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001750PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 static PyObject *silly_list = NULL;
1753 static PyObject *builtins_str = NULL;
1754 static PyObject *import_str = NULL;
1755 PyObject *globals = NULL;
1756 PyObject *import = NULL;
1757 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001758 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* Initialize constant string objects */
1762 if (silly_list == NULL) {
1763 import_str = PyUnicode_InternFromString("__import__");
1764 if (import_str == NULL)
1765 return NULL;
1766 builtins_str = PyUnicode_InternFromString("__builtins__");
1767 if (builtins_str == NULL)
1768 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001769 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (silly_list == NULL)
1771 return NULL;
1772 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* Get the builtins from current globals */
1775 globals = PyEval_GetGlobals();
1776 if (globals != NULL) {
1777 Py_INCREF(globals);
1778 builtins = PyObject_GetItem(globals, builtins_str);
1779 if (builtins == NULL)
1780 goto err;
1781 }
1782 else {
1783 /* No globals -- use standard builtins, and fake globals */
1784 builtins = PyImport_ImportModuleLevel("builtins",
1785 NULL, NULL, NULL, 0);
1786 if (builtins == NULL)
1787 return NULL;
1788 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1789 if (globals == NULL)
1790 goto err;
1791 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 /* Get the __import__ function from the builtins */
1794 if (PyDict_Check(builtins)) {
1795 import = PyObject_GetItem(builtins, import_str);
1796 if (import == NULL)
1797 PyErr_SetObject(PyExc_KeyError, import_str);
1798 }
1799 else
1800 import = PyObject_GetAttr(builtins, import_str);
1801 if (import == NULL)
1802 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001805 Always use absolute import here.
1806 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1808 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001809 if (r == NULL)
1810 goto err;
1811 Py_DECREF(r);
1812
1813 modules = PyImport_GetModuleDict();
1814 r = PyDict_GetItem(modules, module_name);
1815 if (r != NULL)
1816 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001817
1818 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 Py_XDECREF(globals);
1820 Py_XDECREF(builtins);
1821 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001824}
1825
1826
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001827/* Module 'imp' provides Python access to the primitives used for
1828 importing modules.
1829*/
1830
Guido van Rossum79f25d91997-04-29 20:08:16 +00001831static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001832imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 buf[0] = (char) ((magic >> 0) & 0xff);
1837 buf[1] = (char) ((magic >> 8) & 0xff);
1838 buf[2] = (char) ((magic >> 16) & 0xff);
1839 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00001842}
Barry Warsaw28a691b2010-04-17 00:19:56 +00001843
1844static PyObject *
1845imp_get_magic(PyObject *self, PyObject *noargs)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001848}
1849
1850static PyObject *
Brett Cannon2657df42012-05-04 15:20:40 -04001851imp_extension_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001854 const char *suffix;
1855 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 list = PyList_New(0);
1858 if (list == NULL)
1859 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001860#ifdef HAVE_DYNAMIC_LOADING
1861 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1862 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 if (item == NULL) {
1864 Py_DECREF(list);
1865 return NULL;
1866 }
1867 if (PyList_Append(list, item) < 0) {
1868 Py_DECREF(list);
1869 Py_DECREF(item);
1870 return NULL;
1871 }
1872 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001873 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 }
Brett Cannon2657df42012-05-04 15:20:40 -04001875#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001877}
1878
Guido van Rossum79f25d91997-04-29 20:08:16 +00001879static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001880imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001881{
Victor Stinner95872862011-03-07 18:20:56 +01001882 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 int ret;
1884 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01001885 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 return NULL;
1887 ret = init_builtin(name);
1888 if (ret < 0)
1889 return NULL;
1890 if (ret == 0) {
1891 Py_INCREF(Py_None);
1892 return Py_None;
1893 }
Victor Stinner95872862011-03-07 18:20:56 +01001894 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 Py_XINCREF(m);
1896 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001897}
1898
Guido van Rossum79f25d91997-04-29 20:08:16 +00001899static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001900imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001901{
Victor Stinner53dc7352011-03-20 01:50:21 +01001902 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 int ret;
1904 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01001905 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001907 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 if (ret < 0)
1909 return NULL;
1910 if (ret == 0) {
1911 Py_INCREF(Py_None);
1912 return Py_None;
1913 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001914 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Py_XINCREF(m);
1916 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001917}
1918
Guido van Rossum79f25d91997-04-29 20:08:16 +00001919static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001920imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001921{
Victor Stinner53dc7352011-03-20 01:50:21 +01001922 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00001923
Victor Stinner53dc7352011-03-20 01:50:21 +01001924 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 return NULL;
1926 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001927}
1928
Guido van Rossum79f25d91997-04-29 20:08:16 +00001929static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00001930imp_is_frozen_package(PyObject *self, PyObject *args)
1931{
Victor Stinner53dc7352011-03-20 01:50:21 +01001932 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00001933
Victor Stinner53dc7352011-03-20 01:50:21 +01001934 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 return NULL;
1936 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001937}
1938
1939static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001940imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001941{
Victor Stinner95872862011-03-07 18:20:56 +01001942 PyObject *name;
1943 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 return NULL;
1945 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001946}
1947
Guido van Rossum79f25d91997-04-29 20:08:16 +00001948static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001949imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950{
Victor Stinner53dc7352011-03-20 01:50:21 +01001951 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01001953 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 return NULL;
1955 p = find_frozen(name);
1956 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001957}
1958
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001959#ifdef HAVE_DYNAMIC_LOADING
1960
Guido van Rossum79f25d91997-04-29 20:08:16 +00001961static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001962imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001963{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001964 PyObject *name, *pathname, *fob = NULL, *mod;
1965 FILE *fp;
1966
1967 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
1968 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001970 if (fob != NULL) {
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02001971 fp = _Py_fopen(pathname, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001972 if (fp == NULL) {
1973 Py_DECREF(pathname);
Antoine Pitrouf3a42de2012-05-04 22:40:25 +02001974 if (!PyErr_Occurred())
1975 PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001979 else
1980 fp = NULL;
1981 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01001982 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (fp)
1984 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04001985 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001986}
1987
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001988#endif /* HAVE_DYNAMIC_LOADING */
1989
Barry Warsaw28a691b2010-04-17 00:19:56 +00001990
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001991/* Doc strings */
1992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001993PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04001994"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001996PyDoc_STRVAR(doc_get_magic,
1997"get_magic() -> string\n\
1998Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00001999
Brett Cannon2657df42012-05-04 15:20:40 -04002000PyDoc_STRVAR(doc_extension_suffixes,
2001"extension_suffixes() -> list of strings\n\
2002Returns the list of file suffixes used to identify extension modules.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002004PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002005"lock_held() -> boolean\n\
2006Return True if the import lock is currently held, else False.\n\
2007On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002008
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002009PyDoc_STRVAR(doc_acquire_lock,
2010"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002011Acquires the interpreter's import lock for the current thread.\n\
2012This lock should be used by import hooks to ensure thread-safety\n\
2013when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002014On platforms without threads, this function does nothing.");
2015
2016PyDoc_STRVAR(doc_release_lock,
2017"release_lock() -> None\n\
2018Release the interpreter's import lock.\n\
2019On platforms without threads, this function does nothing.");
2020
Guido van Rossum79f25d91997-04-29 20:08:16 +00002021static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
Brett Cannon2657df42012-05-04 15:20:40 -04002023 {"extension_suffixes", imp_extension_suffixes, METH_NOARGS,
2024 doc_extension_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2026 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2027 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2029 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
2030 {"init_builtin", imp_init_builtin, METH_VARARGS},
2031 {"init_frozen", imp_init_frozen, METH_VARARGS},
2032 {"is_builtin", imp_is_builtin, METH_VARARGS},
2033 {"is_frozen", imp_is_frozen, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002034#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002036#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07002037 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002039};
2040
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002041
Martin v. Löwis1a214512008-06-11 05:26:20 +00002042static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002044 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 doc_imp,
2046 0,
2047 imp_methods,
2048 NULL,
2049 NULL,
2050 NULL,
2051 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002052};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002053
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002054PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002055PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 m = PyModule_Create(&impmodule);
2060 if (m == NULL)
2061 goto failure;
2062 d = PyModule_GetDict(m);
2063 if (d == NULL)
2064 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002067 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 Py_XDECREF(m);
2069 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002071
2072
Guido van Rossumb18618d2000-05-03 23:44:39 +00002073/* API for embedding applications that want to add their own entries
2074 to the table of built-in modules. This should normally be called
2075 *before* Py_Initialize(). When the table resize fails, -1 is
2076 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002077
2078 After a similar function by Just van Rossum. */
2079
2080int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002081PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 static struct _inittab *our_copy = NULL;
2084 struct _inittab *p;
2085 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 /* Count the number of entries in both tables */
2088 for (n = 0; newtab[n].name != NULL; n++)
2089 ;
2090 if (n == 0)
2091 return 0; /* Nothing to do */
2092 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2093 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 /* Allocate new memory for the combined table */
2096 p = our_copy;
2097 PyMem_RESIZE(p, struct _inittab, i+n+1);
2098 if (p == NULL)
2099 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 /* Copy the tables into the new memory */
2102 if (our_copy != PyImport_Inittab)
2103 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2104 PyImport_Inittab = our_copy = p;
2105 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002108}
2109
2110/* Shorthand to add a single entry given a name and a function */
2111
2112int
Brett Cannona826f322009-04-02 03:41:46 +00002113PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 newtab[0].name = (char *)name;
2120 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002123}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002124
2125#ifdef __cplusplus
2126}
2127#endif