blob: 8cf10e658c28c87877b4e207cae086856f14c03b [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000011#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000012#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013
Guido van Rossum55a83382000-09-20 20:31:38 +000014#ifdef HAVE_FCNTL_H
15#include <fcntl.h>
16#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000018extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000020
Christian Heimesd3eb5a152008-02-24 00:38:49 +000021#ifdef MS_WINDOWS
22/* for stat.st_mode */
23typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000024/* for _mkdir */
25#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000026#endif
27
Guido van Rossum21d335e1993-10-15 13:01:11 +000028
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000029/* Magic word to reject .pyc files generated by other Python versions.
30 It should change for each incompatible change to the bytecode.
31
32 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000033 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000034 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000035
Guido van Rossum45aecf42006-03-15 04:58:47 +000036 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000037 -U interpeter flag will cause MAGIC+1 being used. They have been
38 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000040 There were a variety of old schemes for setting the magic number.
41 The current working scheme is to increment the previous value by
42 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000043
Barry Warsaw28a691b2010-04-17 00:19:56 +000044 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
45 number also includes a new "magic tag", i.e. a human readable string used
46 to represent the magic number in __pycache__ directories. When you change
47 the magic number, you must also set a new unique magic tag. Generally this
48 can be named after the Python major version of the magic number bump, but
49 it can really be anything, as long as it's different than anything else
50 that's come before. The tags are included in the following table, starting
51 with Python 3.2a0.
52
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Known values:
54 Python 1.5: 20121
55 Python 1.5.1: 20121
56 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000058 Python 2.0: 50823
59 Python 2.0.1: 50823
60 Python 2.1: 60202
61 Python 2.1.1: 60202
62 Python 2.1.2: 60202
63 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000064 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000065 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000066 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000067 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000068 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000069 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000070 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000071 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000072 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000073 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
75 Python 2.5b3: 62111 (fix wrong code: x += yield)
76 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000078 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000079 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000081 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 3010 (removed UNARY_CONVERT)
83 3020 (added BUILD_SET)
84 3030 (added keyword-only parameters)
85 3040 (added signature annotations)
86 3050 (print becomes a function)
87 3060 (PEP 3115 metaclass syntax)
88 3061 (string literals become unicode)
89 3071 (PEP 3109 raise changes)
90 3081 (PEP 3137 make __file__ and __name__ unicode)
91 3091 (kill str8 interning)
92 3101 (merge from 2.6a0, see 62151)
93 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000094 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
95 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
96 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000100 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000102 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
103 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000104 Python 3.2a2 3180 (add DELETE_DEREF)
Benjamin Petersone7c15fa2011-06-19 19:54:45 -0500105 Python 3.3a0 3190 __class__ super closure changed
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 Python 3.3a0 3200 (__qualname__ added)
Benjamin Petersonabdb5522012-03-15 15:40:37 -0500107 3210 (added size modulo 2**32 to the pyc header)
108 Python 3.3a1 3220 (changed PEP 380 implementation)
Tim Peters36515e22001-11-18 04:06:29 +0000109*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000110
Nick Coghlancd419ab2010-09-11 00:39:25 +0000111/* MAGIC must change whenever the bytecode emitted by the compiler may no
112 longer be understood by older implementations of the eval loop (usually
113 due to the addition of new opcodes)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200114 TAG must change for each major Python release. The magic number will take
115 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116*/
Benjamin Peterson48deae12011-06-03 17:50:16 -0500117#define QUOTE(arg) #arg
118#define STRIFY(name) QUOTE(name)
119#define MAJOR STRIFY(PY_MAJOR_VERSION)
120#define MINOR STRIFY(PY_MINOR_VERSION)
Benjamin Petersonf53d20f2012-03-16 09:39:12 -0500121#define MAGIC (3220 | ((long)'\r'<<16) | ((long)'\n'<<24))
Benjamin Peterson48deae12011-06-03 17:50:16 -0500122#define TAG "cpython-" MAJOR MINOR;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000123#define CACHEDIR "__pycache__"
124/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000125static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000126static const char *pyc_tag = TAG;
Benjamin Peterson48deae12011-06-03 17:50:16 -0500127#undef QUOTE
128#undef STRIFY
129#undef MAJOR
130#undef MINOR
Guido van Rossum96774c12000-05-01 20:19:08 +0000131
Victor Stinner95872862011-03-07 18:20:56 +0100132/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000134
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200135/* Function from Parser/tokenizer.c */
136extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
137
Guido van Rossum771c6c81997-10-31 18:37:24 +0000138/* This table is defined in config.c: */
139extern struct _inittab _PyImport_Inittab[];
140
141struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000142
Guido van Rossumed1170e1999-12-20 21:23:41 +0000143/* these tables define the module suffixes that Python recognizes */
144struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000145
Guido van Rossumed1170e1999-12-20 21:23:41 +0000146static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000148#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000150#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 {".pyc", "rb", PY_COMPILED},
152 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153};
154
Victor Stinnerd0296212011-03-14 14:04:10 -0400155static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000157/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158
159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 const struct filedescr *scan;
163 struct filedescr *filetab;
164 int countD = 0;
165 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000166
Victor Stinnerd0296212011-03-14 14:04:10 -0400167 initstr = PyUnicode_InternFromString("__init__");
168 if (initstr == NULL)
169 Py_FatalError("Can't initialize import variables");
170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* prepare _PyImport_Filetab: copy entries from
172 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
173 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000174#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
176 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
179 ++countS;
180 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
181 if (filetab == NULL)
182 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000183#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 memcpy(filetab, _PyImport_DynLoadFiletab,
185 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000186#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 memcpy(filetab + countD, _PyImport_StandardFiletab,
188 countS * sizeof(struct filedescr));
189 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (Py_OptimizeFlag) {
194 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
195 for (; filetab->suffix != NULL; filetab++) {
196 if (strcmp(filetab->suffix, ".pyc") == 0)
197 filetab->suffix = ".pyo";
198 }
199 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202void
Just van Rossum52e14d62002-12-30 22:08:05 +0000203_PyImportHooks_Init(void)
204{
Brett Cannonfd074152012-04-14 14:10:13 -0400205 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (PyType_Ready(&PyNullImporter_Type) < 0)
209 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000210
Brett Cannonfd074152012-04-14 14:10:13 -0400211 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 v = PyList_New(0);
213 if (v == NULL)
214 goto error;
215 err = PySys_SetObject("meta_path", v);
216 Py_DECREF(v);
217 if (err)
218 goto error;
219 v = PyDict_New();
220 if (v == NULL)
221 goto error;
222 err = PySys_SetObject("path_importer_cache", v);
223 Py_DECREF(v);
224 if (err)
225 goto error;
226 path_hooks = PyList_New(0);
227 if (path_hooks == NULL)
228 goto error;
229 err = PySys_SetObject("path_hooks", path_hooks);
230 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000231 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400232 PyErr_Print();
233 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
234 "path_importer_cache, or NullImporter failed"
235 );
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 }
Brett Cannonfd074152012-04-14 14:10:13 -0400237 Py_DECREF(path_hooks);
238}
239
240void
241_PyImportZip_Init(void)
242{
243 PyObject *path_hooks, *zimpimport;
244 int err = 0;
245
246 path_hooks = PySys_GetObject("path_hooks");
247 if (path_hooks == NULL)
248 goto error;
249
250 if (Py_VerboseFlag)
251 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 zimpimport = PyImport_ImportModule("zipimport");
254 if (zimpimport == NULL) {
255 PyErr_Clear(); /* No zip import module -- okay */
256 if (Py_VerboseFlag)
257 PySys_WriteStderr("# can't import zipimport\n");
258 }
259 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200260 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200261 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
262 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_DECREF(zimpimport);
264 if (zipimporter == NULL) {
265 PyErr_Clear(); /* No zipimporter object -- okay */
266 if (Py_VerboseFlag)
267 PySys_WriteStderr(
268 "# can't import zipimport.zipimporter\n");
269 }
270 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400271 /* sys.path_hooks.insert(0, zipimporter) */
272 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400274 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (Py_VerboseFlag)
278 PySys_WriteStderr(
279 "# installed zipimport hook\n");
280 }
281 }
Brett Cannonfd074152012-04-14 14:10:13 -0400282
283 return;
284
285 error:
286 PyErr_Print();
287 Py_FatalError("initializing zipimport or NullImporter failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000288}
289
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290/* Locking primitives to prevent parallel imports of the same module
291 in different threads to return with a partially loaded module.
292 These calls are serialized by the global interpreter lock. */
293
294#ifdef WITH_THREAD
295
Guido van Rossum49b56061998-10-01 20:42:43 +0000296#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297
Guido van Rossum65d5b571998-12-21 19:32:43 +0000298static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000299static long import_lock_thread = -1;
300static int import_lock_level = 0;
301
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000302void
303_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 long me = PyThread_get_thread_ident();
306 if (me == -1)
307 return; /* Too bad */
308 if (import_lock == NULL) {
309 import_lock = PyThread_allocate_lock();
310 if (import_lock == NULL)
311 return; /* Nothing much we can do. */
312 }
313 if (import_lock_thread == me) {
314 import_lock_level++;
315 return;
316 }
317 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
318 {
319 PyThreadState *tstate = PyEval_SaveThread();
320 PyThread_acquire_lock(import_lock, 1);
321 PyEval_RestoreThread(tstate);
322 }
323 import_lock_thread = me;
324 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000325}
326
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000327int
328_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 long me = PyThread_get_thread_ident();
331 if (me == -1 || import_lock == NULL)
332 return 0; /* Too bad */
333 if (import_lock_thread != me)
334 return -1;
335 import_lock_level--;
336 if (import_lock_level == 0) {
337 import_lock_thread = -1;
338 PyThread_release_lock(import_lock);
339 }
340 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000341}
342
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000343/* This function is called from PyOS_AfterFork to ensure that newly
344 created child processes do not share locks with the parent.
345 We now acquire the import lock around fork() calls but on some platforms
346 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000347
348void
349_PyImport_ReInitLock(void)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (import_lock != NULL)
352 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000353 if (import_lock_level > 1) {
354 /* Forked as a side effect of import */
355 long me = PyThread_get_thread_ident();
356 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100357 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000358 import_lock_thread = me;
359 import_lock_level--;
360 } else {
361 import_lock_thread = -1;
362 import_lock_level = 0;
363 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000364}
365
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000366#endif
367
Tim Peters69232342001-08-30 05:16:13 +0000368static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000369imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000370{
Tim Peters69232342001-08-30 05:16:13 +0000371#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000373#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000375#endif
376}
377
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000378static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000379imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000380{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000381#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000383#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_INCREF(Py_None);
385 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000386}
387
388static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000389imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000390{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000391#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (_PyImport_ReleaseLock() < 0) {
393 PyErr_SetString(PyExc_RuntimeError,
394 "not holding the import lock");
395 return NULL;
396 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 Py_INCREF(Py_None);
399 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000400}
401
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100402void
403_PyImport_Fini(void)
404{
405 Py_XDECREF(extensions);
406 extensions = NULL;
407 PyMem_DEL(_PyImport_Filetab);
408 _PyImport_Filetab = NULL;
409#ifdef WITH_THREAD
410 if (import_lock != NULL) {
411 PyThread_free_lock(import_lock);
412 import_lock = NULL;
413 }
414#endif
415}
416
Guido van Rossumd8faa362007-04-27 19:54:29 +0000417static void
418imp_modules_reloading_clear(void)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyInterpreterState *interp = PyThreadState_Get()->interp;
421 if (interp->modules_reloading != NULL)
422 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423}
424
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425/* Helper for sys */
426
427PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000428PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyInterpreterState *interp = PyThreadState_GET()->interp;
431 if (interp->modules == NULL)
432 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
433 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000434}
435
Guido van Rossum3f5da241990-12-20 15:06:42 +0000436
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437/* List of names to clear in sys */
438static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 "path", "argv", "ps1", "ps2",
440 "last_type", "last_value", "last_traceback",
441 "path_hooks", "path_importer_cache", "meta_path",
442 /* misc stuff */
443 "flags", "float_info",
444 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000445};
446
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000447static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 "stdin", "__stdin__",
449 "stdout", "__stdout__",
450 "stderr", "__stderr__",
451 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000452};
453
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000454
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000455/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000456
Guido van Rossum3f5da241990-12-20 15:06:42 +0000457void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000458PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyObject *key, *value, *dict;
462 PyInterpreterState *interp = PyThreadState_GET()->interp;
463 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (modules == NULL)
466 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* Delete some special variables first. These are common
469 places where user values hide and people complain when their
470 destructors fail. Since the modules containing them are
471 deleted *last* of all, they would come too late in the normal
472 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 value = PyDict_GetItemString(modules, "builtins");
475 if (value != NULL && PyModule_Check(value)) {
476 dict = PyModule_GetDict(value);
477 if (Py_VerboseFlag)
478 PySys_WriteStderr("# clear builtins._\n");
479 PyDict_SetItemString(dict, "_", Py_None);
480 }
481 value = PyDict_GetItemString(modules, "sys");
482 if (value != NULL && PyModule_Check(value)) {
483 char **p;
484 PyObject *v;
485 dict = PyModule_GetDict(value);
486 for (p = sys_deletes; *p != NULL; p++) {
487 if (Py_VerboseFlag)
488 PySys_WriteStderr("# clear sys.%s\n", *p);
489 PyDict_SetItemString(dict, *p, Py_None);
490 }
491 for (p = sys_files; *p != NULL; p+=2) {
492 if (Py_VerboseFlag)
493 PySys_WriteStderr("# restore sys.%s\n", *p);
494 v = PyDict_GetItemString(dict, *(p+1));
495 if (v == NULL)
496 v = Py_None;
497 PyDict_SetItemString(dict, *p, v);
498 }
499 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* First, delete __main__ */
502 value = PyDict_GetItemString(modules, "__main__");
503 if (value != NULL && PyModule_Check(value)) {
504 if (Py_VerboseFlag)
505 PySys_WriteStderr("# cleanup __main__\n");
506 _PyModule_Clear(value);
507 PyDict_SetItemString(modules, "__main__", Py_None);
508 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* The special treatment of "builtins" here is because even
511 when it's not referenced as a module, its dictionary is
512 referenced by almost every module's __builtins__. Since
513 deleting a module clears its dictionary (even if there are
514 references left to it), we need to delete the "builtins"
515 module last. Likewise, we don't delete sys until the very
516 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Also note that we 'delete' modules by replacing their entry
519 in the modules dict with None, rather than really deleting
520 them; this avoids a rehash of the modules dictionary and
521 also marks them as "non existent" so they won't be
522 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Next, repeatedly delete modules with a reference count of
525 one (skipping builtins and sys) and delete them */
526 do {
527 ndone = 0;
528 pos = 0;
529 while (PyDict_Next(modules, &pos, &key, &value)) {
530 if (value->ob_refcnt != 1)
531 continue;
532 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100533 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100535 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 continue;
537 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100538 PySys_FormatStderr(
539 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 _PyModule_Clear(value);
541 PyDict_SetItem(modules, key, Py_None);
542 ndone++;
543 }
544 }
545 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* Next, delete all modules (still skipping builtins and sys) */
548 pos = 0;
549 while (PyDict_Next(modules, &pos, &key, &value)) {
550 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100551 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100553 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 continue;
555 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100556 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 _PyModule_Clear(value);
558 PyDict_SetItem(modules, key, Py_None);
559 }
560 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* Next, delete sys and builtins (in that order) */
563 value = PyDict_GetItemString(modules, "sys");
564 if (value != NULL && PyModule_Check(value)) {
565 if (Py_VerboseFlag)
566 PySys_WriteStderr("# cleanup sys\n");
567 _PyModule_Clear(value);
568 PyDict_SetItemString(modules, "sys", Py_None);
569 }
570 value = PyDict_GetItemString(modules, "builtins");
571 if (value != NULL && PyModule_Check(value)) {
572 if (Py_VerboseFlag)
573 PySys_WriteStderr("# cleanup builtins\n");
574 _PyModule_Clear(value);
575 PyDict_SetItemString(modules, "builtins", Py_None);
576 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Finally, clear and delete the modules directory */
579 PyDict_Clear(modules);
580 interp->modules = NULL;
581 Py_DECREF(modules);
582 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000583}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000584
585
Barry Warsaw28a691b2010-04-17 00:19:56 +0000586/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
588long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000589PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000592}
593
594
Barry Warsaw28a691b2010-04-17 00:19:56 +0000595const char *
596PyImport_GetMagicTag(void)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000599}
600
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601/* Magic for extension modules (built-in as well as dynamically
602 loaded). To prevent initializing an extension module more than
603 once, we keep a static dictionary 'extensions' keyed by module name
604 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000605 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100606 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607 immediately after the module initialization function succeeds. A
608 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100609 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000611 Modules which do support multiple initialization set their m_size
612 field to a non-negative number (indicating the size of the
613 module-specific state). They are still recorded in the extensions
614 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000615*/
616
617int
Victor Stinner95872862011-03-07 18:20:56 +0100618_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
619 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *modules, *dict;
622 struct PyModuleDef *def;
623 if (extensions == NULL) {
624 extensions = PyDict_New();
625 if (extensions == NULL)
626 return -1;
627 }
628 if (mod == NULL || !PyModule_Check(mod)) {
629 PyErr_BadInternalCall();
630 return -1;
631 }
632 def = PyModule_GetDef(mod);
633 if (!def) {
634 PyErr_BadInternalCall();
635 return -1;
636 }
637 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100638 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return -1;
640 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100641 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return -1;
643 }
644 if (def->m_size == -1) {
645 if (def->m_base.m_copy) {
646 /* Somebody already imported the module,
647 likely under a different name.
648 XXX this should really not happen. */
649 Py_DECREF(def->m_base.m_copy);
650 def->m_base.m_copy = NULL;
651 }
652 dict = PyModule_GetDict(mod);
653 if (dict == NULL)
654 return -1;
655 def->m_base.m_copy = PyDict_Copy(dict);
656 if (def->m_base.m_copy == NULL)
657 return -1;
658 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000659 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661}
662
Victor Stinner49d3f252010-10-17 01:24:53 +0000663int
664_PyImport_FixupBuiltin(PyObject *mod, char *name)
665{
666 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100667 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100668 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100669 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000670 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100671 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
672 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000673 return res;
674}
675
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100677_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *mod, *mdict;
680 PyModuleDef* def;
681 if (extensions == NULL)
682 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000683 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (def == NULL)
685 return NULL;
686 if (def->m_size == -1) {
687 /* Module does not support repeated initialization */
688 if (def->m_base.m_copy == NULL)
689 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100690 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (mod == NULL)
692 return NULL;
693 mdict = PyModule_GetDict(mod);
694 if (mdict == NULL)
695 return NULL;
696 if (PyDict_Update(mdict, def->m_base.m_copy))
697 return NULL;
698 }
699 else {
700 if (def->m_base.m_init == NULL)
701 return NULL;
702 mod = def->m_base.m_init();
703 if (mod == NULL)
704 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100705 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_DECREF(mod);
707 }
708 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100709 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(mod);
711 return NULL;
712 }
713 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100714 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 name, filename);
716 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000717
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718}
719
Victor Stinner49d3f252010-10-17 01:24:53 +0000720PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000721_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000722{
Victor Stinner95872862011-03-07 18:20:56 +0100723 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100724 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100725 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000726 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100727 res = _PyImport_FindExtensionObject(nameobj, nameobj);
728 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000729 return res;
730}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
732/* Get the module object corresponding to a module name.
733 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000734 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000735 Because the former action is most common, THIS DOES NOT RETURN A
736 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000739PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject *modules = PyImport_GetModuleDict();
742 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743
Victor Stinner27ee0892011-03-04 12:57:09 +0000744 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyModule_Check(m))
746 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000747 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (m == NULL)
749 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000750 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 Py_DECREF(m);
752 return NULL;
753 }
754 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757}
758
Victor Stinner27ee0892011-03-04 12:57:09 +0000759PyObject *
760PyImport_AddModule(const char *name)
761{
762 PyObject *nameobj, *module;
763 nameobj = PyUnicode_FromString(name);
764 if (nameobj == NULL)
765 return NULL;
766 module = PyImport_AddModuleObject(nameobj);
767 Py_DECREF(nameobj);
768 return module;
769}
770
771
Tim Peters1cd70172004-08-02 03:52:12 +0000772/* Remove name from sys.modules, if it's there. */
773static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000774remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000777 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000779 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 Py_FatalError("import: deleting existing key in"
781 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000782}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783
Victor Stinnerc9abda02011-03-14 13:33:46 -0400784static PyObject * get_sourcefile(PyObject *filename);
785static PyObject *make_source_pathname(PyObject *pathname);
Christian Heimes3b06e532008-01-07 20:12:44 +0000786
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000787/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000788 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
789 * removed from sys.modules, to avoid leaving damaged module objects
790 * in sys.modules. The caller may wish to restore the original
791 * module object (if any) in this case; PyImport_ReloadModule is an
792 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000793 *
794 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
795 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000796 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000797PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000798PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 return PyImport_ExecCodeModuleWithPathnames(
801 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000802}
803
804PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000805PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return PyImport_ExecCodeModuleWithPathnames(
808 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000809}
810
811PyObject *
812PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000814{
Victor Stinner27ee0892011-03-04 12:57:09 +0000815 PyObject *m = NULL;
816 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
817
818 nameobj = PyUnicode_FromString(name);
819 if (nameobj == NULL)
820 return NULL;
821
822 if (pathname != NULL) {
823 pathobj = PyUnicode_DecodeFSDefault(pathname);
824 if (pathobj == NULL)
825 goto error;
826 } else
827 pathobj = NULL;
828 if (cpathname != NULL) {
829 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
830 if (cpathobj == NULL)
831 goto error;
832 } else
833 cpathobj = NULL;
834 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
835error:
836 Py_DECREF(nameobj);
837 Py_XDECREF(pathobj);
838 Py_XDECREF(cpathobj);
839 return m;
840}
841
842PyObject*
843PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
844 PyObject *cpathname)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyObject *modules = PyImport_GetModuleDict();
847 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000848
Victor Stinner27ee0892011-03-04 12:57:09 +0000849 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (m == NULL)
851 return NULL;
852 /* If the module is being reloaded, we get the old module back
853 and re-use its dict to exec the new code. */
854 d = PyModule_GetDict(m);
855 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
856 if (PyDict_SetItemString(d, "__builtins__",
857 PyEval_GetBuiltins()) != 0)
858 goto error;
859 }
860 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400862 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (v == NULL)
864 PyErr_Clear();
865 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000866 else
867 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (v == NULL) {
869 v = ((PyCodeObject *)co)->co_filename;
870 Py_INCREF(v);
871 }
872 if (PyDict_SetItemString(d, "__file__", v) != 0)
873 PyErr_Clear(); /* Not important enough to report */
874 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000877 if (cpathname != NULL)
878 v = cpathname;
879 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (PyDict_SetItemString(d, "__cached__", v) != 0)
882 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000883
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000884 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (v == NULL)
886 goto error;
887 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000888
Victor Stinner27ee0892011-03-04 12:57:09 +0000889 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000891 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 name);
893 return NULL;
894 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000899
900 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 remove_module(name);
902 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000903}
904
905
Martin v. Löwis2db72862011-10-23 17:29:08 +0200906/* Like rightmost_sep, but operate on unicode objects. */
907static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200908rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200909{
910 Py_ssize_t found, i;
911 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200912 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200913 c = PyUnicode_READ_CHAR(o, i);
914 if (c == SEP
915#ifdef ALTSEP
916 || c == ALTSEP
917#endif
918 )
919 {
920 found = i;
921 }
922 }
923 return found;
924}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400925
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000926
Barry Warsaw28a691b2010-04-17 00:19:56 +0000927/* Given a pathname to a Python byte compiled file, return the path to the
928 source file, if the path matches the PEP 3147 format. This does not check
929 for any file existence, however, if the pyc file name does not match PEP
930 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400931 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932
Victor Stinnerc9abda02011-03-14 13:33:46 -0400933 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
934
935static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200936make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000937{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200938 Py_ssize_t left, right, dot0, dot1, len;
939 Py_ssize_t i, j;
940 PyObject *result;
941 int kind;
942 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400943
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200944 len = PyUnicode_GET_LENGTH(path);
945 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200946 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Look back two slashes from the end. In between these two slashes
949 must be the string __pycache__ or this is not a PEP 3147 style
950 path. It's possible for there to be only one slash.
951 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200952 right = rightmost_sep_obj(path, 0, len);
953 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200955 left = rightmost_sep_obj(path, 0, right);
956 if (left == -1)
957 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 else
959 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200960 if (right-left != sizeof(CACHEDIR)-1)
961 return NULL;
962 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
963 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
964 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* Now verify that the path component to the right of the last slash
967 has two dots in it.
968 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200969 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
970 if (dot0 < 0)
971 return NULL;
972 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
973 if (dot1 < 0)
974 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200976 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
977 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* This is a PEP 3147 path. Start by copying everything from the
980 start of pathname up to and including the leftmost slash. Then
981 copy the file's basename, removing the magic tag and adding a .py
982 suffix.
983 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200984 result = PyUnicode_New(left + (dot0-right) + 2,
985 PyUnicode_MAX_CHAR_VALUE(path));
986 if (!result)
987 return NULL;
988 kind = PyUnicode_KIND(result);
989 data = PyUnicode_DATA(result);
990 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
991 PyUnicode_CopyCharacters(result, left, path, right+1,
992 (j = dot0-right));
993 PyUnicode_WRITE(kind, data, i+j, 'p');
994 PyUnicode_WRITE(kind, data, i+j+1, 'y');
995 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000996}
997
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000998
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000999static void
1000update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject *constants, *tmp;
1003 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (PyUnicode_Compare(co->co_filename, oldname))
1006 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 tmp = co->co_filename;
1009 co->co_filename = newname;
1010 Py_INCREF(co->co_filename);
1011 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 constants = co->co_consts;
1014 n = PyTuple_GET_SIZE(constants);
1015 for (i = 0; i < n; i++) {
1016 tmp = PyTuple_GET_ITEM(constants, i);
1017 if (PyCode_Check(tmp))
1018 update_code_filenames((PyCodeObject *)tmp,
1019 oldname, newname);
1020 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001021}
1022
Victor Stinner2f42ae52011-03-20 00:41:24 +01001023static void
1024update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001025{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001026 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001027
Victor Stinner2f42ae52011-03-20 00:41:24 +01001028 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1029 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 oldname = co->co_filename;
1032 Py_INCREF(oldname);
1033 update_code_filenames(co, oldname, newname);
1034 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001035}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001036
Brett Cannon442c9b92011-03-23 16:14:42 -07001037static PyObject *
1038imp_fix_co_filename(PyObject *self, PyObject *args)
1039{
1040 PyObject *co;
1041 PyObject *file_path;
1042
1043 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1044 return NULL;
1045
1046 if (!PyCode_Check(co)) {
1047 PyErr_SetString(PyExc_TypeError,
1048 "first argument must be a code object");
1049 return NULL;
1050 }
1051
1052 if (!PyUnicode_Check(file_path)) {
1053 PyErr_SetString(PyExc_TypeError,
1054 "second argument must be a string");
1055 return NULL;
1056 }
1057
1058 update_compiled_module((PyCodeObject*)co, file_path);
1059
1060 Py_RETURN_NONE;
1061}
1062
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001063
Christian Heimes3b06e532008-01-07 20:12:44 +00001064/* Get source file -> unicode or None
1065 * Returns the path to the py file if available, else the given path
1066 */
1067static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001068get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001072 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001074 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001076 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001077 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001079
Victor Stinnerc9abda02011-03-14 13:33:46 -04001080 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 fileuni = PyUnicode_AsUCS4Copy(filename);
1082 if (!fileuni)
1083 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001084 if (len < 5
1085 || fileuni[len-4] != '.'
1086 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1087 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1088 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 /* Start by trying to turn PEP 3147 path into source path. If that
1091 * fails, just chop off the trailing character, i.e. legacy pyc path
1092 * to py.
1093 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001094 py = make_source_pathname(filename);
1095 if (py == NULL) {
1096 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001097 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001099 if (py == NULL)
1100 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001101
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001102 err = _Py_stat(py, &statbuf);
1103 if (err == -2)
1104 goto error;
1105 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001106 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001107 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001108 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001109 Py_DECREF(py);
1110 goto unchanged;
1111
1112error:
1113 PyErr_Clear();
1114unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001115 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001116 Py_INCREF(filename);
1117 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001118}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001119
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001120/* Forward */
Victor Stinner53dc7352011-03-20 01:50:21 +01001121static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001122
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001123
1124/* Helper to test for built-in module */
1125
1126static int
Victor Stinner95872862011-03-07 18:20:56 +01001127is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001128{
Victor Stinner95872862011-03-07 18:20:56 +01001129 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001131 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1132 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (PyImport_Inittab[i].initfunc == NULL)
1134 return -1;
1135 else
1136 return 1;
1137 }
1138 }
1139 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001140}
1141
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001142
Just van Rossum52e14d62002-12-30 22:08:05 +00001143/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1144 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001145 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001146 that can handle the path item. Return None if no hook could;
1147 this tells our caller it should fall back to the builtin
1148 import mechanism. Cache the result in path_importer_cache.
1149 Returns a borrowed reference. */
1150
1151static PyObject *
1152get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyObject *importer;
1156 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 /* These conditions are the caller's responsibility: */
1159 assert(PyList_Check(path_hooks));
1160 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 nhooks = PyList_Size(path_hooks);
1163 if (nhooks < 0)
1164 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 importer = PyDict_GetItem(path_importer_cache, p);
1167 if (importer != NULL)
1168 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 /* set path_importer_cache[p] to None to avoid recursion */
1171 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1172 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 for (j = 0; j < nhooks; j++) {
1175 PyObject *hook = PyList_GetItem(path_hooks, j);
1176 if (hook == NULL)
1177 return NULL;
1178 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1179 if (importer != NULL)
1180 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1183 return NULL;
1184 }
1185 PyErr_Clear();
1186 }
1187 if (importer == NULL) {
1188 importer = PyObject_CallFunctionObjArgs(
1189 (PyObject *)&PyNullImporter_Type, p, NULL
1190 );
1191 if (importer == NULL) {
1192 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1193 PyErr_Clear();
1194 return Py_None;
1195 }
1196 }
1197 }
1198 if (importer != NULL) {
1199 int err = PyDict_SetItem(path_importer_cache, p, importer);
1200 Py_DECREF(importer);
1201 if (err != 0)
1202 return NULL;
1203 }
1204 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001205}
1206
Christian Heimes9cd17752007-11-18 19:35:23 +00001207PyAPI_FUNC(PyObject *)
1208PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1212 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1213 importer = get_path_importer(path_importer_cache,
1214 path_hooks, path);
1215 }
1216 }
1217 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1218 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001219}
1220
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001221
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001222#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001223extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1224 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001225#endif
1226
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001227
Victor Stinner95872862011-03-07 18:20:56 +01001228static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001229
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001230/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001231 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001232 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001233
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001234static int
Victor Stinner95872862011-03-07 18:20:56 +01001235init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001238
Victor Stinner95872862011-03-07 18:20:56 +01001239 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 for (p = PyImport_Inittab; p->name != NULL; p++) {
1243 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001244 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01001245 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (p->initfunc == NULL) {
1247 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01001248 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 name);
1250 return -1;
1251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 mod = (*p->initfunc)();
1253 if (mod == 0)
1254 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001255 /* Remember pointer to module init function. */
1256 def = PyModule_GetDef(mod);
1257 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01001258 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 return -1;
1260 /* FixupExtension has put the module into sys.modules,
1261 so we can release our own reference. */
1262 Py_DECREF(mod);
1263 return 1;
1264 }
1265 }
1266 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001267}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001268
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001269
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001270/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001271
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001272static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001273find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001276
Victor Stinner53dc7352011-03-20 01:50:21 +01001277 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 for (p = PyImport_FrozenModules; ; p++) {
1281 if (p->name == NULL)
1282 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01001283 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 break;
1285 }
1286 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001287}
1288
Guido van Rossum79f25d91997-04-29 20:08:16 +00001289static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001290get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 struct _frozen *p = find_frozen(name);
1293 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (p == NULL) {
1296 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001297 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 name);
1299 return NULL;
1300 }
1301 if (p->code == NULL) {
1302 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001303 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 name);
1305 return NULL;
1306 }
1307 size = p->size;
1308 if (size < 0)
1309 size = -size;
1310 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001311}
1312
Brett Cannon8d110132009-03-15 02:20:16 +00001313static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001314is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 struct _frozen *p = find_frozen(name);
1317 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (p == NULL) {
1320 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001321 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 name);
1323 return NULL;
1324 }
Brett Cannon8d110132009-03-15 02:20:16 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (size < 0)
1329 Py_RETURN_TRUE;
1330 else
1331 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001332}
1333
1334
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001335/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001336 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001337 an exception set if the initialization failed.
1338 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001339
1340int
Victor Stinner53dc7352011-03-20 01:50:21 +01001341PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001342{
Victor Stinner53dc7352011-03-20 01:50:21 +01001343 struct _frozen *p;
1344 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 int ispackage;
1346 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001347
Victor Stinner53dc7352011-03-20 01:50:21 +01001348 p = find_frozen(name);
1349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 if (p == NULL)
1351 return 0;
1352 if (p->code == NULL) {
1353 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001354 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 name);
1356 return -1;
1357 }
1358 size = p->size;
1359 ispackage = (size < 0);
1360 if (ispackage)
1361 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1363 if (co == NULL)
1364 return -1;
1365 if (!PyCode_Check(co)) {
1366 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001367 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 name);
1369 goto err_return;
1370 }
1371 if (ispackage) {
1372 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01001373 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001375 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (m == NULL)
1377 goto err_return;
1378 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 l = PyList_New(1);
1380 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 goto err_return;
1382 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001383 Py_INCREF(name);
1384 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 err = PyDict_SetItemString(d, "__path__", l);
1386 Py_DECREF(l);
1387 if (err != 0)
1388 goto err_return;
1389 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001390 path = PyUnicode_FromString("<frozen>");
1391 if (path == NULL)
1392 goto err_return;
1393 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
1394 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (m == NULL)
1396 goto err_return;
1397 Py_DECREF(co);
1398 Py_DECREF(m);
1399 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001400err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 Py_DECREF(co);
1402 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001403}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001404
Victor Stinner53dc7352011-03-20 01:50:21 +01001405int
1406PyImport_ImportFrozenModule(char *name)
1407{
1408 PyObject *nameobj;
1409 int ret;
1410 nameobj = PyUnicode_InternFromString(name);
1411 if (nameobj == NULL)
1412 return -1;
1413 ret = PyImport_ImportFrozenModuleObject(nameobj);
1414 Py_DECREF(nameobj);
1415 return ret;
1416}
1417
Guido van Rossum74e6a111994-08-29 12:54:38 +00001418
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001419/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001420 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001421
Guido van Rossum79f25d91997-04-29 20:08:16 +00001422PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001423PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyObject *pname;
1426 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 pname = PyUnicode_FromString(name);
1429 if (pname == NULL)
1430 return NULL;
1431 result = PyImport_Import(pname);
1432 Py_DECREF(pname);
1433 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001434}
1435
Christian Heimes072c0f12008-01-03 23:01:04 +00001436/* Import a module without blocking
1437 *
1438 * At first it tries to fetch the module from sys.modules. If the module was
1439 * never loaded before it loads it with PyImport_ImportModule() unless another
1440 * thread holds the import lock. In the latter case the function raises an
1441 * ImportError instead of blocking.
1442 *
1443 * Returns the module object with incremented ref count.
1444 */
1445PyObject *
1446PyImport_ImportModuleNoBlock(const char *name)
1447{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001448 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02001449#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02001451#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* Try to get the module from sys.modules[name] */
1454 modules = PyImport_GetModuleDict();
1455 if (modules == NULL)
1456 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001457
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001458 nameobj = PyUnicode_FromString(name);
1459 if (nameobj == NULL)
1460 return NULL;
1461 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001463 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 Py_INCREF(result);
1465 return result;
1466 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001467 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001468#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 /* check the import lock
1470 * me might be -1 but I ignore the error here, the lock function
1471 * takes care of the problem */
1472 me = PyThread_get_thread_ident();
1473 if (import_lock_thread == -1 || import_lock_thread == me) {
1474 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001475 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 }
1477 else {
1478 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04001479 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001481 nameobj);
1482 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001484#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001485 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00001486#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04001487 Py_DECREF(nameobj);
1488 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00001489}
1490
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001491
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001492PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04001493PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
1494 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001495 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001496{
Brett Cannonfd074152012-04-14 14:10:13 -04001497 _Py_IDENTIFIER(__import__);
1498 _Py_IDENTIFIER(__package__);
1499 _Py_IDENTIFIER(__path__);
1500 _Py_IDENTIFIER(__name__);
1501 _Py_IDENTIFIER(_find_and_load);
1502 _Py_IDENTIFIER(_handle_fromlist);
1503 _Py_static_string(single_dot, ".");
1504 PyObject *abs_name = NULL;
1505 PyObject *builtins_import = NULL;
1506 PyObject *final_mod = NULL;
1507 PyObject *mod = NULL;
1508 PyObject *package = NULL;
1509 PyObject *globals = NULL;
1510 PyObject *fromlist = NULL;
1511 PyInterpreterState *interp = PyThreadState_GET()->interp;
1512
1513 /* Make sure to use default values so as to not have
1514 PyObject_CallMethodObjArgs() truncate the parameter list because of a
1515 NULL argument. */
1516 if (given_globals == NULL) {
1517 globals = PyDict_New();
1518 if (globals == NULL) {
1519 goto error;
1520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 }
Brett Cannonfd074152012-04-14 14:10:13 -04001522 else {
1523 /* Only have to care what given_globals is if it will be used
1524 fortsomething. */
1525 if (level > 0 && !PyDict_Check(given_globals)) {
1526 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1527 goto error;
1528 }
1529 globals = given_globals;
1530 Py_INCREF(globals);
1531 }
1532
1533 if (given_fromlist == NULL) {
1534 fromlist = PyList_New(0);
1535 if (fromlist == NULL) {
1536 goto error;
1537 }
1538 }
1539 else {
1540 fromlist = given_fromlist;
1541 Py_INCREF(fromlist);
1542 }
1543 if (name == NULL) {
1544 PyErr_SetString(PyExc_ValueError, "Empty module name");
1545 goto error;
1546 }
1547
1548 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1549 for added performance. */
1550
1551 if (!PyUnicode_Check(name)) {
1552 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1553 goto error;
1554 }
1555 else if (PyUnicode_READY(name) < 0) {
1556 goto error;
1557 }
1558 if (level < 0) {
1559 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1560 goto error;
1561 }
1562 else if (level > 0) {
1563 package = _PyDict_GetItemId(globals, &PyId___package__);
1564 if (package != NULL && package != Py_None) {
1565 Py_INCREF(package);
1566 if (!PyUnicode_Check(package)) {
1567 PyErr_SetString(PyExc_TypeError, "package must be a string");
1568 goto error;
1569 }
1570 }
1571 else {
Brett Cannon273323c2012-04-17 19:05:11 -04001572 package = _PyDict_GetItemId(globals, &PyId___name__);
Brett Cannonfd074152012-04-14 14:10:13 -04001573 if (package == NULL) {
Brett Cannon273323c2012-04-17 19:05:11 -04001574 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
Brett Cannonfd074152012-04-14 14:10:13 -04001575 goto error;
1576 }
1577 else if (!PyUnicode_Check(package)) {
1578 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1579 }
1580 Py_INCREF(package);
1581
1582 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04001583 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001584 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1585 if (borrowed_dot == NULL) {
1586 goto error;
1587 }
Brett Cannon740fce02012-04-14 14:23:49 -04001588 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001589 Py_DECREF(package);
1590 if (partition == NULL) {
1591 goto error;
1592 }
1593 package = PyTuple_GET_ITEM(partition, 0);
1594 Py_INCREF(package);
1595 Py_DECREF(partition);
1596 }
1597 }
1598
1599 if (PyDict_GetItem(interp->modules, package) == NULL) {
1600 PyErr_Format(PyExc_SystemError,
1601 "Parent module %R not loaded, cannot perform relative "
1602 "import", package);
1603 goto error;
1604 }
1605 }
1606 else { /* level == 0 */
1607 if (PyUnicode_GET_LENGTH(name) == 0) {
1608 PyErr_SetString(PyExc_ValueError, "Empty module name");
1609 goto error;
1610 }
1611 package = Py_None;
1612 Py_INCREF(package);
1613 }
1614
1615 if (level > 0) {
1616 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
1617 PyObject *base = NULL;
1618 int level_up = 1;
1619
1620 for (level_up = 1; level_up < level; level_up += 1) {
1621 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1622 if (last_dot == -2) {
1623 goto error;
1624 }
1625 else if (last_dot == -1) {
1626 PyErr_SetString(PyExc_ValueError,
1627 "attempted relative import beyond top-level "
1628 "package");
1629 goto error;
1630 }
1631 }
1632 base = PyUnicode_Substring(package, 0, last_dot);
1633 if (PyUnicode_GET_LENGTH(name) > 0) {
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001634 PyObject *borrowed_dot, *seq = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001635
1636 borrowed_dot = _PyUnicode_FromId(&single_dot);
Antoine Pitrou538ba2a2012-04-16 21:52:45 +02001637 seq = PyTuple_Pack(2, base, name);
1638 Py_DECREF(base);
Brett Cannonfd074152012-04-14 14:10:13 -04001639 if (borrowed_dot == NULL || seq == NULL) {
1640 goto error;
1641 }
1642
1643 abs_name = PyUnicode_Join(borrowed_dot, seq);
1644 Py_DECREF(seq);
1645 if (abs_name == NULL) {
1646 goto error;
1647 }
1648 }
1649 else {
1650 abs_name = base;
1651 }
1652 }
1653 else {
1654 abs_name = name;
1655 Py_INCREF(abs_name);
1656 }
1657
Brian Curtine6b299f2012-04-14 14:19:33 -05001658#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001659 _PyImport_AcquireLock();
1660#endif
1661 /* From this point forward, goto error_with_unlock! */
1662 if (PyDict_Check(globals)) {
1663 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
1664 }
1665 if (builtins_import == NULL) {
1666 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
1667 if (builtins_import == NULL) {
1668 Py_FatalError("__import__ missing");
1669 }
1670 }
1671 Py_INCREF(builtins_import);
1672
1673 mod = PyDict_GetItem(interp->modules, abs_name);
1674 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04001675 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
1676 "None in sys.modules", abs_name);
1677 if (msg != NULL) {
Brian Curtin09b86d12012-04-17 16:57:09 -05001678 PyErr_SetImportError(msg, abs_name, NULL);
1679 Py_DECREF(msg);
Brett Cannon27fc5282012-04-15 14:15:31 -04001680 }
Antoine Pitrou71382cb2012-04-16 18:48:49 +02001681 mod = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001682 goto error_with_unlock;
1683 }
1684 else if (mod != NULL) {
1685 Py_INCREF(mod);
1686 }
1687 else {
1688 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1689 &PyId__find_and_load, abs_name,
1690 builtins_import, NULL);
1691 if (mod == NULL) {
1692 goto error_with_unlock;
1693 }
1694 }
1695
1696 if (PyObject_Not(fromlist)) {
1697 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
1698 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05001699 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001700 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
1701
1702 if (borrowed_dot == NULL) {
1703 goto error_with_unlock;
1704 }
1705
Brian Curtine6b299f2012-04-14 14:19:33 -05001706 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04001707 if (partition == NULL) {
1708 goto error_with_unlock;
1709 }
1710
1711 front = PyTuple_GET_ITEM(partition, 0);
1712 Py_INCREF(front);
1713 Py_DECREF(partition);
1714
1715 if (level == 0) {
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001716 final_mod = PyDict_GetItem(interp->modules, front);
Brett Cannon881535b2012-04-15 15:24:04 -04001717 Py_DECREF(front);
1718 if (final_mod == NULL) {
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001719 PyErr_Format(PyExc_KeyError,
1720 "%R not in sys.modules as expected", front);
Brett Cannon881535b2012-04-15 15:24:04 -04001721 }
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001722 else {
1723 Py_INCREF(final_mod);
1724 }
Brett Cannonfd074152012-04-14 14:10:13 -04001725 }
1726 else {
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001727 Py_ssize_t cut_off = PyUnicode_GET_LENGTH(name) -
1728 PyUnicode_GET_LENGTH(front);
1729 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001730 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001731 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001732 Py_DECREF(front);
1733 if (to_return == NULL) {
1734 goto error_with_unlock;
1735 }
Brett Cannonfd074152012-04-14 14:10:13 -04001736
1737 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04001738 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001739 if (final_mod == NULL) {
1740 PyErr_Format(PyExc_KeyError,
1741 "%R not in sys.modules as expected",
1742 to_return);
1743 }
1744 else {
1745 Py_INCREF(final_mod);
1746 }
Brett Cannonfd074152012-04-14 14:10:13 -04001747 }
1748 }
1749 else {
1750 final_mod = mod;
1751 Py_INCREF(mod);
1752 }
1753 }
1754 else {
1755 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
1756 &PyId__handle_fromlist, mod,
1757 fromlist, builtins_import,
1758 NULL);
1759 }
1760 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05001761#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04001762 if (_PyImport_ReleaseLock() < 0) {
1763 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
1764 }
1765#endif
1766 error:
1767 Py_XDECREF(abs_name);
1768 Py_XDECREF(builtins_import);
1769 Py_XDECREF(mod);
1770 Py_XDECREF(package);
1771 Py_XDECREF(globals);
1772 Py_XDECREF(fromlist);
1773 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001774}
1775
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001776PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001777PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001778 PyObject *fromlist, int level)
1779{
1780 PyObject *nameobj, *mod;
1781 nameobj = PyUnicode_FromString(name);
1782 if (nameobj == NULL)
1783 return NULL;
1784 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1785 fromlist, level);
1786 Py_DECREF(nameobj);
1787 return mod;
1788}
1789
1790
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001791/* Re-import a module of any kind and return its module object, WITH
1792 INCREMENTED REFERENCE COUNT */
1793
Guido van Rossum79f25d91997-04-29 20:08:16 +00001794PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001795PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyInterpreterState *interp = PyThreadState_Get()->interp;
1798 PyObject *modules_reloading = interp->modules_reloading;
1799 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon8a1d04c2012-04-15 17:56:09 -04001800 PyObject *loader = NULL, *existing_m = NULL;
1801 PyObject *name;
Martin v. Löwis796ea532011-10-30 09:07:07 +01001802 Py_ssize_t subname_start;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001803 PyObject *newm = NULL;
Brett Cannon8a1d04c2012-04-15 17:56:09 -04001804 _Py_IDENTIFIER(__loader__);
1805 _Py_IDENTIFIER(load_module);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (modules_reloading == NULL) {
1808 Py_FatalError("PyImport_ReloadModule: "
1809 "no modules_reloading dictionary!");
1810 return NULL;
1811 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (m == NULL || !PyModule_Check(m)) {
1814 PyErr_SetString(PyExc_TypeError,
1815 "reload() argument must be module");
1816 return NULL;
1817 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01001818 name = PyModule_GetNameObject(m);
1819 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01001821 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04001823 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01001824 name);
1825 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return NULL;
1827 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01001828 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (existing_m != NULL) {
1830 /* Due to a recursive reload, this module is already
1831 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01001832 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 Py_INCREF(existing_m);
1834 return existing_m;
1835 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01001836 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
1837 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001839 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001840
Martin v. Löwis796ea532011-10-30 09:07:07 +01001841 subname_start = PyUnicode_FindChar(name, '.', 0,
1842 PyUnicode_GET_LENGTH(name), -1);
Brett Cannon8a1d04c2012-04-15 17:56:09 -04001843 if (subname_start != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 PyObject *parentname, *parent;
Martin v. Löwis796ea532011-10-30 09:07:07 +01001845 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001847 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 }
1849 parent = PyDict_GetItem(modules, parentname);
Brett Cannon8a1d04c2012-04-15 17:56:09 -04001850 Py_XDECREF(parent);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (parent == NULL) {
1852 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04001853 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001855 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00001858
Brett Cannon8a1d04c2012-04-15 17:56:09 -04001859 loader = _PyObject_GetAttrId(m, &PyId___loader__);
1860 if (loader == NULL) {
1861 goto error;
1862 }
1863 newm = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
1864 Py_DECREF(loader);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (newm == NULL) {
1866 /* load_module probably removed name from modules because of
1867 * the error. Put back the original module object. We're
1868 * going to return NULL in this case regardless of whether
1869 * replacing name succeeds, so the return value is ignored.
1870 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01001871 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001873
1874error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01001876 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001878}
1879
1880
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001881/* Higher-level import emulator which emulates the "import" statement
1882 more accurately -- it invokes the __import__() function from the
1883 builtins of the current globals. This means that the import is
1884 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001885 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001886 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001887 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001888 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001889
1890PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001891PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 static PyObject *silly_list = NULL;
1894 static PyObject *builtins_str = NULL;
1895 static PyObject *import_str = NULL;
1896 PyObject *globals = NULL;
1897 PyObject *import = NULL;
1898 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001899 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 /* Initialize constant string objects */
1903 if (silly_list == NULL) {
1904 import_str = PyUnicode_InternFromString("__import__");
1905 if (import_str == NULL)
1906 return NULL;
1907 builtins_str = PyUnicode_InternFromString("__builtins__");
1908 if (builtins_str == NULL)
1909 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001910 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (silly_list == NULL)
1912 return NULL;
1913 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 /* Get the builtins from current globals */
1916 globals = PyEval_GetGlobals();
1917 if (globals != NULL) {
1918 Py_INCREF(globals);
1919 builtins = PyObject_GetItem(globals, builtins_str);
1920 if (builtins == NULL)
1921 goto err;
1922 }
1923 else {
1924 /* No globals -- use standard builtins, and fake globals */
1925 builtins = PyImport_ImportModuleLevel("builtins",
1926 NULL, NULL, NULL, 0);
1927 if (builtins == NULL)
1928 return NULL;
1929 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1930 if (globals == NULL)
1931 goto err;
1932 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 /* Get the __import__ function from the builtins */
1935 if (PyDict_Check(builtins)) {
1936 import = PyObject_GetItem(builtins, import_str);
1937 if (import == NULL)
1938 PyErr_SetObject(PyExc_KeyError, import_str);
1939 }
1940 else
1941 import = PyObject_GetAttr(builtins, import_str);
1942 if (import == NULL)
1943 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001946 Always use absolute import here.
1947 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1949 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001950 if (r == NULL)
1951 goto err;
1952 Py_DECREF(r);
1953
1954 modules = PyImport_GetModuleDict();
1955 r = PyDict_GetItem(modules, module_name);
1956 if (r != NULL)
1957 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001958
1959 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 Py_XDECREF(globals);
1961 Py_XDECREF(builtins);
1962 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001965}
1966
1967
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001968/* Module 'imp' provides Python access to the primitives used for
1969 importing modules.
1970*/
1971
Guido van Rossum79f25d91997-04-29 20:08:16 +00001972static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001973imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 buf[0] = (char) ((magic >> 0) & 0xff);
1978 buf[1] = (char) ((magic >> 8) & 0xff);
1979 buf[2] = (char) ((magic >> 16) & 0xff);
1980 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00001983}
Barry Warsaw28a691b2010-04-17 00:19:56 +00001984
1985static PyObject *
1986imp_get_magic(PyObject *self, PyObject *noargs)
1987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00001989}
1990
1991static PyObject *
1992imp_get_tag(PyObject *self, PyObject *noargs)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001995}
1996
Guido van Rossum79f25d91997-04-29 20:08:16 +00001997static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00001998imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 PyObject *list;
2001 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 list = PyList_New(0);
2004 if (list == NULL)
2005 return NULL;
2006 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2007 PyObject *item = Py_BuildValue("ssi",
2008 fdp->suffix, fdp->mode, fdp->type);
2009 if (item == NULL) {
2010 Py_DECREF(list);
2011 return NULL;
2012 }
2013 if (PyList_Append(list, item) < 0) {
2014 Py_DECREF(list);
2015 Py_DECREF(item);
2016 return NULL;
2017 }
2018 Py_DECREF(item);
2019 }
2020 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002021}
2022
Guido van Rossum79f25d91997-04-29 20:08:16 +00002023static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002024imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002025{
Victor Stinner95872862011-03-07 18:20:56 +01002026 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 int ret;
2028 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01002029 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return NULL;
2031 ret = init_builtin(name);
2032 if (ret < 0)
2033 return NULL;
2034 if (ret == 0) {
2035 Py_INCREF(Py_None);
2036 return Py_None;
2037 }
Victor Stinner95872862011-03-07 18:20:56 +01002038 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 Py_XINCREF(m);
2040 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002041}
2042
Guido van Rossum79f25d91997-04-29 20:08:16 +00002043static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002044imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002045{
Victor Stinner53dc7352011-03-20 01:50:21 +01002046 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 int ret;
2048 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01002049 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002051 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (ret < 0)
2053 return NULL;
2054 if (ret == 0) {
2055 Py_INCREF(Py_None);
2056 return Py_None;
2057 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002058 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 Py_XINCREF(m);
2060 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002061}
2062
Guido van Rossum79f25d91997-04-29 20:08:16 +00002063static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002064imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002065{
Victor Stinner53dc7352011-03-20 01:50:21 +01002066 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002067
Victor Stinner53dc7352011-03-20 01:50:21 +01002068 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 return NULL;
2070 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002071}
2072
Guido van Rossum79f25d91997-04-29 20:08:16 +00002073static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00002074imp_is_frozen_package(PyObject *self, PyObject *args)
2075{
Victor Stinner53dc7352011-03-20 01:50:21 +01002076 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00002077
Victor Stinner53dc7352011-03-20 01:50:21 +01002078 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 return NULL;
2080 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002081}
2082
2083static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002084imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002085{
Victor Stinner95872862011-03-07 18:20:56 +01002086 PyObject *name;
2087 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 return NULL;
2089 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002090}
2091
Guido van Rossum79f25d91997-04-29 20:08:16 +00002092static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002093imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002094{
Victor Stinner53dc7352011-03-20 01:50:21 +01002095 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01002097 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return NULL;
2099 p = find_frozen(name);
2100 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101}
2102
2103static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01002104get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 FILE *fp;
2107 if (mode[0] == 'U')
2108 mode = "r" PY_STDIOTEXTMODE;
2109 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01002110 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01002111 if (!fp) {
2112 if (!PyErr_Occurred())
2113 PyErr_SetFromErrno(PyExc_IOError);
2114 return NULL;
2115 }
2116 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 }
2118 else {
2119 int fd = PyObject_AsFileDescriptor(fob);
2120 if (fd == -1)
2121 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01002122 if (!_PyVerify_fd(fd)) {
2123 PyErr_SetFromErrno(PyExc_IOError);
2124 return NULL;
2125 }
2126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 /* the FILE struct gets a new fd, so that it can be closed
2128 * independently of the file descriptor given
2129 */
2130 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01002131 if (fd == -1) {
2132 PyErr_SetFromErrno(PyExc_IOError);
2133 return NULL;
2134 }
2135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01002137 if (!fp) {
2138 PyErr_SetFromErrno(PyExc_IOError);
2139 return NULL;
2140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01002142 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002143}
2144
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002145#ifdef HAVE_DYNAMIC_LOADING
2146
Guido van Rossum79f25d91997-04-29 20:08:16 +00002147static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002148imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002149{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002150 PyObject *name, *pathname, *fob = NULL, *mod;
2151 FILE *fp;
2152
2153 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
2154 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002156 if (fob != NULL) {
2157 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002158 if (fp == NULL) {
2159 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002161 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002163 else
2164 fp = NULL;
2165 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002166 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 if (fp)
2168 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002169 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002170}
2171
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002172#endif /* HAVE_DYNAMIC_LOADING */
2173
Guido van Rossum79f25d91997-04-29 20:08:16 +00002174static PyObject *
Christian Heimes13a7a212008-01-07 17:13:09 +00002175imp_reload(PyObject *self, PyObject *v)
2176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00002178}
2179
2180PyDoc_STRVAR(doc_reload,
2181"reload(module) -> module\n\
2182\n\
2183Reload the module. The module must have been successfully imported before.");
2184
Barry Warsaw28a691b2010-04-17 00:19:56 +00002185
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002186/* Doc strings */
2187
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002188PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002189"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002190
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002191PyDoc_STRVAR(doc_get_magic,
2192"get_magic() -> string\n\
2193Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002194
Barry Warsaw28a691b2010-04-17 00:19:56 +00002195PyDoc_STRVAR(doc_get_tag,
2196"get_tag() -> string\n\
2197Return the magic tag for .pyc or .pyo files.");
2198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002199PyDoc_STRVAR(doc_get_suffixes,
2200"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002201Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002202that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002203
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002204PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002205"lock_held() -> boolean\n\
2206Return True if the import lock is currently held, else False.\n\
2207On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002208
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002209PyDoc_STRVAR(doc_acquire_lock,
2210"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002211Acquires the interpreter's import lock for the current thread.\n\
2212This lock should be used by import hooks to ensure thread-safety\n\
2213when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002214On platforms without threads, this function does nothing.");
2215
2216PyDoc_STRVAR(doc_release_lock,
2217"release_lock() -> None\n\
2218Release the interpreter's import lock.\n\
2219On platforms without threads, this function does nothing.");
2220
Guido van Rossum79f25d91997-04-29 20:08:16 +00002221static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2223 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
2224 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2226 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2227 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
2228 {"reload", imp_reload, METH_O, doc_reload},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2230 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
2231 {"init_builtin", imp_init_builtin, METH_VARARGS},
2232 {"init_frozen", imp_init_frozen, METH_VARARGS},
2233 {"is_builtin", imp_is_builtin, METH_VARARGS},
2234 {"is_frozen", imp_is_frozen, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002235#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002237#endif
Brett Cannon442c9b92011-03-23 16:14:42 -07002238 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002240};
2241
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002242static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002243setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyObject *v;
2246 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 v = PyLong_FromLong((long)value);
2249 err = PyDict_SetItemString(d, name, v);
2250 Py_XDECREF(v);
2251 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002252}
2253
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002254typedef struct {
2255 PyObject_HEAD
2256} NullImporter;
2257
2258static int
2259NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
2260{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002261#ifndef MS_WINDOWS
2262 PyObject *path;
2263 struct stat statbuf;
2264 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2267 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002268
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002269 if (!PyArg_ParseTuple(args, "O&:NullImporter",
2270 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002272
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002273 if (PyBytes_GET_SIZE(path) == 0) {
2274 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyErr_SetString(PyExc_ImportError, "empty pathname");
2276 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002278
2279 rv = stat(PyBytes_AS_STRING(path), &statbuf);
2280 Py_DECREF(path);
2281 if (rv == 0) {
2282 /* it exists */
2283 if (S_ISDIR(statbuf.st_mode)) {
2284 /* it's a directory */
2285 PyErr_SetString(PyExc_ImportError, "existing directory");
2286 return -1;
2287 }
2288 }
2289#else /* MS_WINDOWS */
2290 PyObject *pathobj;
2291 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00002292 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002293
2294 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2295 return -1;
2296
2297 if (!PyArg_ParseTuple(args, "U:NullImporter",
2298 &pathobj))
2299 return -1;
2300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002301 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002302 PyErr_SetString(PyExc_ImportError, "empty pathname");
2303 return -1;
2304 }
2305
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002306 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00002307 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002308 return -1;
2309 /* see issue1293 and issue3677:
2310 * stat() on Windows doesn't recognise paths like
2311 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
2312 */
2313 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00002314 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00002315 if (rv != INVALID_FILE_ATTRIBUTES) {
2316 /* it exists */
2317 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
2318 /* it's a directory */
2319 PyErr_SetString(PyExc_ImportError, "existing directory");
2320 return -1;
2321 }
2322 }
2323#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002325}
2326
2327static PyObject *
2328NullImporter_find_module(NullImporter *self, PyObject *args)
2329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002331}
2332
2333static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
2335 "Always return None"
2336 },
2337 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002338};
2339
2340
Christian Heimes9cd17752007-11-18 19:35:23 +00002341PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 PyVarObject_HEAD_INIT(NULL, 0)
2343 "imp.NullImporter", /*tp_name*/
2344 sizeof(NullImporter), /*tp_basicsize*/
2345 0, /*tp_itemsize*/
2346 0, /*tp_dealloc*/
2347 0, /*tp_print*/
2348 0, /*tp_getattr*/
2349 0, /*tp_setattr*/
2350 0, /*tp_reserved*/
2351 0, /*tp_repr*/
2352 0, /*tp_as_number*/
2353 0, /*tp_as_sequence*/
2354 0, /*tp_as_mapping*/
2355 0, /*tp_hash */
2356 0, /*tp_call*/
2357 0, /*tp_str*/
2358 0, /*tp_getattro*/
2359 0, /*tp_setattro*/
2360 0, /*tp_as_buffer*/
2361 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2362 "Null importer object", /* tp_doc */
2363 0, /* tp_traverse */
2364 0, /* tp_clear */
2365 0, /* tp_richcompare */
2366 0, /* tp_weaklistoffset */
2367 0, /* tp_iter */
2368 0, /* tp_iternext */
2369 NullImporter_methods, /* tp_methods */
2370 0, /* tp_members */
2371 0, /* tp_getset */
2372 0, /* tp_base */
2373 0, /* tp_dict */
2374 0, /* tp_descr_get */
2375 0, /* tp_descr_set */
2376 0, /* tp_dictoffset */
2377 (initproc)NullImporter_init, /* tp_init */
2378 0, /* tp_alloc */
2379 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002380};
2381
Martin v. Löwis1a214512008-06-11 05:26:20 +00002382static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002384 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 doc_imp,
2386 0,
2387 imp_methods,
2388 NULL,
2389 NULL,
2390 NULL,
2391 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002392};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002393
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002394PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002395PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (PyType_Ready(&PyNullImporter_Type) < 0)
2400 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 m = PyModule_Create(&impmodule);
2403 if (m == NULL)
2404 goto failure;
2405 d = PyModule_GetDict(m);
2406 if (d == NULL)
2407 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2410 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2411 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2412 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2413 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2414 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2415 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2416 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2417 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2418 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 Py_INCREF(&PyNullImporter_Type);
2421 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
2422 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002423 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 Py_XDECREF(m);
2425 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002426}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002427
2428
Guido van Rossumb18618d2000-05-03 23:44:39 +00002429/* API for embedding applications that want to add their own entries
2430 to the table of built-in modules. This should normally be called
2431 *before* Py_Initialize(). When the table resize fails, -1 is
2432 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002433
2434 After a similar function by Just van Rossum. */
2435
2436int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002437PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 static struct _inittab *our_copy = NULL;
2440 struct _inittab *p;
2441 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 /* Count the number of entries in both tables */
2444 for (n = 0; newtab[n].name != NULL; n++)
2445 ;
2446 if (n == 0)
2447 return 0; /* Nothing to do */
2448 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2449 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* Allocate new memory for the combined table */
2452 p = our_copy;
2453 PyMem_RESIZE(p, struct _inittab, i+n+1);
2454 if (p == NULL)
2455 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* Copy the tables into the new memory */
2458 if (our_copy != PyImport_Inittab)
2459 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2460 PyImport_Inittab = our_copy = p;
2461 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002464}
2465
2466/* Shorthand to add a single entry given a name and a function */
2467
2468int
Brett Cannona826f322009-04-02 03:41:46 +00002469PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 newtab[0].name = (char *)name;
2476 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002479}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480
2481#ifdef __cplusplus
2482}
2483#endif