blob: f655e514d1b98517ebe4b32218e62271797f7fe9 [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)
Tim Peters36515e22001-11-18 04:06:29 +0000105*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000106
Nick Coghlancd419ab2010-09-11 00:39:25 +0000107/* MAGIC must change whenever the bytecode emitted by the compiler may no
108 longer be understood by older implementations of the eval loop (usually
109 due to the addition of new opcodes)
110 TAG must change for each major Python release. The magic number will take
111 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112*/
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000113#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114#define TAG "cpython-32"
115#define CACHEDIR "__pycache__"
116/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000117static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000119
Victor Stinner49d3f252010-10-17 01:24:53 +0000120/* See _PyImport_FixupExtensionUnicode() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000122
Guido van Rossum771c6c81997-10-31 18:37:24 +0000123/* This table is defined in config.c: */
124extern struct _inittab _PyImport_Inittab[];
125
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000126/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000127extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000128
Guido van Rossum771c6c81997-10-31 18:37:24 +0000129struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000130
Guido van Rossumed1170e1999-12-20 21:23:41 +0000131/* these tables define the module suffixes that Python recognizes */
132struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000133
Guido van Rossumed1170e1999-12-20 21:23:41 +0000134static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000136#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 {".pyc", "rb", PY_COMPILED},
140 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000141};
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000144/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145
146void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000147_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 const struct filedescr *scan;
150 struct filedescr *filetab;
151 int countD = 0;
152 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 /* prepare _PyImport_Filetab: copy entries from
155 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
156 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000157#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
159 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
162 ++countS;
163 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
164 if (filetab == NULL)
165 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000166#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 memcpy(filetab, _PyImport_DynLoadFiletab,
168 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000169#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 memcpy(filetab + countD, _PyImport_StandardFiletab,
171 countS * sizeof(struct filedescr));
172 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (Py_OptimizeFlag) {
177 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
178 for (; filetab->suffix != NULL; filetab++) {
179 if (strcmp(filetab->suffix, ".pyc") == 0)
180 filetab->suffix = ".pyo";
181 }
182 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185void
Just van Rossum52e14d62002-12-30 22:08:05 +0000186_PyImportHooks_Init(void)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyObject *v, *path_hooks = NULL, *zimpimport;
189 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* adding sys.path_hooks and sys.path_importer_cache, setting up
192 zipimport */
193 if (PyType_Ready(&PyNullImporter_Type) < 0)
194 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (Py_VerboseFlag)
197 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 v = PyList_New(0);
200 if (v == NULL)
201 goto error;
202 err = PySys_SetObject("meta_path", v);
203 Py_DECREF(v);
204 if (err)
205 goto error;
206 v = PyDict_New();
207 if (v == NULL)
208 goto error;
209 err = PySys_SetObject("path_importer_cache", v);
210 Py_DECREF(v);
211 if (err)
212 goto error;
213 path_hooks = PyList_New(0);
214 if (path_hooks == NULL)
215 goto error;
216 err = PySys_SetObject("path_hooks", path_hooks);
217 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000218 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 PyErr_Print();
220 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
221 "path_importer_cache, or NullImporter failed"
222 );
223 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 zimpimport = PyImport_ImportModule("zipimport");
226 if (zimpimport == NULL) {
227 PyErr_Clear(); /* No zip import module -- okay */
228 if (Py_VerboseFlag)
229 PySys_WriteStderr("# can't import zipimport\n");
230 }
231 else {
232 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
233 "zipimporter");
234 Py_DECREF(zimpimport);
235 if (zipimporter == NULL) {
236 PyErr_Clear(); /* No zipimporter object -- okay */
237 if (Py_VerboseFlag)
238 PySys_WriteStderr(
239 "# can't import zipimport.zipimporter\n");
240 }
241 else {
242 /* sys.path_hooks.append(zipimporter) */
243 err = PyList_Append(path_hooks, zipimporter);
244 Py_DECREF(zipimporter);
245 if (err)
246 goto error;
247 if (Py_VerboseFlag)
248 PySys_WriteStderr(
249 "# installed zipimport hook\n");
250 }
251 }
252 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000253}
254
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000255/* Locking primitives to prevent parallel imports of the same module
256 in different threads to return with a partially loaded module.
257 These calls are serialized by the global interpreter lock. */
258
259#ifdef WITH_THREAD
260
Guido van Rossum49b56061998-10-01 20:42:43 +0000261#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000262
Guido van Rossum65d5b571998-12-21 19:32:43 +0000263static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000264static long import_lock_thread = -1;
265static int import_lock_level = 0;
266
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000267void
268_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 long me = PyThread_get_thread_ident();
271 if (me == -1)
272 return; /* Too bad */
273 if (import_lock == NULL) {
274 import_lock = PyThread_allocate_lock();
275 if (import_lock == NULL)
276 return; /* Nothing much we can do. */
277 }
278 if (import_lock_thread == me) {
279 import_lock_level++;
280 return;
281 }
282 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
283 {
284 PyThreadState *tstate = PyEval_SaveThread();
285 PyThread_acquire_lock(import_lock, 1);
286 PyEval_RestoreThread(tstate);
287 }
288 import_lock_thread = me;
289 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290}
291
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000292int
293_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 long me = PyThread_get_thread_ident();
296 if (me == -1 || import_lock == NULL)
297 return 0; /* Too bad */
298 if (import_lock_thread != me)
299 return -1;
300 import_lock_level--;
301 if (import_lock_level == 0) {
302 import_lock_thread = -1;
303 PyThread_release_lock(import_lock);
304 }
305 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000306}
307
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000308/* This function is called from PyOS_AfterFork to ensure that newly
309 created child processes do not share locks with the parent.
310 We now acquire the import lock around fork() calls but on some platforms
311 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000312
313void
314_PyImport_ReInitLock(void)
315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (import_lock != NULL)
317 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000318 if (import_lock_level > 1) {
319 /* Forked as a side effect of import */
320 long me = PyThread_get_thread_ident();
321 PyThread_acquire_lock(import_lock, 0);
322 /* XXX: can the previous line fail? */
323 import_lock_thread = me;
324 import_lock_level--;
325 } else {
326 import_lock_thread = -1;
327 import_lock_level = 0;
328 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000329}
330
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000331#endif
332
Tim Peters69232342001-08-30 05:16:13 +0000333static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000334imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000335{
Tim Peters69232342001-08-30 05:16:13 +0000336#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000338#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000340#endif
341}
342
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000343static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000344imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000346#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_INCREF(Py_None);
350 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000351}
352
353static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000354imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000355{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000356#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (_PyImport_ReleaseLock() < 0) {
358 PyErr_SetString(PyExc_RuntimeError,
359 "not holding the import lock");
360 return NULL;
361 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000362#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 Py_INCREF(Py_None);
364 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000365}
366
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100367void
368_PyImport_Fini(void)
369{
370 Py_XDECREF(extensions);
371 extensions = NULL;
372 PyMem_DEL(_PyImport_Filetab);
373 _PyImport_Filetab = NULL;
374#ifdef WITH_THREAD
375 if (import_lock != NULL) {
376 PyThread_free_lock(import_lock);
377 import_lock = NULL;
378 }
379#endif
380}
381
Guido van Rossumd8faa362007-04-27 19:54:29 +0000382static void
383imp_modules_reloading_clear(void)
384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyInterpreterState *interp = PyThreadState_Get()->interp;
386 if (interp->modules_reloading != NULL)
387 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000388}
389
Guido van Rossum25ce5661997-08-02 03:10:38 +0000390/* Helper for sys */
391
392PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000393PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 PyInterpreterState *interp = PyThreadState_GET()->interp;
396 if (interp->modules == NULL)
397 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
398 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000399}
400
Guido van Rossum3f5da241990-12-20 15:06:42 +0000401
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000402/* List of names to clear in sys */
403static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 "path", "argv", "ps1", "ps2",
405 "last_type", "last_value", "last_traceback",
406 "path_hooks", "path_importer_cache", "meta_path",
407 /* misc stuff */
408 "flags", "float_info",
409 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000410};
411
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000412static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 "stdin", "__stdin__",
414 "stdout", "__stdout__",
415 "stderr", "__stderr__",
416 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000417};
418
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000419
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000420/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000421
Guido van Rossum3f5da241990-12-20 15:06:42 +0000422void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000423PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_ssize_t pos, ndone;
426 char *name;
427 PyObject *key, *value, *dict;
428 PyInterpreterState *interp = PyThreadState_GET()->interp;
429 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (modules == NULL)
432 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 /* Delete some special variables first. These are common
435 places where user values hide and people complain when their
436 destructors fail. Since the modules containing them are
437 deleted *last* of all, they would come too late in the normal
438 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 value = PyDict_GetItemString(modules, "builtins");
441 if (value != NULL && PyModule_Check(value)) {
442 dict = PyModule_GetDict(value);
443 if (Py_VerboseFlag)
444 PySys_WriteStderr("# clear builtins._\n");
445 PyDict_SetItemString(dict, "_", Py_None);
446 }
447 value = PyDict_GetItemString(modules, "sys");
448 if (value != NULL && PyModule_Check(value)) {
449 char **p;
450 PyObject *v;
451 dict = PyModule_GetDict(value);
452 for (p = sys_deletes; *p != NULL; p++) {
453 if (Py_VerboseFlag)
454 PySys_WriteStderr("# clear sys.%s\n", *p);
455 PyDict_SetItemString(dict, *p, Py_None);
456 }
457 for (p = sys_files; *p != NULL; p+=2) {
458 if (Py_VerboseFlag)
459 PySys_WriteStderr("# restore sys.%s\n", *p);
460 v = PyDict_GetItemString(dict, *(p+1));
461 if (v == NULL)
462 v = Py_None;
463 PyDict_SetItemString(dict, *p, v);
464 }
465 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* First, delete __main__ */
468 value = PyDict_GetItemString(modules, "__main__");
469 if (value != NULL && PyModule_Check(value)) {
470 if (Py_VerboseFlag)
471 PySys_WriteStderr("# cleanup __main__\n");
472 _PyModule_Clear(value);
473 PyDict_SetItemString(modules, "__main__", Py_None);
474 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* The special treatment of "builtins" here is because even
477 when it's not referenced as a module, its dictionary is
478 referenced by almost every module's __builtins__. Since
479 deleting a module clears its dictionary (even if there are
480 references left to it), we need to delete the "builtins"
481 module last. Likewise, we don't delete sys until the very
482 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Also note that we 'delete' modules by replacing their entry
485 in the modules dict with None, rather than really deleting
486 them; this avoids a rehash of the modules dictionary and
487 also marks them as "non existent" so they won't be
488 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Next, repeatedly delete modules with a reference count of
491 one (skipping builtins and sys) and delete them */
492 do {
493 ndone = 0;
494 pos = 0;
495 while (PyDict_Next(modules, &pos, &key, &value)) {
496 if (value->ob_refcnt != 1)
497 continue;
498 if (PyUnicode_Check(key) && PyModule_Check(value)) {
499 name = _PyUnicode_AsString(key);
500 if (strcmp(name, "builtins") == 0)
501 continue;
502 if (strcmp(name, "sys") == 0)
503 continue;
504 if (Py_VerboseFlag)
505 PySys_WriteStderr(
506 "# cleanup[1] %s\n", name);
507 _PyModule_Clear(value);
508 PyDict_SetItem(modules, key, Py_None);
509 ndone++;
510 }
511 }
512 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 /* Next, delete all modules (still skipping builtins and sys) */
515 pos = 0;
516 while (PyDict_Next(modules, &pos, &key, &value)) {
517 if (PyUnicode_Check(key) && PyModule_Check(value)) {
518 name = _PyUnicode_AsString(key);
519 if (strcmp(name, "builtins") == 0)
520 continue;
521 if (strcmp(name, "sys") == 0)
522 continue;
523 if (Py_VerboseFlag)
524 PySys_WriteStderr("# cleanup[2] %s\n", name);
525 _PyModule_Clear(value);
526 PyDict_SetItem(modules, key, Py_None);
527 }
528 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* Next, delete sys and builtins (in that order) */
531 value = PyDict_GetItemString(modules, "sys");
532 if (value != NULL && PyModule_Check(value)) {
533 if (Py_VerboseFlag)
534 PySys_WriteStderr("# cleanup sys\n");
535 _PyModule_Clear(value);
536 PyDict_SetItemString(modules, "sys", Py_None);
537 }
538 value = PyDict_GetItemString(modules, "builtins");
539 if (value != NULL && PyModule_Check(value)) {
540 if (Py_VerboseFlag)
541 PySys_WriteStderr("# cleanup builtins\n");
542 _PyModule_Clear(value);
543 PyDict_SetItemString(modules, "builtins", Py_None);
544 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* Finally, clear and delete the modules directory */
547 PyDict_Clear(modules);
548 interp->modules = NULL;
549 Py_DECREF(modules);
550 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000551}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000552
553
Barry Warsaw28a691b2010-04-17 00:19:56 +0000554/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555
556long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000557PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560}
561
562
Barry Warsaw28a691b2010-04-17 00:19:56 +0000563const char *
564PyImport_GetMagicTag(void)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000567}
568
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569/* Magic for extension modules (built-in as well as dynamically
570 loaded). To prevent initializing an extension module more than
571 once, we keep a static dictionary 'extensions' keyed by module name
572 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000573 modules), containing these modules. A copy of the module's
Victor Stinner49d3f252010-10-17 01:24:53 +0000574 dictionary is stored by calling _PyImport_FixupExtensionUnicode()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575 immediately after the module initialization function succeeds. A
576 copy can be retrieved from there by calling
Victor Stinner49d3f252010-10-17 01:24:53 +0000577 _PyImport_FindExtensionUnicode().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000578
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000579 Modules which do support multiple initialization set their m_size
580 field to a non-negative number (indicating the size of the
581 module-specific state). They are still recorded in the extensions
582 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000583*/
584
585int
Victor Stinner49d3f252010-10-17 01:24:53 +0000586_PyImport_FixupExtensionUnicode(PyObject *mod, char *name, PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 PyObject *modules, *dict;
589 struct PyModuleDef *def;
590 if (extensions == NULL) {
591 extensions = PyDict_New();
592 if (extensions == NULL)
593 return -1;
594 }
595 if (mod == NULL || !PyModule_Check(mod)) {
596 PyErr_BadInternalCall();
597 return -1;
598 }
599 def = PyModule_GetDef(mod);
600 if (!def) {
601 PyErr_BadInternalCall();
602 return -1;
603 }
604 modules = PyImport_GetModuleDict();
605 if (PyDict_SetItemString(modules, name, mod) < 0)
606 return -1;
607 if (_PyState_AddModule(mod, def) < 0) {
608 PyDict_DelItemString(modules, name);
609 return -1;
610 }
611 if (def->m_size == -1) {
612 if (def->m_base.m_copy) {
613 /* Somebody already imported the module,
614 likely under a different name.
615 XXX this should really not happen. */
616 Py_DECREF(def->m_base.m_copy);
617 def->m_base.m_copy = NULL;
618 }
619 dict = PyModule_GetDict(mod);
620 if (dict == NULL)
621 return -1;
622 def->m_base.m_copy = PyDict_Copy(dict);
623 if (def->m_base.m_copy == NULL)
624 return -1;
625 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000626 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628}
629
Victor Stinner49d3f252010-10-17 01:24:53 +0000630int
631_PyImport_FixupBuiltin(PyObject *mod, char *name)
632{
633 int res;
634 PyObject *filename;
635 filename = PyUnicode_FromString(name);
636 if (filename == NULL)
637 return -1;
638 res = _PyImport_FixupExtensionUnicode(mod, name, filename);
639 Py_DECREF(filename);
640 return res;
641}
642
Guido van Rossum25ce5661997-08-02 03:10:38 +0000643PyObject *
Victor Stinner49d3f252010-10-17 01:24:53 +0000644_PyImport_FindExtensionUnicode(char *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *mod, *mdict;
647 PyModuleDef* def;
648 if (extensions == NULL)
649 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000650 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (def == NULL)
652 return NULL;
653 if (def->m_size == -1) {
654 /* Module does not support repeated initialization */
655 if (def->m_base.m_copy == NULL)
656 return NULL;
657 mod = PyImport_AddModule(name);
658 if (mod == NULL)
659 return NULL;
660 mdict = PyModule_GetDict(mod);
661 if (mdict == NULL)
662 return NULL;
663 if (PyDict_Update(mdict, def->m_base.m_copy))
664 return NULL;
665 }
666 else {
667 if (def->m_base.m_init == NULL)
668 return NULL;
669 mod = def->m_base.m_init();
670 if (mod == NULL)
671 return NULL;
672 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
673 Py_DECREF(mod);
674 }
675 if (_PyState_AddModule(mod, def) < 0) {
676 PyDict_DelItemString(PyImport_GetModuleDict(), name);
677 Py_DECREF(mod);
678 return NULL;
679 }
680 if (Py_VerboseFlag)
Victor Stinner49d3f252010-10-17 01:24:53 +0000681 PySys_FormatStderr("import %s # previously loaded (%U)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 name, filename);
683 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000684
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000685}
686
Victor Stinner49d3f252010-10-17 01:24:53 +0000687PyObject *
688_PyImport_FindBuiltin(char *name)
689{
690 PyObject *res, *filename;
691 filename = PyUnicode_FromString(name);
692 if (filename == NULL)
693 return NULL;
694 res = _PyImport_FindExtensionUnicode(name, filename);
695 Py_DECREF(filename);
696 return res;
697}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698
699/* Get the module object corresponding to a module name.
700 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000701 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000702 Because the former action is most common, THIS DOES NOT RETURN A
703 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000704
Guido van Rossum79f25d91997-04-29 20:08:16 +0000705PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000706PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyObject *modules = PyImport_GetModuleDict();
709 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
712 PyModule_Check(m))
713 return m;
714 m = PyModule_New(name);
715 if (m == NULL)
716 return NULL;
717 if (PyDict_SetItemString(modules, name, m) != 0) {
718 Py_DECREF(m);
719 return NULL;
720 }
721 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724}
725
Tim Peters1cd70172004-08-02 03:52:12 +0000726/* Remove name from sys.modules, if it's there. */
727static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000728remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyObject *modules = PyImport_GetModuleDict();
731 if (PyDict_GetItemString(modules, name) == NULL)
732 return;
733 if (PyDict_DelItemString(modules, name) < 0)
734 Py_FatalError("import: deleting existing key in"
735 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000736}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737
Barry Warsaw28a691b2010-04-17 00:19:56 +0000738static PyObject * get_sourcefile(char *file);
739static char *make_source_pathname(char *pathname, char *buf);
740static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000742
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000743/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000744 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
745 * removed from sys.modules, to avoid leaving damaged module objects
746 * in sys.modules. The caller may wish to restore the original
747 * module object (if any) in this case; PyImport_ReloadModule is an
748 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000749 *
750 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
751 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000752 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000753PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000754PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return PyImport_ExecCodeModuleWithPathnames(
757 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000758}
759
760PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000761PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return PyImport_ExecCodeModuleWithPathnames(
764 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000765}
766
767PyObject *
768PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyObject *modules = PyImport_GetModuleDict();
772 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 m = PyImport_AddModule(name);
775 if (m == NULL)
776 return NULL;
777 /* If the module is being reloaded, we get the old module back
778 and re-use its dict to exec the new code. */
779 d = PyModule_GetDict(m);
780 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
781 if (PyDict_SetItemString(d, "__builtins__",
782 PyEval_GetBuiltins()) != 0)
783 goto error;
784 }
785 /* Remember the filename as the __file__ attribute */
786 v = NULL;
787 if (pathname != NULL) {
788 v = get_sourcefile(pathname);
789 if (v == NULL)
790 PyErr_Clear();
791 }
792 if (v == NULL) {
793 v = ((PyCodeObject *)co)->co_filename;
794 Py_INCREF(v);
795 }
796 if (PyDict_SetItemString(d, "__file__", v) != 0)
797 PyErr_Clear(); /* Not important enough to report */
798 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 /* Remember the pyc path name as the __cached__ attribute. */
801 if (cpathname == NULL) {
802 v = Py_None;
803 Py_INCREF(v);
804 }
805 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
806 PyErr_Clear(); /* Not important enough to report */
807 v = Py_None;
808 Py_INCREF(v);
809 }
810 if (PyDict_SetItemString(d, "__cached__", v) != 0)
811 PyErr_Clear(); /* Not important enough to report */
812 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000813
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000814 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (v == NULL)
816 goto error;
817 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
820 PyErr_Format(PyExc_ImportError,
821 "Loaded module %.200s not found in sys.modules",
822 name);
823 return NULL;
824 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000829
830 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 remove_module(name);
832 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833}
834
835
Barry Warsaw28a691b2010-04-17 00:19:56 +0000836/* Like strrchr(string, '/') but searches for the rightmost of either SEP
837 or ALTSEP, if the latter is defined.
838*/
839static char *
840rightmost_sep(char *s)
841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 char *found, c;
843 for (found = NULL; (c = *s); s++) {
844 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000845#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000847#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 )
849 {
850 found = s;
851 }
852 }
853 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000854}
855
856
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857/* Given a pathname for a Python source file, fill a buffer with the
858 pathname for the corresponding compiled file. Return the pathname
859 for the compiled file, or NULL if there's no space in the buffer.
860 Doesn't set an exception. */
861
862static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000863make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* foo.py -> __pycache__/foo.<tag>.pyc */
866 size_t len = strlen(pathname);
867 size_t i, save;
868 char *pos;
869 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 /* Sanity check that the buffer has roughly enough space to hold what
872 will eventually be the full path to the compiled file. The 5 extra
873 bytes include the slash afer __pycache__, the two extra dots, the
874 extra trailing character ('c' or 'o') and null. This isn't exact
875 because the contents of the buffer can affect how many actual
876 characters of the string get into the buffer. We'll do a final
877 sanity check before writing the extension to ensure we do not
878 overflow the buffer.
879 */
880 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
881 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 /* Find the last path separator and copy everything from the start of
884 the source string up to and including the separator.
885 */
886 if ((pos = rightmost_sep(pathname)) == NULL) {
887 i = 0;
888 }
889 else {
890 sep = *pos;
891 i = pos - pathname + 1;
892 strncpy(buf, pathname, i);
893 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 save = i;
896 buf[i++] = '\0';
897 /* Add __pycache__/ */
898 strcat(buf, CACHEDIR);
899 i += strlen(CACHEDIR) - 1;
900 buf[i++] = sep;
901 buf[i++] = '\0';
902 /* Add the base filename, but remove the .py or .pyw extension, since
903 the tag name must go before the extension.
904 */
905 strcat(buf, pathname + save);
906 if ((pos = strrchr(buf, '.')) != NULL)
907 *++pos = '\0';
908 strcat(buf, pyc_tag);
909 /* The length test above assumes that we're only adding one character
910 to the end of what would normally be the extension. What if there
911 is no extension, or the string ends in '.' or '.p', and otherwise
912 fills the buffer? By appending 4 more characters onto the string
913 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 As a simple example, let's say buflen=32 and the input string is
916 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 which is false and so the name mangling would continue. This would
921 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
926 We can even handle an input string of say 'xxxxx' above because
927 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
928 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 which is 32 characters including the nul, and thus fits in the
933 buffer. However, an input string of 'xxxxxx' would yield a result
934 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 which is 33 characters long (including the nul), thus overflowing
939 the buffer, even though the first test would fail, i.e.: the input
940 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 The reason the first test fails but we still overflow the buffer is
943 that the test above only expects to add one extra character to be
944 added to the extension, and here we're adding three (pyc). We
945 don't add the first dot, so that reclaims one of expected
946 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
947 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 The best we can do is ensure that we still have enough room in the
950 target buffer before we write the extension. Because it's always
951 only the extension that can cause the overflow, and never the other
952 path bytes we've written, it's sufficient to just do one more test
953 here. Still, the assertion that follows can't hurt.
954 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000955#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000957#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (strlen(buf) + 5 > buflen)
959 return NULL;
960 strcat(buf, debug ? ".pyc" : ".pyo");
961 assert(strlen(buf) < buflen);
962 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000963}
964
965
Barry Warsaw28a691b2010-04-17 00:19:56 +0000966/* Given a pathname to a Python byte compiled file, return the path to the
967 source file, if the path matches the PEP 3147 format. This does not check
968 for any file existence, however, if the pyc file name does not match PEP
969 3147 style, NULL is returned. buf must be at least as big as pathname;
970 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971
Barry Warsaw28a691b2010-04-17 00:19:56 +0000972static char *
973make_source_pathname(char *pathname, char *buf)
974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 /* __pycache__/foo.<tag>.pyc -> foo.py */
976 size_t i, j;
977 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* Look back two slashes from the end. In between these two slashes
980 must be the string __pycache__ or this is not a PEP 3147 style
981 path. It's possible for there to be only one slash.
982 */
983 if ((right = rightmost_sep(pathname)) == NULL)
984 return NULL;
985 sep = *right;
986 *right = '\0';
987 left = rightmost_sep(pathname);
988 *right = sep;
989 if (left == NULL)
990 left = pathname;
991 else
992 left++;
993 if (right-left != strlen(CACHEDIR) ||
994 strncmp(left, CACHEDIR, right-left) != 0)
995 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* Now verify that the path component to the right of the last slash
998 has two dots in it.
999 */
1000 if ((dot0 = strchr(right + 1, '.')) == NULL)
1001 return NULL;
1002 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
1003 return NULL;
1004 /* Too many dots? */
1005 if (strchr(dot1 + 1, '.') != NULL)
1006 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* This is a PEP 3147 path. Start by copying everything from the
1009 start of pathname up to and including the leftmost slash. Then
1010 copy the file's basename, removing the magic tag and adding a .py
1011 suffix.
1012 */
1013 strncpy(buf, pathname, (i=left-pathname));
1014 strncpy(buf+i, right+1, (j=dot0-right));
1015 strcpy(buf+i+j, "py");
1016 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001017}
1018
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001019/* Given a pathname for a Python source file, its time of last
1020 modification, and a pathname for a compiled file, check whether the
1021 compiled file represents the same version of the source. If so,
1022 return a FILE pointer for the compiled file, positioned just after
1023 the header; if not, return NULL.
1024 Doesn't set an exception. */
1025
1026static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001027check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 FILE *fp;
1030 long magic;
1031 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 fp = fopen(cpathname, "rb");
1034 if (fp == NULL)
1035 return NULL;
1036 magic = PyMarshal_ReadLongFromFile(fp);
1037 if (magic != pyc_magic) {
1038 if (Py_VerboseFlag)
1039 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1040 fclose(fp);
1041 return NULL;
1042 }
1043 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1044 if (pyc_mtime != mtime) {
1045 if (Py_VerboseFlag)
1046 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1047 fclose(fp);
1048 return NULL;
1049 }
1050 if (Py_VerboseFlag)
1051 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1052 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001053}
1054
1055
1056/* Read a code object from a file and check it for validity */
1057
Guido van Rossum79f25d91997-04-29 20:08:16 +00001058static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001059read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 co = PyMarshal_ReadLastObjectFromFile(fp);
1064 if (co == NULL)
1065 return NULL;
1066 if (!PyCode_Check(co)) {
1067 PyErr_Format(PyExc_ImportError,
1068 "Non-code object in %.200s", cpathname);
1069 Py_DECREF(co);
1070 return NULL;
1071 }
1072 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001073}
1074
1075
1076/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001077 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001078
Guido van Rossum79f25d91997-04-29 20:08:16 +00001079static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001080load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 long magic;
1083 PyCodeObject *co;
1084 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 magic = PyMarshal_ReadLongFromFile(fp);
1087 if (magic != pyc_magic) {
1088 PyErr_Format(PyExc_ImportError,
1089 "Bad magic number in %.200s", cpathname);
1090 return NULL;
1091 }
1092 (void) PyMarshal_ReadLongFromFile(fp);
1093 co = read_compiled_module(cpathname, fp);
1094 if (co == NULL)
1095 return NULL;
1096 if (Py_VerboseFlag)
1097 PySys_WriteStderr("import %s # precompiled from %s\n",
1098 name, cpathname);
1099 m = PyImport_ExecCodeModuleWithPathnames(
1100 name, (PyObject *)co, cpathname, cpathname);
1101 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001104}
1105
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001106/* Parse a source file and return the corresponding code object */
1107
Guido van Rossum79f25d91997-04-29 20:08:16 +00001108static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyCodeObject *co = NULL;
1112 mod_ty mod;
1113 PyCompilerFlags flags;
1114 PyArena *arena = PyArena_New();
1115 if (arena == NULL)
1116 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 flags.cf_flags = 0;
1119 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1120 Py_file_input, 0, 0, &flags,
1121 NULL, arena);
1122 if (mod) {
1123 co = PyAST_Compile(mod, pathname, NULL, arena);
1124 }
1125 PyArena_Free(arena);
1126 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001127}
1128
1129
Guido van Rossum55a83382000-09-20 20:31:38 +00001130/* Helper to open a bytecode file for writing in exclusive mode */
1131
1132static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001133open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001134{
1135#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* Use O_EXCL to avoid a race condition when another process tries to
1137 write the same file. When that happens, our open() call fails,
1138 which is just fine (since it's only a cache).
1139 XXX If the file exists and is writable but the directory is not
1140 writable, the file will never be written. Oh well.
1141 */
1142 int fd;
1143 (void) unlink(filename);
1144 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001145#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001147#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001148#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001150#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001152#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 );
1154 if (fd < 0)
1155 return NULL;
1156 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001157#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 /* Best we can do -- on Windows this can't happen anyway */
1159 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001160#endif
1161}
1162
1163
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001164/* Write a compiled module to a file, placing the time of last
1165 modification of its source into the header.
1166 Errors are ignored, if a write error occurs an attempt is made to
1167 remove the file. */
1168
1169static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001170write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 FILE *fp;
1173 char *dirpath;
1174 time_t mtime = srcstat->st_mtime;
Nick Coghlan557c76c2012-10-20 11:43:58 +10001175 int saved;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001176#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Nick Coghlan34937ce2012-10-19 22:38:14 +10001178 /* Issue #6074: We ensure user write access, so we can delete it later
1179 * when the source file changes. (On POSIX, this only requires write
1180 * access to the directory, on Windows, we need write access to the file
1181 * as well)
1182 */
1183 mode |= _S_IWRITE;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001184#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1186 mode_t dirmode = (srcstat->st_mode |
1187 S_IXUSR | S_IXGRP | S_IXOTH |
1188 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001189#endif
Barry Warsaw28a691b2010-04-17 00:19:56 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* Ensure that the __pycache__ directory exists. */
1192 dirpath = rightmost_sep(cpathname);
1193 if (dirpath == NULL) {
1194 if (Py_VerboseFlag)
1195 PySys_WriteStderr(
1196 "# no %s path found %s\n",
1197 CACHEDIR, cpathname);
1198 return;
1199 }
1200 saved = *dirpath;
1201 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001202
1203#ifdef MS_WINDOWS
1204 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1205#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001207#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 *dirpath = saved;
1209 if (Py_VerboseFlag)
1210 PySys_WriteStderr(
1211 "# cannot create cache dir %s\n", cpathname);
1212 return;
1213 }
1214 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 fp = open_exclusive(cpathname, mode);
1217 if (fp == NULL) {
1218 if (Py_VerboseFlag)
1219 PySys_WriteStderr(
1220 "# can't create %s\n", cpathname);
1221 return;
1222 }
1223 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1224 /* First write a 0 for mtime */
1225 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1226 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1227 if (fflush(fp) != 0 || ferror(fp)) {
1228 if (Py_VerboseFlag)
1229 PySys_WriteStderr("# can't write %s\n", cpathname);
1230 /* Don't keep partial file */
1231 fclose(fp);
1232 (void) unlink(cpathname);
1233 return;
1234 }
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001235 /* Now write the true mtime (as a 32-bit field) */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 fseek(fp, 4L, 0);
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001237 assert(mtime <= 0xFFFFFFFF);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1239 fflush(fp);
1240 fclose(fp);
1241 if (Py_VerboseFlag)
1242 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243}
1244
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001245static void
1246update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyObject *constants, *tmp;
1249 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (PyUnicode_Compare(co->co_filename, oldname))
1252 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 tmp = co->co_filename;
1255 co->co_filename = newname;
1256 Py_INCREF(co->co_filename);
1257 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 constants = co->co_consts;
1260 n = PyTuple_GET_SIZE(constants);
1261 for (i = 0; i < n; i++) {
1262 tmp = PyTuple_GET_ITEM(constants, i);
1263 if (PyCode_Check(tmp))
1264 update_code_filenames((PyCodeObject *)tmp,
1265 oldname, newname);
1266 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001267}
1268
1269static int
1270update_compiled_module(PyCodeObject *co, char *pathname)
1271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 newname = PyUnicode_DecodeFSDefault(pathname);
1275 if (newname == NULL)
1276 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!PyUnicode_Compare(co->co_filename, newname)) {
1279 Py_DECREF(newname);
1280 return 0;
1281 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 oldname = co->co_filename;
1284 Py_INCREF(oldname);
1285 update_code_filenames(co, oldname, newname);
1286 Py_DECREF(oldname);
1287 Py_DECREF(newname);
1288 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001289}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001290
1291/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001292 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1293 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001294
Guido van Rossum79f25d91997-04-29 20:08:16 +00001295static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001296load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 struct stat st;
1299 FILE *fpc;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001300 char *buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 char *cpathname;
Antoine Pitroud576c712012-05-09 13:24:31 +02001302 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (fstat(fileno(fp), &st) != 0) {
1306 PyErr_Format(PyExc_RuntimeError,
1307 "unable to get file status from '%s'",
1308 pathname);
1309 return NULL;
1310 }
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001311 if (sizeof st.st_mtime > 4) {
1312 /* Python's .pyc timestamp handling presumes that the timestamp fits
1313 in 4 bytes. Since the code only does an equality comparison,
1314 ordering is not important and we can safely ignore the higher bits
1315 (collisions are extremely unlikely).
1316 */
1317 st.st_mtime &= 0xFFFFFFFF;
1318 }
Gregory P. Smithc809f982012-03-18 16:06:53 -07001319 buf = PyMem_MALLOC(MAXPATHLEN+1);
1320 if (buf == NULL) {
1321 return PyErr_NoMemory();
1322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 cpathname = make_compiled_pathname(
1324 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1325 if (cpathname != NULL &&
1326 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1327 co = read_compiled_module(cpathname, fpc);
1328 fclose(fpc);
1329 if (co == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001330 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (update_compiled_module(co, pathname) < 0)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001332 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (Py_VerboseFlag)
1334 PySys_WriteStderr("import %s # precompiled from %s\n",
1335 name, cpathname);
1336 pathname = cpathname;
1337 }
1338 else {
1339 co = parse_source_module(pathname, fp);
1340 if (co == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001341 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (Py_VerboseFlag)
1343 PySys_WriteStderr("import %s # from %s\n",
1344 name, pathname);
1345 if (cpathname) {
1346 PyObject *ro = PySys_GetObject("dont_write_bytecode");
Antoine Pitrou6f430e42012-08-15 23:18:25 +02001347 int b = (ro == NULL) ? 0 : PyObject_IsTrue(ro);
1348 if (b < 0)
1349 goto error_exit;
1350 if (!b)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 write_compiled_module(co, cpathname, &st);
1352 }
1353 }
1354 m = PyImport_ExecCodeModuleWithPathnames(
1355 name, (PyObject *)co, pathname, cpathname);
1356 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001357
Gregory P. Smithc809f982012-03-18 16:06:53 -07001358 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 return m;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001360
1361error_exit:
Antoine Pitroud576c712012-05-09 13:24:31 +02001362 Py_XDECREF(co);
Gregory P. Smithc809f982012-03-18 16:06:53 -07001363 PyMem_FREE(buf);
1364 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001365}
1366
Christian Heimes3b06e532008-01-07 20:12:44 +00001367/* Get source file -> unicode or None
1368 * Returns the path to the py file if available, else the given path
1369 */
1370static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001371get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001372{
Gregory P. Smithc809f982012-03-18 16:06:53 -07001373 char *py = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 Py_ssize_t len;
1375 PyObject *u;
1376 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (!file || !*file) {
1379 Py_RETURN_NONE;
1380 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 len = strlen(file);
1383 /* match '*.py?' */
1384 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1385 return PyUnicode_DecodeFSDefault(file);
1386 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001387
Gregory P. Smithc809f982012-03-18 16:06:53 -07001388 py = PyMem_MALLOC(MAXPATHLEN+1);
1389 if (py == NULL) {
1390 return PyErr_NoMemory();
1391 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* Start by trying to turn PEP 3147 path into source path. If that
1393 * fails, just chop off the trailing character, i.e. legacy pyc path
1394 * to py.
1395 */
1396 if (make_source_pathname(file, py) == NULL) {
1397 strncpy(py, file, len-1);
1398 py[len-1] = '\0';
1399 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (stat(py, &statbuf) == 0 &&
1402 S_ISREG(statbuf.st_mode)) {
1403 u = PyUnicode_DecodeFSDefault(py);
1404 }
1405 else {
1406 u = PyUnicode_DecodeFSDefault(file);
1407 }
Gregory P. Smithc809f982012-03-18 16:06:53 -07001408 PyMem_FREE(py);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001410}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001411
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001412/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001413static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1414static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001416static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001417
1418/* Load a package and return its module object WITH INCREMENTED
1419 REFERENCE COUNT */
1420
1421static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001422load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 PyObject *m, *d;
1425 PyObject *file = NULL;
1426 PyObject *path = NULL;
1427 int err;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001428 char *buf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 FILE *fp = NULL;
1430 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 m = PyImport_AddModule(name);
1433 if (m == NULL)
1434 return NULL;
1435 if (Py_VerboseFlag)
1436 PySys_WriteStderr("import %s # directory %s\n",
1437 name, pathname);
1438 d = PyModule_GetDict(m);
1439 file = get_sourcefile(pathname);
1440 if (file == NULL)
1441 goto error;
1442 path = Py_BuildValue("[O]", file);
1443 if (path == NULL)
1444 goto error;
1445 err = PyDict_SetItemString(d, "__file__", file);
1446 if (err == 0)
1447 err = PyDict_SetItemString(d, "__path__", path);
1448 if (err != 0)
1449 goto error;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001450 buf = PyMem_MALLOC(MAXPATHLEN+1);
1451 if (buf == NULL) {
1452 PyErr_NoMemory();
1453 goto error;
1454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 buf[0] = '\0';
Gregory P. Smithc809f982012-03-18 16:06:53 -07001456 fdp = find_module(name, "__init__", path, buf, MAXPATHLEN+1, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 if (fdp == NULL) {
1458 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1459 PyErr_Clear();
1460 Py_INCREF(m);
1461 }
1462 else
1463 m = NULL;
1464 goto cleanup;
1465 }
1466 m = load_module(name, fp, buf, fdp->type, NULL);
1467 if (fp != NULL)
1468 fclose(fp);
1469 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001470
1471 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001473 cleanup:
Gregory P. Smithc809f982012-03-18 16:06:53 -07001474 if (buf)
1475 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 Py_XDECREF(path);
1477 Py_XDECREF(file);
1478 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001479}
1480
1481
1482/* Helper to test for built-in module */
1483
1484static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001485is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 int i;
1488 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1489 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1490 if (PyImport_Inittab[i].initfunc == NULL)
1491 return -1;
1492 else
1493 return 1;
1494 }
1495 }
1496 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001497}
1498
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001499
Just van Rossum52e14d62002-12-30 22:08:05 +00001500/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1501 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001502 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001503 that can handle the path item. Return None if no hook could;
1504 this tells our caller it should fall back to the builtin
1505 import mechanism. Cache the result in path_importer_cache.
1506 Returns a borrowed reference. */
1507
1508static PyObject *
1509get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 PyObject *importer;
1513 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 /* These conditions are the caller's responsibility: */
1516 assert(PyList_Check(path_hooks));
1517 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 nhooks = PyList_Size(path_hooks);
1520 if (nhooks < 0)
1521 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 importer = PyDict_GetItem(path_importer_cache, p);
1524 if (importer != NULL)
1525 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 /* set path_importer_cache[p] to None to avoid recursion */
1528 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1529 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 for (j = 0; j < nhooks; j++) {
1532 PyObject *hook = PyList_GetItem(path_hooks, j);
1533 if (hook == NULL)
1534 return NULL;
1535 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1536 if (importer != NULL)
1537 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1540 return NULL;
1541 }
1542 PyErr_Clear();
1543 }
1544 if (importer == NULL) {
1545 importer = PyObject_CallFunctionObjArgs(
1546 (PyObject *)&PyNullImporter_Type, p, NULL
1547 );
1548 if (importer == NULL) {
1549 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1550 PyErr_Clear();
1551 return Py_None;
1552 }
1553 }
1554 }
1555 if (importer != NULL) {
1556 int err = PyDict_SetItem(path_importer_cache, p, importer);
1557 Py_DECREF(importer);
1558 if (err != 0)
1559 return NULL;
1560 }
1561 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001562}
1563
Christian Heimes9cd17752007-11-18 19:35:23 +00001564PyAPI_FUNC(PyObject *)
1565PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1569 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1570 importer = get_path_importer(path_importer_cache,
1571 path_hooks, path);
1572 }
1573 }
1574 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1575 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001576}
1577
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001578/* Search the path (default sys.path) for a module. Return the
1579 corresponding filedescr struct, and (via return arguments) the
1580 pathname and an open file. Return NULL if the module is not found. */
1581
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001582#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001583extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001585#endif
1586
Martin v. Löwis18e16552006-02-15 17:27:45 +00001587static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001588static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001589static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001590
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001591static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001592find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 Py_ssize_t i, npath;
1596 size_t len, namelen;
1597 struct filedescr *fdp = NULL;
1598 char *filemode;
1599 FILE *fp = NULL;
1600 PyObject *path_hooks, *path_importer_cache;
1601 struct stat statbuf;
1602 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1603 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1604 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Gregory P. Smithc809f982012-03-18 16:06:53 -07001605 char *name;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001606#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 size_t saved_len;
1608 size_t saved_namelen;
1609 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001610#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 if (p_loader != NULL)
1612 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (strlen(subname) > MAXPATHLEN) {
1615 PyErr_SetString(PyExc_OverflowError,
1616 "module name is too long");
1617 return NULL;
1618 }
Gregory P. Smithc809f982012-03-18 16:06:53 -07001619 name = PyMem_MALLOC(MAXPATHLEN+1);
1620 if (name == NULL) {
1621 PyErr_NoMemory();
1622 return NULL;
1623 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* sys.meta_path import hook */
1627 if (p_loader != NULL) {
1628 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 meta_path = PySys_GetObject("meta_path");
1631 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02001632 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 "sys.meta_path must be a list of "
1634 "import hooks");
Gregory P. Smithc809f982012-03-18 16:06:53 -07001635 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 }
1637 Py_INCREF(meta_path); /* zap guard */
1638 npath = PyList_Size(meta_path);
1639 for (i = 0; i < npath; i++) {
1640 PyObject *loader;
1641 PyObject *hook = PyList_GetItem(meta_path, i);
1642 loader = PyObject_CallMethod(hook, "find_module",
1643 "sO", fullname,
1644 path != NULL ?
1645 path : Py_None);
1646 if (loader == NULL) {
1647 Py_DECREF(meta_path);
Gregory P. Smithc809f982012-03-18 16:06:53 -07001648 goto error_exit; /* true error */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 }
1650 if (loader != Py_None) {
1651 /* a loader was found */
1652 *p_loader = loader;
1653 Py_DECREF(meta_path);
Gregory P. Smithc809f982012-03-18 16:06:53 -07001654 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 return &importhookdescr;
1656 }
1657 Py_DECREF(loader);
1658 }
1659 Py_DECREF(meta_path);
1660 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (find_frozen(fullname) != NULL) {
1663 strcpy(buf, fullname);
Gregory P. Smithc809f982012-03-18 16:06:53 -07001664 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 return &fd_frozen;
1666 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (path == NULL) {
1669 if (is_builtin(name)) {
1670 strcpy(buf, name);
Gregory P. Smithc809f982012-03-18 16:06:53 -07001671 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 return &fd_builtin;
1673 }
Guido van Rossumac279101996-08-22 23:10:58 +00001674#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1676 if (fp != NULL) {
1677 *p_fp = fp;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001678 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 return fdp;
1680 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001681#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 path = PySys_GetObject("path");
1683 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (path == NULL || !PyList_Check(path)) {
Victor Stinner16191322011-09-15 19:28:05 +02001686 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 "sys.path must be a list of directory names");
Gregory P. Smithc809f982012-03-18 16:06:53 -07001688 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 path_hooks = PySys_GetObject("path_hooks");
1692 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02001693 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 "sys.path_hooks must be a list of "
1695 "import hooks");
Gregory P. Smithc809f982012-03-18 16:06:53 -07001696 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 }
1698 path_importer_cache = PySys_GetObject("path_importer_cache");
1699 if (path_importer_cache == NULL ||
1700 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02001701 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 "sys.path_importer_cache must be a dict");
Gregory P. Smithc809f982012-03-18 16:06:53 -07001703 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 npath = PyList_Size(path);
1707 namelen = strlen(name);
1708 for (i = 0; i < npath; i++) {
1709 PyObject *v = PyList_GetItem(path, i);
1710 PyObject *origv = v;
1711 const char *base;
1712 Py_ssize_t size;
1713 if (!v)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001714 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001716 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (v == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001718 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 }
1720 else if (!PyBytes_Check(v))
1721 continue;
1722 else
1723 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 base = PyBytes_AS_STRING(v);
1726 size = PyBytes_GET_SIZE(v);
1727 len = size;
1728 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1729 Py_DECREF(v);
1730 continue; /* Too long */
1731 }
1732 strcpy(buf, base);
1733 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (strlen(buf) != len) {
1736 continue; /* v contains '\0' */
1737 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* sys.path_hooks import hook */
1740 if (p_loader != NULL) {
1741 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 importer = get_path_importer(path_importer_cache,
1744 path_hooks, origv);
1745 if (importer == NULL) {
Gregory P. Smithc809f982012-03-18 16:06:53 -07001746 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 }
1748 /* Note: importer is a borrowed reference */
1749 if (importer != Py_None) {
1750 PyObject *loader;
1751 loader = PyObject_CallMethod(importer,
1752 "find_module",
1753 "s", fullname);
1754 if (loader == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001755 goto error_exit; /* error */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (loader != Py_None) {
1757 /* a loader was found */
1758 *p_loader = loader;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001759 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 return &importhookdescr;
1761 }
1762 Py_DECREF(loader);
1763 continue;
1764 }
1765 }
1766 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001769#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001771#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 )
1773 buf[len++] = SEP;
1774 strcpy(buf+len, name);
1775 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /* Check for package import (buf holds a directory name,
1778 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001779#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (stat(buf, &statbuf) == 0 && /* it exists */
1781 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1782 case_ok(buf, len, namelen, name)) { /* case matches */
1783 if (find_init_module(buf)) { /* and has __init__.py */
Gregory P. Smithc809f982012-03-18 16:06:53 -07001784 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 return &fd_package;
1786 }
1787 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001788 int err;
1789 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1790 if (unicode == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001791 goto error_exit;
Victor Stinnered7916d2010-10-17 02:07:09 +00001792 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1793 "Not importing directory '%U': missing __init__.py",
1794 unicode);
1795 Py_DECREF(unicode);
1796 if (err)
Gregory P. Smithc809f982012-03-18 16:06:53 -07001797 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 }
1799 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001800#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001801#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* take a snapshot of the module spec for restoration
1803 * after the 8 character DLL hackery
1804 */
1805 saved_buf = strdup(buf);
1806 saved_len = len;
1807 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001808#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinner53ffdc52011-09-23 18:54:40 +02001810 struct stat statbuf;
Guido van Rossum04110fb2007-08-24 16:32:05 +00001811#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* OS/2 limits DLLs to 8 character names (w/o
1813 extension)
1814 * so if the name is longer than that and its a
1815 * dynamically loaded module we're going to try,
1816 * truncate the name before trying
1817 */
1818 if (strlen(subname) > 8) {
1819 /* is this an attempt to load a C extension? */
1820 const struct filedescr *scan;
1821 scan = _PyImport_DynLoadFiletab;
1822 while (scan->suffix != NULL) {
1823 if (!strcmp(scan->suffix, fdp->suffix))
1824 break;
1825 else
1826 scan++;
1827 }
1828 if (scan->suffix != NULL) {
1829 /* yes, so truncate the name */
1830 namelen = 8;
1831 len -= strlen(subname) - namelen;
1832 buf[len] = '\0';
1833 }
1834 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001835#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 strcpy(buf+len, fdp->suffix);
1837 if (Py_VerboseFlag > 1)
1838 PySys_WriteStderr("# trying %s\n", buf);
Victor Stinner53ffdc52011-09-23 18:54:40 +02001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 filemode = fdp->mode;
1841 if (filemode[0] == 'U')
1842 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinner53ffdc52011-09-23 18:54:40 +02001843
1844 if (stat(buf, &statbuf) == 0 && S_ISDIR(statbuf.st_mode))
1845 /* it's a directory */
1846 fp = NULL;
1847 else
1848 fp = fopen(buf, filemode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (fp != NULL) {
1850 if (case_ok(buf, len, namelen, name))
1851 break;
1852 else { /* continue search */
1853 fclose(fp);
1854 fp = NULL;
1855 }
1856 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001857#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* restore the saved snapshot */
1859 strcpy(buf, saved_buf);
1860 len = saved_len;
1861 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001864#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* don't need/want the module name snapshot anymore */
1866 if (saved_buf)
1867 {
1868 free(saved_buf);
1869 saved_buf = NULL;
1870 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001871#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (fp != NULL)
1873 break;
1874 }
1875 if (fp == NULL) {
1876 PyErr_Format(PyExc_ImportError,
1877 "No module named %.200s", name);
Gregory P. Smithc809f982012-03-18 16:06:53 -07001878 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 }
1880 *p_fp = fp;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001881 PyMem_FREE(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 return fdp;
Gregory P. Smithc809f982012-03-18 16:06:53 -07001883
1884error_exit:
1885 PyMem_FREE(name);
1886 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001887}
1888
Martin v. Löwis18e16552006-02-15 17:27:45 +00001889/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001890 * The arguments here are tricky, best shown by example:
1891 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1892 * ^ ^ ^ ^
1893 * |--------------------- buf ---------------------|
1894 * |------------------- len ------------------|
1895 * |------ name -------|
1896 * |----- namelen -----|
1897 * buf is the full path, but len only counts up to (& exclusive of) the
1898 * extension. name is the module name, also exclusive of extension.
1899 *
1900 * We've already done a successful stat() or fopen() on buf, so know that
1901 * there's some match, possibly case-insensitive.
1902 *
Tim Peters50d8d372001-02-28 05:34:27 +00001903 * case_ok() is to return 1 if there's a case-sensitive match for
1904 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1905 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001906 *
Tim Peters50d8d372001-02-28 05:34:27 +00001907 * case_ok() is used to implement case-sensitive import semantics even
1908 * on platforms with case-insensitive filesystems. It's trivial to implement
1909 * for case-sensitive filesystems. It's pretty much a cross-platform
1910 * nightmare for systems with case-insensitive filesystems.
1911 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001912
Tim Peters50d8d372001-02-28 05:34:27 +00001913/* First we may need a pile of platform-specific header files; the sequence
1914 * of #if's here should match the sequence in the body of case_ok().
1915 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001916#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001917#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001918
Tim Peters50d8d372001-02-28 05:34:27 +00001919#elif defined(DJGPP)
1920#include <dir.h>
1921
Jason Tishler7961aa62005-05-20 00:56:54 +00001922#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001923#include <sys/types.h>
1924#include <dirent.h>
1925
Andrew MacIntyred9400542002-02-26 11:41:34 +00001926#elif defined(PYOS_OS2)
1927#define INCL_DOS
1928#define INCL_DOSERRORS
1929#define INCL_NOPMAPI
1930#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001931#endif
1932
Guido van Rossum0980bd91998-02-13 17:18:36 +00001933static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001934case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001935{
Tim Peters50d8d372001-02-28 05:34:27 +00001936/* Pick a platform-specific implementation; the sequence of #if's here should
1937 * match the sequence just above.
1938 */
1939
Jason Tishler7961aa62005-05-20 00:56:54 +00001940/* MS_WINDOWS */
1941#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 WIN32_FIND_DATA data;
1943 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (Py_GETENV("PYTHONCASEOK") != NULL)
1946 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 h = FindFirstFile(buf, &data);
1949 if (h == INVALID_HANDLE_VALUE) {
1950 PyErr_Format(PyExc_NameError,
1951 "Can't find file for module %.100s\n(filename %.300s)",
1952 name, buf);
1953 return 0;
1954 }
1955 FindClose(h);
1956 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001957
1958/* DJGPP */
1959#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 struct ffblk ffblk;
1961 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (Py_GETENV("PYTHONCASEOK") != NULL)
1964 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1967 if (done) {
1968 PyErr_Format(PyExc_NameError,
1969 "Can't find file for module %.100s\n(filename %.300s)",
1970 name, buf);
1971 return 0;
1972 }
1973 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001974
Jason Tishler7961aa62005-05-20 00:56:54 +00001975/* new-fangled macintosh (macosx) or Cygwin */
1976#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 DIR *dirp;
1978 struct dirent *dp;
1979 char dirname[MAXPATHLEN + 1];
1980 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (Py_GETENV("PYTHONCASEOK") != NULL)
1983 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 /* Copy the dir component into dirname; substitute "." if empty */
1986 if (dirlen <= 0) {
1987 dirname[0] = '.';
1988 dirname[1] = '\0';
1989 }
1990 else {
1991 assert(dirlen <= MAXPATHLEN);
1992 memcpy(dirname, buf, dirlen);
1993 dirname[dirlen] = '\0';
1994 }
1995 /* Open the directory and search the entries for an exact match. */
1996 dirp = opendir(dirname);
1997 if (dirp) {
1998 char *nameWithExt = buf + len - namelen;
1999 while ((dp = readdir(dirp)) != NULL) {
2000 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002001#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002003#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002005#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (thislen >= namelen &&
2007 strcmp(dp->d_name, nameWithExt) == 0) {
2008 (void)closedir(dirp);
2009 return 1; /* Found */
2010 }
2011 }
2012 (void)closedir(dirp);
2013 }
2014 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002015
Andrew MacIntyred9400542002-02-26 11:41:34 +00002016/* OS/2 */
2017#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 HDIR hdir = 1;
2019 ULONG srchcnt = 1;
2020 FILEFINDBUF3 ffbuf;
2021 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (Py_GETENV("PYTHONCASEOK") != NULL)
2024 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 rc = DosFindFirst(buf,
2027 &hdir,
2028 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2029 &ffbuf, sizeof(ffbuf),
2030 &srchcnt,
2031 FIL_STANDARD);
2032 if (rc != NO_ERROR)
2033 return 0;
2034 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002035
Tim Peters50d8d372001-02-28 05:34:27 +00002036/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2037#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002039
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002040#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002041}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002042
Guido van Rossum197346f1997-10-31 18:38:52 +00002043#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002044
Guido van Rossum197346f1997-10-31 18:38:52 +00002045/* Helper to look for __init__.py or __init__.py[co] in potential package */
2046static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002047find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 const size_t save_len = strlen(buf);
2050 size_t i = save_len;
2051 char *pname; /* pointer to start of __init__ */
2052 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054/* For calling case_ok(buf, len, namelen, name):
2055 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2056 * ^ ^ ^ ^
2057 * |--------------------- buf ---------------------|
2058 * |------------------- len ------------------|
2059 * |------ name -------|
2060 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002061 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (save_len + 13 >= MAXPATHLEN)
2063 return 0;
2064 buf[i++] = SEP;
2065 pname = buf + i;
2066 strcpy(pname, "__init__.py");
2067 if (stat(buf, &statbuf) == 0) {
2068 if (case_ok(buf,
2069 save_len + 9, /* len("/__init__") */
2070 8, /* len("__init__") */
2071 pname)) {
2072 buf[save_len] = '\0';
2073 return 1;
2074 }
2075 }
2076 i += strlen(pname);
2077 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2078 if (stat(buf, &statbuf) == 0) {
2079 if (case_ok(buf,
2080 save_len + 9, /* len("/__init__") */
2081 8, /* len("__init__") */
2082 pname)) {
2083 buf[save_len] = '\0';
2084 return 1;
2085 }
2086 }
2087 buf[save_len] = '\0';
2088 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002089}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002090
Guido van Rossum197346f1997-10-31 18:38:52 +00002091#endif /* HAVE_STAT */
2092
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002093
Tim Petersdbd9ba62000-07-09 03:09:57 +00002094static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002095
Victor Stinner44c6c152010-08-09 00:59:10 +00002096static PyObject*
2097load_builtin(char *name, char *pathname, int type)
2098{
2099 PyObject *m, *modules;
2100 int err;
2101
2102 if (pathname != NULL && pathname[0] != '\0')
2103 name = pathname;
2104
2105 if (type == C_BUILTIN)
2106 err = init_builtin(name);
2107 else
2108 err = PyImport_ImportFrozenModule(name);
2109 if (err < 0)
2110 return NULL;
2111 if (err == 0) {
2112 PyErr_Format(PyExc_ImportError,
2113 "Purported %s module %.200s not found",
2114 type == C_BUILTIN ?
2115 "builtin" : "frozen",
2116 name);
2117 return NULL;
2118 }
2119
2120 modules = PyImport_GetModuleDict();
2121 m = PyDict_GetItemString(modules, name);
2122 if (m == NULL) {
2123 PyErr_Format(
2124 PyExc_ImportError,
2125 "%s module %.200s not properly initialized",
2126 type == C_BUILTIN ?
2127 "builtin" : "frozen",
2128 name);
2129 return NULL;
2130 }
2131 Py_INCREF(m);
2132 return m;
2133}
2134
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002135/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002136 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002137
Guido van Rossum79f25d91997-04-29 20:08:16 +00002138static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002139load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* First check that there's an open file (if we need one) */
2144 switch (type) {
2145 case PY_SOURCE:
2146 case PY_COMPILED:
2147 if (fp == NULL) {
2148 PyErr_Format(PyExc_ValueError,
2149 "file object required for import (type code %d)",
2150 type);
2151 return NULL;
2152 }
2153 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 case PY_SOURCE:
2158 m = load_source_module(name, pathname, fp);
2159 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 case PY_COMPILED:
2162 m = load_compiled_module(name, pathname, fp);
2163 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002164
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002165#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 case C_EXTENSION:
2167 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2168 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002169#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 case PKG_DIRECTORY:
2172 m = load_package(name, pathname);
2173 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 case C_BUILTIN:
2176 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002177 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 case IMP_HOOK: {
2181 if (loader == NULL) {
2182 PyErr_SetString(PyExc_ImportError,
2183 "import hook without loader");
2184 return NULL;
2185 }
2186 m = PyObject_CallMethod(loader, "load_module", "s", name);
2187 break;
2188 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 default:
2191 PyErr_Format(PyExc_ImportError,
2192 "Don't know how to import %.200s (type code %d)",
2193 name, type);
2194 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002199}
2200
2201
2202/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002203 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002204 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002205
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002206static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002207init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002210
Victor Stinner49d3f252010-10-17 01:24:53 +00002211 if (_PyImport_FindBuiltin(name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 for (p = PyImport_Inittab; p->name != NULL; p++) {
2215 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002216 PyModuleDef *def;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (strcmp(name, p->name) == 0) {
2218 if (p->initfunc == NULL) {
2219 PyErr_Format(PyExc_ImportError,
2220 "Cannot re-init internal module %.200s",
2221 name);
2222 return -1;
2223 }
2224 if (Py_VerboseFlag)
2225 PySys_WriteStderr("import %s # builtin\n", name);
2226 mod = (*p->initfunc)();
2227 if (mod == 0)
2228 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002229 /* Remember pointer to module init function. */
2230 def = PyModule_GetDef(mod);
2231 def->m_base.m_init = p->initfunc;
Victor Stinner49d3f252010-10-17 01:24:53 +00002232 if (_PyImport_FixupBuiltin(mod, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 return -1;
2234 /* FixupExtension has put the module into sys.modules,
2235 so we can release our own reference. */
2236 Py_DECREF(mod);
2237 return 1;
2238 }
2239 }
2240 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002241}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002242
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002243
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002244/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002245
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002246static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002247find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 if (!name)
2252 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 for (p = PyImport_FrozenModules; ; p++) {
2255 if (p->name == NULL)
2256 return NULL;
2257 if (strcmp(p->name, name) == 0)
2258 break;
2259 }
2260 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002261}
2262
Guido van Rossum79f25d91997-04-29 20:08:16 +00002263static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002264get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 struct _frozen *p = find_frozen(name);
2267 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 if (p == NULL) {
2270 PyErr_Format(PyExc_ImportError,
2271 "No such frozen object named %.200s",
2272 name);
2273 return NULL;
2274 }
2275 if (p->code == NULL) {
2276 PyErr_Format(PyExc_ImportError,
2277 "Excluded frozen object named %.200s",
2278 name);
2279 return NULL;
2280 }
2281 size = p->size;
2282 if (size < 0)
2283 size = -size;
2284 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002285}
2286
Brett Cannon8d110132009-03-15 02:20:16 +00002287static PyObject *
2288is_frozen_package(char *name)
2289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 struct _frozen *p = find_frozen(name);
2291 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 if (p == NULL) {
2294 PyErr_Format(PyExc_ImportError,
2295 "No such frozen object named %.200s",
2296 name);
2297 return NULL;
2298 }
Brett Cannon8d110132009-03-15 02:20:16 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (size < 0)
2303 Py_RETURN_TRUE;
2304 else
2305 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002306}
2307
2308
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002309/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002310 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002311 an exception set if the initialization failed.
2312 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002313
2314int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002315PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 struct _frozen *p = find_frozen(name);
2318 PyObject *co;
2319 PyObject *m;
2320 int ispackage;
2321 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (p == NULL)
2324 return 0;
2325 if (p->code == NULL) {
2326 PyErr_Format(PyExc_ImportError,
2327 "Excluded frozen object named %.200s",
2328 name);
2329 return -1;
2330 }
2331 size = p->size;
2332 ispackage = (size < 0);
2333 if (ispackage)
2334 size = -size;
2335 if (Py_VerboseFlag)
2336 PySys_WriteStderr("import %s # frozen%s\n",
2337 name, ispackage ? " package" : "");
2338 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2339 if (co == NULL)
2340 return -1;
2341 if (!PyCode_Check(co)) {
2342 PyErr_Format(PyExc_TypeError,
2343 "frozen object %.200s is not a code object",
2344 name);
2345 goto err_return;
2346 }
2347 if (ispackage) {
2348 /* Set __path__ to the package name */
2349 PyObject *d, *s, *l;
2350 int err;
2351 m = PyImport_AddModule(name);
2352 if (m == NULL)
2353 goto err_return;
2354 d = PyModule_GetDict(m);
2355 s = PyUnicode_InternFromString(name);
2356 if (s == NULL)
2357 goto err_return;
2358 l = PyList_New(1);
2359 if (l == NULL) {
2360 Py_DECREF(s);
2361 goto err_return;
2362 }
2363 PyList_SET_ITEM(l, 0, s);
2364 err = PyDict_SetItemString(d, "__path__", l);
2365 Py_DECREF(l);
2366 if (err != 0)
2367 goto err_return;
2368 }
2369 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2370 if (m == NULL)
2371 goto err_return;
2372 Py_DECREF(co);
2373 Py_DECREF(m);
2374 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002375err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Py_DECREF(co);
2377 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002378}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002379
2380
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002381/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002382 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002383
Guido van Rossum79f25d91997-04-29 20:08:16 +00002384PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002385PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 PyObject *pname;
2388 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 pname = PyUnicode_FromString(name);
2391 if (pname == NULL)
2392 return NULL;
2393 result = PyImport_Import(pname);
2394 Py_DECREF(pname);
2395 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002396}
2397
Christian Heimes072c0f12008-01-03 23:01:04 +00002398/* Import a module without blocking
2399 *
2400 * At first it tries to fetch the module from sys.modules. If the module was
2401 * never loaded before it loads it with PyImport_ImportModule() unless another
2402 * thread holds the import lock. In the latter case the function raises an
2403 * ImportError instead of blocking.
2404 *
2405 * Returns the module object with incremented ref count.
2406 */
2407PyObject *
2408PyImport_ImportModuleNoBlock(const char *name)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 PyObject *result;
2411 PyObject *modules;
Victor Stinner0af03062011-09-02 00:11:43 +02002412#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002414#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* Try to get the module from sys.modules[name] */
2417 modules = PyImport_GetModuleDict();
2418 if (modules == NULL)
2419 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 result = PyDict_GetItemString(modules, name);
2422 if (result != NULL) {
2423 Py_INCREF(result);
2424 return result;
2425 }
2426 else {
2427 PyErr_Clear();
2428 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002429#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 /* check the import lock
2431 * me might be -1 but I ignore the error here, the lock function
2432 * takes care of the problem */
2433 me = PyThread_get_thread_ident();
2434 if (import_lock_thread == -1 || import_lock_thread == me) {
2435 /* no thread or me is holding the lock */
2436 return PyImport_ImportModule(name);
2437 }
2438 else {
2439 PyErr_Format(PyExc_ImportError,
2440 "Failed to import %.200s because the import lock"
2441 "is held by another thread.",
2442 name);
2443 return NULL;
2444 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002445#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002447#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002448}
2449
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002450/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002451static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002453static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002455static int mark_miss(char *name);
2456static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002458static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002459
2460/* The Magnum Opus of dotted-name import :-) */
2461
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002462static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002463import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002465{
Gregory P. Smithc809f982012-03-18 16:06:53 -07002466 char *buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 Py_ssize_t buflen = 0;
2468 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002471#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002473#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 ) {
2475 PyErr_SetString(PyExc_ImportError,
2476 "Import by filename is not supported.");
2477 return NULL;
2478 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002479
Gregory P. Smithc809f982012-03-18 16:06:53 -07002480 buf = PyMem_MALLOC(MAXPATHLEN+1);
2481 if (buf == NULL) {
2482 return PyErr_NoMemory();
2483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 parent = get_parent(globals, buf, &buflen, level);
2485 if (parent == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07002486 goto error_exit;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002487
Benjamin Peterson556d8002010-06-27 22:37:28 +00002488 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2489 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 if (head == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07002491 goto error_exit;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 tail = head;
2494 Py_INCREF(tail);
2495 while (name) {
2496 next = load_next(tail, tail, &name, buf, &buflen);
2497 Py_DECREF(tail);
2498 if (next == NULL) {
2499 Py_DECREF(head);
Gregory P. Smithc809f982012-03-18 16:06:53 -07002500 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 }
2502 tail = next;
2503 }
2504 if (tail == Py_None) {
2505 /* If tail is Py_None, both get_parent and load_next found
2506 an empty module name: someone called __import__("") or
2507 doctored faulty bytecode */
2508 Py_DECREF(tail);
2509 Py_DECREF(head);
2510 PyErr_SetString(PyExc_ValueError,
2511 "Empty module name");
Gregory P. Smithc809f982012-03-18 16:06:53 -07002512 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 if (fromlist != NULL) {
Antoine Pitrou6f430e42012-08-15 23:18:25 +02002516 int b = (fromlist == Py_None) ? 0 : PyObject_IsTrue(fromlist);
2517 if (b < 0) {
2518 Py_DECREF(tail);
2519 Py_DECREF(head);
2520 goto error_exit;
2521 }
2522 if (!b)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 fromlist = NULL;
2524 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 if (fromlist == NULL) {
2527 Py_DECREF(tail);
Gregory P. Smithc809f982012-03-18 16:06:53 -07002528 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 return head;
2530 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 Py_DECREF(head);
2533 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2534 Py_DECREF(tail);
Gregory P. Smithc809f982012-03-18 16:06:53 -07002535 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002537
Gregory P. Smithc809f982012-03-18 16:06:53 -07002538 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return tail;
Gregory P. Smithc809f982012-03-18 16:06:53 -07002540
2541error_exit:
2542 PyMem_FREE(buf);
2543 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002544}
2545
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002546PyObject *
2547PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 PyObject *result;
2551 _PyImport_AcquireLock();
2552 result = import_module_level(name, globals, locals, fromlist, level);
2553 if (_PyImport_ReleaseLock() < 0) {
2554 Py_XDECREF(result);
2555 PyErr_SetString(PyExc_RuntimeError,
2556 "not holding the import lock");
2557 return NULL;
2558 }
2559 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002560}
2561
Fred Drake87590902004-05-28 20:21:36 +00002562/* Return the package that an import is being performed in. If globals comes
2563 from the module foo.bar.bat (not itself a package), this returns the
2564 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002565 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002566
2567 The *name* of the returned package is returned in buf, with the length of
2568 the name in *p_buflen.
2569
2570 If globals doesn't come from a package or a module in a package, or a
2571 corresponding entry is not found in sys.modules, Py_None is returned.
2572*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002573static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002574get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 static PyObject *namestr = NULL;
2577 static PyObject *pathstr = NULL;
2578 static PyObject *pkgstr = NULL;
2579 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2580 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 if (globals == NULL || !PyDict_Check(globals) || !level)
2583 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 if (namestr == NULL) {
2586 namestr = PyUnicode_InternFromString("__name__");
2587 if (namestr == NULL)
2588 return NULL;
2589 }
2590 if (pathstr == NULL) {
2591 pathstr = PyUnicode_InternFromString("__path__");
2592 if (pathstr == NULL)
2593 return NULL;
2594 }
2595 if (pkgstr == NULL) {
2596 pkgstr = PyUnicode_InternFromString("__package__");
2597 if (pkgstr == NULL)
2598 return NULL;
2599 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 *buf = '\0';
2602 *p_buflen = 0;
2603 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if ((pkgname != NULL) && (pkgname != Py_None)) {
2606 /* __package__ is set, so use it */
2607 char *pkgname_str;
2608 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 if (!PyUnicode_Check(pkgname)) {
2611 PyErr_SetString(PyExc_ValueError,
2612 "__package__ set to non-string");
2613 return NULL;
2614 }
2615 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2616 if (len == 0) {
2617 if (level > 0) {
2618 PyErr_SetString(PyExc_ValueError,
2619 "Attempted relative import in non-package");
2620 return NULL;
2621 }
2622 return Py_None;
2623 }
2624 if (len > MAXPATHLEN) {
2625 PyErr_SetString(PyExc_ValueError,
2626 "Package name too long");
2627 return NULL;
2628 }
2629 strcpy(buf, pkgname_str);
2630 } else {
2631 /* __package__ not set, so figure it out and set it */
2632 modname = PyDict_GetItem(globals, namestr);
2633 if (modname == NULL || !PyUnicode_Check(modname))
2634 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 modpath = PyDict_GetItem(globals, pathstr);
2637 if (modpath != NULL) {
2638 /* __path__ is set, so modname is already the package name */
2639 char *modname_str;
2640 Py_ssize_t len;
2641 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2644 if (len > MAXPATHLEN) {
2645 PyErr_SetString(PyExc_ValueError,
2646 "Module name too long");
2647 return NULL;
2648 }
2649 strcpy(buf, modname_str);
2650 error = PyDict_SetItem(globals, pkgstr, modname);
2651 if (error) {
2652 PyErr_SetString(PyExc_ValueError,
2653 "Could not set __package__");
2654 return NULL;
2655 }
2656 } else {
2657 /* Normal module, so work out the package name if any */
2658 char *start = _PyUnicode_AsString(modname);
2659 char *lastdot = strrchr(start, '.');
2660 size_t len;
2661 int error;
2662 if (lastdot == NULL && level > 0) {
2663 PyErr_SetString(PyExc_ValueError,
2664 "Attempted relative import in non-package");
2665 return NULL;
2666 }
2667 if (lastdot == NULL) {
2668 error = PyDict_SetItem(globals, pkgstr, Py_None);
2669 if (error) {
2670 PyErr_SetString(PyExc_ValueError,
2671 "Could not set __package__");
2672 return NULL;
2673 }
2674 return Py_None;
2675 }
2676 len = lastdot - start;
2677 if (len >= MAXPATHLEN) {
2678 PyErr_SetString(PyExc_ValueError,
2679 "Module name too long");
2680 return NULL;
2681 }
2682 strncpy(buf, start, len);
2683 buf[len] = '\0';
2684 pkgname = PyUnicode_FromString(buf);
2685 if (pkgname == NULL) {
2686 return NULL;
2687 }
2688 error = PyDict_SetItem(globals, pkgstr, pkgname);
2689 Py_DECREF(pkgname);
2690 if (error) {
2691 PyErr_SetString(PyExc_ValueError,
2692 "Could not set __package__");
2693 return NULL;
2694 }
2695 }
2696 }
2697 while (--level > 0) {
2698 char *dot = strrchr(buf, '.');
2699 if (dot == NULL) {
2700 PyErr_SetString(PyExc_ValueError,
2701 "Attempted relative import beyond "
2702 "toplevel package");
2703 return NULL;
2704 }
2705 *dot = '\0';
2706 }
2707 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 modules = PyImport_GetModuleDict();
2710 parent = PyDict_GetItemString(modules, buf);
2711 if (parent == NULL) {
2712 if (orig_level < 1) {
2713 PyObject *err_msg = PyBytes_FromFormat(
2714 "Parent module '%.200s' not found "
2715 "while handling absolute import", buf);
2716 if (err_msg == NULL) {
2717 return NULL;
2718 }
2719 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2720 PyBytes_AsString(err_msg), 1)) {
2721 *buf = '\0';
2722 *p_buflen = 0;
2723 parent = Py_None;
2724 }
2725 Py_DECREF(err_msg);
2726 } else {
2727 PyErr_Format(PyExc_SystemError,
2728 "Parent module '%.200s' not loaded, "
2729 "cannot perform relative import", buf);
2730 }
2731 }
2732 return parent;
2733 /* We expect, but can't guarantee, if parent != None, that:
2734 - parent.__name__ == buf
2735 - parent.__dict__ is globals
2736 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002737}
2738
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002739/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002740static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002741load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 char *name = *p_name;
2745 char *dot = strchr(name, '.');
2746 size_t len;
2747 char *p;
2748 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 if (strlen(name) == 0) {
2751 /* completely empty module name should only happen in
2752 'from . import' (or '__import__("")')*/
2753 Py_INCREF(mod);
2754 *p_name = NULL;
2755 return mod;
2756 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 if (dot == NULL) {
2759 *p_name = NULL;
2760 len = strlen(name);
2761 }
2762 else {
2763 *p_name = dot+1;
2764 len = dot-name;
2765 }
2766 if (len == 0) {
2767 PyErr_SetString(PyExc_ValueError,
2768 "Empty module name");
2769 return NULL;
2770 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 p = buf + *p_buflen;
2773 if (p != buf)
2774 *p++ = '.';
2775 if (p+len-buf >= MAXPATHLEN) {
2776 PyErr_SetString(PyExc_ValueError,
2777 "Module name too long");
2778 return NULL;
2779 }
2780 strncpy(p, name, len);
2781 p[len] = '\0';
2782 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 result = import_submodule(mod, p, buf);
2785 if (result == Py_None && altmod != mod) {
2786 Py_DECREF(result);
2787 /* Here, altmod must be None and mod must not be None */
2788 result = import_submodule(altmod, p, p);
2789 if (result != NULL && result != Py_None) {
2790 if (mark_miss(buf) != 0) {
2791 Py_DECREF(result);
2792 return NULL;
2793 }
2794 strncpy(buf, name, len);
2795 buf[len] = '\0';
2796 *p_buflen = len;
2797 }
2798 }
2799 if (result == NULL)
2800 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 if (result == Py_None) {
2803 Py_DECREF(result);
2804 PyErr_Format(PyExc_ImportError,
2805 "No module named %.200s", name);
2806 return NULL;
2807 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002810}
2811
2812static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002813mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 PyObject *modules = PyImport_GetModuleDict();
2816 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002817}
2818
2819static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002820ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 if (!PyObject_HasAttrString(mod, "__path__"))
2826 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 for (i = 0; ; i++) {
2829 PyObject *item = PySequence_GetItem(fromlist, i);
2830 int hasit;
2831 if (item == NULL) {
2832 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2833 PyErr_Clear();
2834 return 1;
2835 }
2836 return 0;
2837 }
2838 if (!PyUnicode_Check(item)) {
2839 PyErr_SetString(PyExc_TypeError,
2840 "Item in ``from list'' not a string");
2841 Py_DECREF(item);
2842 return 0;
2843 }
2844 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2845 PyObject *all;
2846 Py_DECREF(item);
2847 /* See if the package defines __all__ */
2848 if (recursive)
2849 continue; /* Avoid endless recursion */
2850 all = PyObject_GetAttrString(mod, "__all__");
2851 if (all == NULL)
2852 PyErr_Clear();
2853 else {
2854 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2855 Py_DECREF(all);
2856 if (!ret)
2857 return 0;
2858 }
2859 continue;
2860 }
2861 hasit = PyObject_HasAttr(mod, item);
2862 if (!hasit) {
2863 PyObject *item8;
2864 char *subname;
2865 PyObject *submod;
2866 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002867 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if (!item8) {
2869 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2870 return 0;
2871 }
2872 subname = PyBytes_AS_STRING(item8);
2873 if (buflen + strlen(subname) >= MAXPATHLEN) {
2874 PyErr_SetString(PyExc_ValueError,
2875 "Module name too long");
2876 Py_DECREF(item);
2877 return 0;
2878 }
2879 p = buf + buflen;
2880 *p++ = '.';
2881 strcpy(p, subname);
2882 submod = import_submodule(mod, subname, buf);
2883 Py_DECREF(item8);
2884 Py_XDECREF(submod);
2885 if (submod == NULL) {
2886 Py_DECREF(item);
2887 return 0;
2888 }
2889 }
2890 Py_DECREF(item);
2891 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002894}
2895
Neil Schemenauer00b09662003-06-16 21:03:07 +00002896static int
2897add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 if (mod == Py_None)
2901 return 1;
2902 /* Irrespective of the success of this load, make a
2903 reference to it in the parent package module. A copy gets
2904 saved in the modules dictionary under the full name, so get a
2905 reference from there, if need be. (The exception is when the
2906 load failed with a SyntaxError -- then there's no trace in
2907 sys.modules. In that case, of course, do nothing extra.) */
2908 if (submod == NULL) {
2909 submod = PyDict_GetItemString(modules, fullname);
2910 if (submod == NULL)
2911 return 1;
2912 }
2913 if (PyModule_Check(mod)) {
2914 /* We can't use setattr here since it can give a
2915 * spurious warning if the submodule name shadows a
2916 * builtin name */
2917 PyObject *dict = PyModule_GetDict(mod);
2918 if (!dict)
2919 return 0;
2920 if (PyDict_SetItemString(dict, subname, submod) < 0)
2921 return 0;
2922 }
2923 else {
2924 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2925 return 0;
2926 }
2927 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002928}
2929
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002930static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002931import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 PyObject *modules = PyImport_GetModuleDict();
2934 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 /* Require:
2937 if mod == None: subname == fullname
2938 else: mod.__name__ + "." + subname == fullname
2939 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2942 Py_INCREF(m);
2943 }
2944 else {
2945 PyObject *path, *loader = NULL;
Gregory P. Smithc809f982012-03-18 16:06:53 -07002946 char *buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 struct filedescr *fdp;
2948 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 if (mod == Py_None)
2951 path = NULL;
2952 else {
2953 path = PyObject_GetAttrString(mod, "__path__");
2954 if (path == NULL) {
2955 PyErr_Clear();
2956 Py_INCREF(Py_None);
2957 return Py_None;
2958 }
2959 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002960
Gregory P. Smithc809f982012-03-18 16:06:53 -07002961 buf = PyMem_MALLOC(MAXPATHLEN+1);
2962 if (buf == NULL) {
2963 return PyErr_NoMemory();
2964 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 buf[0] = '\0';
2966 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2967 &fp, &loader);
2968 Py_XDECREF(path);
2969 if (fdp == NULL) {
Gregory P. Smithc809f982012-03-18 16:06:53 -07002970 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2972 return NULL;
2973 PyErr_Clear();
2974 Py_INCREF(Py_None);
2975 return Py_None;
2976 }
2977 m = load_module(fullname, fp, buf, fdp->type, loader);
2978 Py_XDECREF(loader);
2979 if (fp)
2980 fclose(fp);
2981 if (!add_submodule(mod, m, fullname, subname, modules)) {
2982 Py_XDECREF(m);
2983 m = NULL;
2984 }
Gregory P. Smithc809f982012-03-18 16:06:53 -07002985 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002989}
2990
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002991
2992/* Re-import a module of any kind and return its module object, WITH
2993 INCREMENTED REFERENCE COUNT */
2994
Guido van Rossum79f25d91997-04-29 20:08:16 +00002995PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002996PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 PyInterpreterState *interp = PyThreadState_Get()->interp;
2999 PyObject *modules_reloading = interp->modules_reloading;
3000 PyObject *modules = PyImport_GetModuleDict();
3001 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
3002 char *name, *subname;
Gregory P. Smithc809f982012-03-18 16:06:53 -07003003 char *buf;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 struct filedescr *fdp;
3005 FILE *fp = NULL;
3006 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 if (modules_reloading == NULL) {
3009 Py_FatalError("PyImport_ReloadModule: "
3010 "no modules_reloading dictionary!");
3011 return NULL;
3012 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 if (m == NULL || !PyModule_Check(m)) {
3015 PyErr_SetString(PyExc_TypeError,
3016 "reload() argument must be module");
3017 return NULL;
3018 }
3019 name = (char*)PyModule_GetName(m);
3020 if (name == NULL)
3021 return NULL;
3022 if (m != PyDict_GetItemString(modules, name)) {
3023 PyErr_Format(PyExc_ImportError,
3024 "reload(): module %.200s not in sys.modules",
3025 name);
3026 return NULL;
3027 }
3028 existing_m = PyDict_GetItemString(modules_reloading, name);
3029 if (existing_m != NULL) {
3030 /* Due to a recursive reload, this module is already
3031 being reloaded. */
3032 Py_INCREF(existing_m);
3033 return existing_m;
3034 }
3035 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
3036 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 subname = strrchr(name, '.');
3039 if (subname == NULL)
3040 subname = name;
3041 else {
3042 PyObject *parentname, *parent;
3043 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
3044 if (parentname == NULL) {
3045 imp_modules_reloading_clear();
3046 return NULL;
3047 }
3048 parent = PyDict_GetItem(modules, parentname);
3049 if (parent == NULL) {
3050 PyErr_Format(PyExc_ImportError,
3051 "reload(): parent %U not in sys.modules",
3052 parentname);
3053 Py_DECREF(parentname);
3054 imp_modules_reloading_clear();
3055 return NULL;
3056 }
3057 Py_DECREF(parentname);
3058 subname++;
3059 path = PyObject_GetAttrString(parent, "__path__");
3060 if (path == NULL)
3061 PyErr_Clear();
3062 }
Gregory P. Smithc809f982012-03-18 16:06:53 -07003063 buf = PyMem_MALLOC(MAXPATHLEN+1);
3064 if (buf == NULL) {
3065 Py_XDECREF(path);
3066 return PyErr_NoMemory();
3067 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 buf[0] = '\0';
3069 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3070 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 if (fdp == NULL) {
3073 Py_XDECREF(loader);
3074 imp_modules_reloading_clear();
Gregory P. Smithc809f982012-03-18 16:06:53 -07003075 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 return NULL;
3077 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 newm = load_module(name, fp, buf, fdp->type, loader);
3080 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 if (fp)
3083 fclose(fp);
3084 if (newm == NULL) {
3085 /* load_module probably removed name from modules because of
3086 * the error. Put back the original module object. We're
3087 * going to return NULL in this case regardless of whether
3088 * replacing name succeeds, so the return value is ignored.
3089 */
3090 PyDict_SetItemString(modules, name, m);
3091 }
3092 imp_modules_reloading_clear();
Gregory P. Smithc809f982012-03-18 16:06:53 -07003093 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003095}
3096
3097
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003098/* Higher-level import emulator which emulates the "import" statement
3099 more accurately -- it invokes the __import__() function from the
3100 builtins of the current globals. This means that the import is
3101 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003102 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003103 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003104 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003105 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003106
3107PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003108PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 static PyObject *silly_list = NULL;
3111 static PyObject *builtins_str = NULL;
3112 static PyObject *import_str = NULL;
3113 PyObject *globals = NULL;
3114 PyObject *import = NULL;
3115 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003116 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 /* Initialize constant string objects */
3120 if (silly_list == NULL) {
3121 import_str = PyUnicode_InternFromString("__import__");
3122 if (import_str == NULL)
3123 return NULL;
3124 builtins_str = PyUnicode_InternFromString("__builtins__");
3125 if (builtins_str == NULL)
3126 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003127 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 if (silly_list == NULL)
3129 return NULL;
3130 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 /* Get the builtins from current globals */
3133 globals = PyEval_GetGlobals();
3134 if (globals != NULL) {
3135 Py_INCREF(globals);
3136 builtins = PyObject_GetItem(globals, builtins_str);
3137 if (builtins == NULL)
3138 goto err;
3139 }
3140 else {
3141 /* No globals -- use standard builtins, and fake globals */
3142 builtins = PyImport_ImportModuleLevel("builtins",
3143 NULL, NULL, NULL, 0);
3144 if (builtins == NULL)
3145 return NULL;
3146 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3147 if (globals == NULL)
3148 goto err;
3149 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 /* Get the __import__ function from the builtins */
3152 if (PyDict_Check(builtins)) {
3153 import = PyObject_GetItem(builtins, import_str);
3154 if (import == NULL)
3155 PyErr_SetObject(PyExc_KeyError, import_str);
3156 }
3157 else
3158 import = PyObject_GetAttr(builtins, import_str);
3159 if (import == NULL)
3160 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003163 Always use absolute import here.
3164 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3166 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003167 if (r == NULL)
3168 goto err;
3169 Py_DECREF(r);
3170
3171 modules = PyImport_GetModuleDict();
3172 r = PyDict_GetItem(modules, module_name);
3173 if (r != NULL)
3174 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003175
3176 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 Py_XDECREF(globals);
3178 Py_XDECREF(builtins);
3179 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003182}
3183
3184
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003185/* Module 'imp' provides Python access to the primitives used for
3186 importing modules.
3187*/
3188
Guido van Rossum79f25d91997-04-29 20:08:16 +00003189static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003190imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 buf[0] = (char) ((magic >> 0) & 0xff);
3195 buf[1] = (char) ((magic >> 8) & 0xff);
3196 buf[2] = (char) ((magic >> 16) & 0xff);
3197 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003200}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003201
3202static PyObject *
3203imp_get_magic(PyObject *self, PyObject *noargs)
3204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003206}
3207
3208static PyObject *
3209imp_get_tag(PyObject *self, PyObject *noargs)
3210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003212}
3213
Guido van Rossum79f25d91997-04-29 20:08:16 +00003214static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003215imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 PyObject *list;
3218 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 list = PyList_New(0);
3221 if (list == NULL)
3222 return NULL;
3223 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3224 PyObject *item = Py_BuildValue("ssi",
3225 fdp->suffix, fdp->mode, fdp->type);
3226 if (item == NULL) {
3227 Py_DECREF(list);
3228 return NULL;
3229 }
3230 if (PyList_Append(list, item) < 0) {
3231 Py_DECREF(list);
3232 Py_DECREF(item);
3233 return NULL;
3234 }
3235 Py_DECREF(item);
3236 }
3237 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003238}
3239
Guido van Rossum79f25d91997-04-29 20:08:16 +00003240static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003241call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 extern int fclose(FILE *);
3244 PyObject *fob, *ret;
3245 PyObject *pathobj;
3246 struct filedescr *fdp;
Gregory P. Smithc809f982012-03-18 16:06:53 -07003247 char *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 FILE *fp = NULL;
3249 int fd = -1;
3250 char *found_encoding = NULL;
3251 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003252
Gregory P. Smithc809f982012-03-18 16:06:53 -07003253 pathname = PyMem_MALLOC(MAXPATHLEN+1);
3254 if (pathname == NULL) {
3255 return PyErr_NoMemory();
3256 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 pathname[0] = '\0';
3258 if (path == Py_None)
3259 path = NULL;
3260 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3261 if (fdp == NULL)
Gregory P. Smithc809f982012-03-18 16:06:53 -07003262 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 if (fp != NULL) {
3264 fd = fileno(fp);
3265 if (fd != -1)
3266 fd = dup(fd);
3267 fclose(fp);
3268 fp = NULL;
Gregory P. Smithc809f982012-03-18 16:06:53 -07003269 if (fd == -1) {
3270 PyErr_SetFromErrno(PyExc_OSError);
3271 goto error_exit;
3272 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 }
3274 if (fd != -1) {
3275 if (strchr(fdp->mode, 'b') == NULL) {
3276 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3277 memory. */
3278 found_encoding = PyTokenizer_FindEncoding(fd);
3279 lseek(fd, 0, 0); /* Reset position */
Antoine Pitrou4f22a8d2012-02-22 18:05:43 +01003280 if (found_encoding == NULL && PyErr_Occurred()) {
3281 close(fd);
Gregory P. Smithc809f982012-03-18 16:06:53 -07003282 goto error_exit;
Antoine Pitrou4f22a8d2012-02-22 18:05:43 +01003283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 encoding = (found_encoding != NULL) ? found_encoding :
3285 (char*)PyUnicode_GetDefaultEncoding();
3286 }
3287 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3288 (char*)encoding, NULL, NULL, 1);
3289 if (fob == NULL) {
3290 close(fd);
3291 PyMem_FREE(found_encoding);
Gregory P. Smithc809f982012-03-18 16:06:53 -07003292 goto error_exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 }
3294 }
3295 else {
3296 fob = Py_None;
3297 Py_INCREF(fob);
3298 }
3299 pathobj = PyUnicode_DecodeFSDefault(pathname);
3300 ret = Py_BuildValue("NN(ssi)",
3301 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3302 PyMem_FREE(found_encoding);
Gregory P. Smithc809f982012-03-18 16:06:53 -07003303 PyMem_FREE(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 return ret;
Gregory P. Smithc809f982012-03-18 16:06:53 -07003305
3306error_exit:
3307 PyMem_FREE(pathname);
3308 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003309}
3310
Guido van Rossum79f25d91997-04-29 20:08:16 +00003311static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003312imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003313{
Victor Stinnerebc00522010-12-03 17:06:43 +00003314 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 PyObject *ret, *path = NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003316 if (!PyArg_ParseTuple(args, "O&|O:find_module",
3317 PyUnicode_FSConverter, &name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 &path))
3319 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003320 ret = call_find_module(PyBytes_AS_STRING(name), path);
3321 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003323}
3324
3325static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003326imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 char *name;
3329 int ret;
3330 PyObject *m;
3331 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3332 return NULL;
3333 ret = init_builtin(name);
3334 if (ret < 0)
3335 return NULL;
3336 if (ret == 0) {
3337 Py_INCREF(Py_None);
3338 return Py_None;
3339 }
3340 m = PyImport_AddModule(name);
3341 Py_XINCREF(m);
3342 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003343}
3344
Guido van Rossum79f25d91997-04-29 20:08:16 +00003345static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003346imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 char *name;
3349 int ret;
3350 PyObject *m;
3351 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3352 return NULL;
3353 ret = PyImport_ImportFrozenModule(name);
3354 if (ret < 0)
3355 return NULL;
3356 if (ret == 0) {
3357 Py_INCREF(Py_None);
3358 return Py_None;
3359 }
3360 m = PyImport_AddModule(name);
3361 Py_XINCREF(m);
3362 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003363}
3364
Guido van Rossum79f25d91997-04-29 20:08:16 +00003365static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003366imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3371 return NULL;
3372 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003373}
3374
Guido van Rossum79f25d91997-04-29 20:08:16 +00003375static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003376imp_is_frozen_package(PyObject *self, PyObject *args)
3377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3381 return NULL;
3382 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003383}
3384
3385static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003386imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 char *name;
3389 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3390 return NULL;
3391 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003392}
3393
Guido van Rossum79f25d91997-04-29 20:08:16 +00003394static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003395imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 char *name;
3398 struct _frozen *p;
3399 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3400 return NULL;
3401 p = find_frozen(name);
3402 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003403}
3404
3405static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003406get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 FILE *fp;
3409 if (mode[0] == 'U')
3410 mode = "r" PY_STDIOTEXTMODE;
3411 if (fob == NULL) {
3412 fp = fopen(pathname, mode);
3413 }
3414 else {
3415 int fd = PyObject_AsFileDescriptor(fob);
3416 if (fd == -1)
3417 return NULL;
3418 if (!_PyVerify_fd(fd))
3419 goto error;
3420 /* the FILE struct gets a new fd, so that it can be closed
3421 * independently of the file descriptor given
3422 */
3423 fd = dup(fd);
3424 if (fd == -1)
3425 goto error;
3426 fp = fdopen(fd, mode);
3427 }
3428 if (fp)
3429 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003430error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 PyErr_SetFromErrno(PyExc_IOError);
3432 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003433}
3434
Guido van Rossum79f25d91997-04-29 20:08:16 +00003435static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003436imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003439 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 PyObject *fob = NULL;
3441 PyObject *m;
3442 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003443 if (!PyArg_ParseTuple(args, "sO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003445 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 &fob))
3447 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003448 fp = get_file(PyBytes_AS_STRING(pathname), fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003450 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 return NULL;
3452 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003453 m = load_compiled_module(name, PyBytes_AS_STRING(pathname), fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003455 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003457}
3458
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003459#ifdef HAVE_DYNAMIC_LOADING
3460
Guido van Rossum79f25d91997-04-29 20:08:16 +00003461static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003462imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003465 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 char *pathname;
3467 PyObject *fob = NULL;
3468 PyObject *m;
3469 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003470 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3471 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003473 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 if (fob) {
3475 fp = get_file(pathname, fob, "r");
3476 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003477 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 return NULL;
3479 }
3480 }
3481 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003482 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 if (fp)
3484 fclose(fp);
3485 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003486}
3487
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003488#endif /* HAVE_DYNAMIC_LOADING */
3489
Guido van Rossum79f25d91997-04-29 20:08:16 +00003490static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003491imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003494 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 PyObject *fob = NULL;
3496 PyObject *m;
3497 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003498 if (!PyArg_ParseTuple(args, "sO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003500 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 &fob))
3502 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003503 fp = get_file(PyBytes_AS_STRING(pathname), fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003505 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 return NULL;
3507 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003508 m = load_source_module(name, PyBytes_AS_STRING(pathname), fp);
3509 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 fclose(fp);
3511 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003512}
3513
Guido van Rossum79f25d91997-04-29 20:08:16 +00003514static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003515imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 char *name;
3518 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003519 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 PyObject * ret;
3521 char *suffix; /* Unused */
3522 char *mode;
3523 int type;
3524 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003525
Victor Stinner1a563032010-10-15 22:43:10 +00003526 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003528 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 &suffix, &mode, &type))
3530 return NULL;
3531 if (*mode) {
3532 /* Mode must start with 'r' or 'U' and must not contain '+'.
3533 Implicit in this test is the assumption that the mode
3534 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3537 PyErr_Format(PyExc_ValueError,
3538 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003539 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 return NULL;
3541 }
3542 }
3543 if (fob == Py_None)
3544 fp = NULL;
3545 else {
3546 fp = get_file(NULL, fob, mode);
3547 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003548 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 return NULL;
3550 }
3551 }
Victor Stinner1a563032010-10-15 22:43:10 +00003552 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3553 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 if (fp)
3555 fclose(fp);
3556 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003557}
3558
3559static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003560imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003563 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 PyObject * ret;
Victor Stinnerebc00522010-12-03 17:06:43 +00003565 if (!PyArg_ParseTuple(args, "sO&:load_package",
3566 &name, PyUnicode_FSConverter, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003568 ret = load_package(name, PyBytes_AS_STRING(pathname));
3569 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003571}
3572
3573static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003574imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 char *name;
3577 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3578 return NULL;
3579 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003580}
3581
Christian Heimes13a7a212008-01-07 17:13:09 +00003582static PyObject *
3583imp_reload(PyObject *self, PyObject *v)
3584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003586}
3587
3588PyDoc_STRVAR(doc_reload,
3589"reload(module) -> module\n\
3590\n\
3591Reload the module. The module must have been successfully imported before.");
3592
Barry Warsaw28a691b2010-04-17 00:19:56 +00003593static PyObject *
3594imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003597
Gregory P. Smithc809f982012-03-18 16:06:53 -07003598 char *buf;
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003599 PyObject *pathbytes;
3600 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003601 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003605 args, kws, "O&|O", kwlist,
3606 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003608
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003609 if (debug_override != NULL &&
3610 (debug = PyObject_IsTrue(debug_override)) < 0) {
3611 Py_DECREF(pathbytes);
3612 return NULL;
3613 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003614
Gregory P. Smithc809f982012-03-18 16:06:53 -07003615 buf = PyMem_MALLOC(MAXPATHLEN+1);
3616 if (buf == NULL) {
3617 return PyErr_NoMemory();
3618 }
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003619 cpathname = make_compiled_pathname(
3620 PyBytes_AS_STRING(pathbytes),
3621 buf, MAXPATHLEN+1, debug);
3622 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 if (cpathname == NULL) {
3625 PyErr_Format(PyExc_SystemError, "path buffer too short");
Gregory P. Smithc809f982012-03-18 16:06:53 -07003626 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 return NULL;
3628 }
Gregory P. Smithc809f982012-03-18 16:06:53 -07003629 {
3630 PyObject *ret = PyUnicode_DecodeFSDefault(buf);
3631 PyMem_FREE(buf);
3632 return ret;
3633 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003634}
3635
3636PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01003637"cache_from_source(path, [debug_override]) -> path\n\
3638Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003639\n\
3640The .py file does not need to exist; this simply returns the path to the\n\
3641.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3642will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3643\n\
3644If debug_override is not None, then it must be a boolean and is taken as\n\
3645the value of __debug__ instead.");
3646
3647static PyObject *
3648imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003651
Victor Stinnerebc00522010-12-03 17:06:43 +00003652 PyObject *pathname_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 char *pathname;
Gregory P. Smithc809f982012-03-18 16:06:53 -07003654 char *buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003657 args, kws, "O&", kwlist,
3658 PyUnicode_FSConverter, &pathname_obj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003660
Victor Stinnerebc00522010-12-03 17:06:43 +00003661 pathname = PyBytes_AS_STRING(pathname_obj);
Gregory P. Smithc809f982012-03-18 16:06:53 -07003662 buf = PyMem_MALLOC(MAXPATHLEN+1);
3663 if (buf == NULL) {
3664 return PyErr_NoMemory();
3665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 if (make_source_pathname(pathname, buf) == NULL) {
3667 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3668 pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003669 Py_DECREF(pathname_obj);
Gregory P. Smithc809f982012-03-18 16:06:53 -07003670 PyMem_FREE(buf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 return NULL;
3672 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003673 Py_DECREF(pathname_obj);
Gregory P. Smithc809f982012-03-18 16:06:53 -07003674 {
3675 PyObject *ret = PyUnicode_FromString(buf);
3676 PyMem_FREE(buf);
3677 return ret;
3678 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003679}
3680
3681PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01003682"source_from_cache(path) -> path\n\
3683Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003684\n\
3685The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3686the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3687does not conform to PEP 3147 format, ValueError will be raised.");
3688
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003689/* Doc strings */
3690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003691PyDoc_STRVAR(doc_imp,
3692"This module provides the components needed to build your own\n\
3693__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003695PyDoc_STRVAR(doc_find_module,
3696"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003697Search for a module. If path is omitted or None, search for a\n\
3698built-in, frozen or special module and continue search in sys.path.\n\
3699The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003700package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003702PyDoc_STRVAR(doc_load_module,
3703"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003704Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003705The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003707PyDoc_STRVAR(doc_get_magic,
3708"get_magic() -> string\n\
3709Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003710
Barry Warsaw28a691b2010-04-17 00:19:56 +00003711PyDoc_STRVAR(doc_get_tag,
3712"get_tag() -> string\n\
3713Return the magic tag for .pyc or .pyo files.");
3714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003715PyDoc_STRVAR(doc_get_suffixes,
3716"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003717Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003718that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003720PyDoc_STRVAR(doc_new_module,
3721"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003722Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003723The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003725PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003726"lock_held() -> boolean\n\
3727Return True if the import lock is currently held, else False.\n\
3728On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003729
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003730PyDoc_STRVAR(doc_acquire_lock,
3731"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003732Acquires the interpreter's import lock for the current thread.\n\
3733This lock should be used by import hooks to ensure thread-safety\n\
3734when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003735On platforms without threads, this function does nothing.");
3736
3737PyDoc_STRVAR(doc_release_lock,
3738"release_lock() -> None\n\
3739Release the interpreter's import lock.\n\
3740On platforms without threads, this function does nothing.");
3741
Guido van Rossum79f25d91997-04-29 20:08:16 +00003742static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3744 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3745 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3746 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3747 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3748 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3749 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3750 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3751 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3752 {"reload", imp_reload, METH_O, doc_reload},
3753 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3754 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3755 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3756 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3757 /* The rest are obsolete */
3758 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3759 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3760 {"init_builtin", imp_init_builtin, METH_VARARGS},
3761 {"init_frozen", imp_init_frozen, METH_VARARGS},
3762 {"is_builtin", imp_is_builtin, METH_VARARGS},
3763 {"is_frozen", imp_is_frozen, METH_VARARGS},
3764 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003765#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003767#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 {"load_package", imp_load_package, METH_VARARGS},
3769 {"load_source", imp_load_source, METH_VARARGS},
3770 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003771};
3772
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003773static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003774setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 PyObject *v;
3777 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 v = PyLong_FromLong((long)value);
3780 err = PyDict_SetItemString(d, name, v);
3781 Py_XDECREF(v);
3782 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003783}
3784
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003785typedef struct {
3786 PyObject_HEAD
3787} NullImporter;
3788
3789static int
3790NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3791{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003792#ifndef MS_WINDOWS
3793 PyObject *path;
3794 struct stat statbuf;
3795 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3798 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003799
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003800 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3801 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003803
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003804 if (PyBytes_GET_SIZE(path) == 0) {
3805 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 PyErr_SetString(PyExc_ImportError, "empty pathname");
3807 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003809
3810 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3811 Py_DECREF(path);
3812 if (rv == 0) {
3813 /* it exists */
3814 if (S_ISDIR(statbuf.st_mode)) {
3815 /* it's a directory */
3816 PyErr_SetString(PyExc_ImportError, "existing directory");
3817 return -1;
3818 }
3819 }
3820#else /* MS_WINDOWS */
3821 PyObject *pathobj;
3822 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003823 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003824
3825 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3826 return -1;
3827
3828 if (!PyArg_ParseTuple(args, "U:NullImporter",
3829 &pathobj))
3830 return -1;
3831
3832 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3833 PyErr_SetString(PyExc_ImportError, "empty pathname");
3834 return -1;
3835 }
3836
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003837 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003838 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003839 return -1;
3840 /* see issue1293 and issue3677:
3841 * stat() on Windows doesn't recognise paths like
3842 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3843 */
3844 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003845 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003846 if (rv != INVALID_FILE_ATTRIBUTES) {
3847 /* it exists */
3848 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3849 /* it's a directory */
3850 PyErr_SetString(PyExc_ImportError, "existing directory");
3851 return -1;
3852 }
3853 }
3854#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003856}
3857
3858static PyObject *
3859NullImporter_find_module(NullImporter *self, PyObject *args)
3860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003862}
3863
3864static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3866 "Always return None"
3867 },
3868 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003869};
3870
3871
Christian Heimes9cd17752007-11-18 19:35:23 +00003872PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 PyVarObject_HEAD_INIT(NULL, 0)
3874 "imp.NullImporter", /*tp_name*/
3875 sizeof(NullImporter), /*tp_basicsize*/
3876 0, /*tp_itemsize*/
3877 0, /*tp_dealloc*/
3878 0, /*tp_print*/
3879 0, /*tp_getattr*/
3880 0, /*tp_setattr*/
3881 0, /*tp_reserved*/
3882 0, /*tp_repr*/
3883 0, /*tp_as_number*/
3884 0, /*tp_as_sequence*/
3885 0, /*tp_as_mapping*/
3886 0, /*tp_hash */
3887 0, /*tp_call*/
3888 0, /*tp_str*/
3889 0, /*tp_getattro*/
3890 0, /*tp_setattro*/
3891 0, /*tp_as_buffer*/
3892 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3893 "Null importer object", /* tp_doc */
3894 0, /* tp_traverse */
3895 0, /* tp_clear */
3896 0, /* tp_richcompare */
3897 0, /* tp_weaklistoffset */
3898 0, /* tp_iter */
3899 0, /* tp_iternext */
3900 NullImporter_methods, /* tp_methods */
3901 0, /* tp_members */
3902 0, /* tp_getset */
3903 0, /* tp_base */
3904 0, /* tp_dict */
3905 0, /* tp_descr_get */
3906 0, /* tp_descr_set */
3907 0, /* tp_dictoffset */
3908 (initproc)NullImporter_init, /* tp_init */
3909 0, /* tp_alloc */
3910 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003911};
3912
Martin v. Löwis1a214512008-06-11 05:26:20 +00003913static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 PyModuleDef_HEAD_INIT,
3915 "imp",
3916 doc_imp,
3917 0,
3918 imp_methods,
3919 NULL,
3920 NULL,
3921 NULL,
3922 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003923};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003924
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003925PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003926PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 if (PyType_Ready(&PyNullImporter_Type) < 0)
3931 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 m = PyModule_Create(&impmodule);
3934 if (m == NULL)
3935 goto failure;
3936 d = PyModule_GetDict(m);
3937 if (d == NULL)
3938 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3941 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3942 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3943 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3944 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3945 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3946 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3947 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3948 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3949 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 Py_INCREF(&PyNullImporter_Type);
3952 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3953 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003954 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 Py_XDECREF(m);
3956 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003957}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003958
3959
Guido van Rossumb18618d2000-05-03 23:44:39 +00003960/* API for embedding applications that want to add their own entries
3961 to the table of built-in modules. This should normally be called
3962 *before* Py_Initialize(). When the table resize fails, -1 is
3963 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003964
3965 After a similar function by Just van Rossum. */
3966
3967int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003968PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 static struct _inittab *our_copy = NULL;
3971 struct _inittab *p;
3972 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* Count the number of entries in both tables */
3975 for (n = 0; newtab[n].name != NULL; n++)
3976 ;
3977 if (n == 0)
3978 return 0; /* Nothing to do */
3979 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3980 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* Allocate new memory for the combined table */
3983 p = our_copy;
3984 PyMem_RESIZE(p, struct _inittab, i+n+1);
3985 if (p == NULL)
3986 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 /* Copy the tables into the new memory */
3989 if (our_copy != PyImport_Inittab)
3990 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3991 PyImport_Inittab = our_copy = p;
3992 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003995}
3996
3997/* Shorthand to add a single entry given a name and a function */
3998
3999int
Brett Cannona826f322009-04-02 03:41:46 +00004000PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 newtab[0].name = (char *)name;
4007 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004010}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004011
4012#ifdef __cplusplus
4013}
4014#endif