blob: 37cd4b81f2df68803f97ee39ec7c609c8c7d1acf [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 Stinner95872862011-03-07 18:20:56 +0100120/* See _PyImport_FixupExtensionObject() 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
255void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000256_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 Py_XDECREF(extensions);
259 extensions = NULL;
260 PyMem_DEL(_PyImport_Filetab);
261 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000262}
263
264
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000265/* Locking primitives to prevent parallel imports of the same module
266 in different threads to return with a partially loaded module.
267 These calls are serialized by the global interpreter lock. */
268
269#ifdef WITH_THREAD
270
Guido van Rossum49b56061998-10-01 20:42:43 +0000271#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272
Guido van Rossum65d5b571998-12-21 19:32:43 +0000273static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000274static long import_lock_thread = -1;
275static int import_lock_level = 0;
276
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000277void
278_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 long me = PyThread_get_thread_ident();
281 if (me == -1)
282 return; /* Too bad */
283 if (import_lock == NULL) {
284 import_lock = PyThread_allocate_lock();
285 if (import_lock == NULL)
286 return; /* Nothing much we can do. */
287 }
288 if (import_lock_thread == me) {
289 import_lock_level++;
290 return;
291 }
292 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
293 {
294 PyThreadState *tstate = PyEval_SaveThread();
295 PyThread_acquire_lock(import_lock, 1);
296 PyEval_RestoreThread(tstate);
297 }
298 import_lock_thread = me;
299 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300}
301
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000302int
303_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 long me = PyThread_get_thread_ident();
306 if (me == -1 || import_lock == NULL)
307 return 0; /* Too bad */
308 if (import_lock_thread != me)
309 return -1;
310 import_lock_level--;
311 if (import_lock_level == 0) {
312 import_lock_thread = -1;
313 PyThread_release_lock(import_lock);
314 }
315 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000316}
317
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000318/* This function is called from PyOS_AfterFork to ensure that newly
319 created child processes do not share locks with the parent.
320 We now acquire the import lock around fork() calls but on some platforms
321 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000322
323void
324_PyImport_ReInitLock(void)
325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (import_lock != NULL)
327 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000328 if (import_lock_level > 1) {
329 /* Forked as a side effect of import */
330 long me = PyThread_get_thread_ident();
331 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100332 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000333 import_lock_thread = me;
334 import_lock_level--;
335 } else {
336 import_lock_thread = -1;
337 import_lock_level = 0;
338 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000339}
340
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000341#endif
342
Tim Peters69232342001-08-30 05:16:13 +0000343static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000344imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000345{
Tim Peters69232342001-08-30 05:16:13 +0000346#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000348#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000350#endif
351}
352
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000354imp_acquire_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 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000358#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 Py_INCREF(Py_None);
360 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361}
362
363static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000364imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000365{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000366#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (_PyImport_ReleaseLock() < 0) {
368 PyErr_SetString(PyExc_RuntimeError,
369 "not holding the import lock");
370 return NULL;
371 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000372#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 Py_INCREF(Py_None);
374 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000375}
376
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377static void
378imp_modules_reloading_clear(void)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyInterpreterState *interp = PyThreadState_Get()->interp;
381 if (interp->modules_reloading != NULL)
382 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383}
384
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385/* Helper for sys */
386
387PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000388PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyInterpreterState *interp = PyThreadState_GET()->interp;
391 if (interp->modules == NULL)
392 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
393 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394}
395
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000397/* List of names to clear in sys */
398static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 "path", "argv", "ps1", "ps2",
400 "last_type", "last_value", "last_traceback",
401 "path_hooks", "path_importer_cache", "meta_path",
402 /* misc stuff */
403 "flags", "float_info",
404 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405};
406
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000407static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 "stdin", "__stdin__",
409 "stdout", "__stdout__",
410 "stderr", "__stderr__",
411 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000412};
413
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000415/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000416
Guido van Rossum3f5da241990-12-20 15:06:42 +0000417void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000418PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *key, *value, *dict;
422 PyInterpreterState *interp = PyThreadState_GET()->interp;
423 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (modules == NULL)
426 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 /* Delete some special variables first. These are common
429 places where user values hide and people complain when their
430 destructors fail. Since the modules containing them are
431 deleted *last* of all, they would come too late in the normal
432 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 value = PyDict_GetItemString(modules, "builtins");
435 if (value != NULL && PyModule_Check(value)) {
436 dict = PyModule_GetDict(value);
437 if (Py_VerboseFlag)
438 PySys_WriteStderr("# clear builtins._\n");
439 PyDict_SetItemString(dict, "_", Py_None);
440 }
441 value = PyDict_GetItemString(modules, "sys");
442 if (value != NULL && PyModule_Check(value)) {
443 char **p;
444 PyObject *v;
445 dict = PyModule_GetDict(value);
446 for (p = sys_deletes; *p != NULL; p++) {
447 if (Py_VerboseFlag)
448 PySys_WriteStderr("# clear sys.%s\n", *p);
449 PyDict_SetItemString(dict, *p, Py_None);
450 }
451 for (p = sys_files; *p != NULL; p+=2) {
452 if (Py_VerboseFlag)
453 PySys_WriteStderr("# restore sys.%s\n", *p);
454 v = PyDict_GetItemString(dict, *(p+1));
455 if (v == NULL)
456 v = Py_None;
457 PyDict_SetItemString(dict, *p, v);
458 }
459 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* First, delete __main__ */
462 value = PyDict_GetItemString(modules, "__main__");
463 if (value != NULL && PyModule_Check(value)) {
464 if (Py_VerboseFlag)
465 PySys_WriteStderr("# cleanup __main__\n");
466 _PyModule_Clear(value);
467 PyDict_SetItemString(modules, "__main__", Py_None);
468 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 /* The special treatment of "builtins" here is because even
471 when it's not referenced as a module, its dictionary is
472 referenced by almost every module's __builtins__. Since
473 deleting a module clears its dictionary (even if there are
474 references left to it), we need to delete the "builtins"
475 module last. Likewise, we don't delete sys until the very
476 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Also note that we 'delete' modules by replacing their entry
479 in the modules dict with None, rather than really deleting
480 them; this avoids a rehash of the modules dictionary and
481 also marks them as "non existent" so they won't be
482 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Next, repeatedly delete modules with a reference count of
485 one (skipping builtins and sys) and delete them */
486 do {
487 ndone = 0;
488 pos = 0;
489 while (PyDict_Next(modules, &pos, &key, &value)) {
490 if (value->ob_refcnt != 1)
491 continue;
492 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100493 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100495 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 continue;
497 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100498 PySys_FormatStderr(
499 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 _PyModule_Clear(value);
501 PyDict_SetItem(modules, key, Py_None);
502 ndone++;
503 }
504 }
505 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Next, delete all modules (still skipping builtins and sys) */
508 pos = 0;
509 while (PyDict_Next(modules, &pos, &key, &value)) {
510 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100511 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100513 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 continue;
515 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100516 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 _PyModule_Clear(value);
518 PyDict_SetItem(modules, key, Py_None);
519 }
520 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* Next, delete sys and builtins (in that order) */
523 value = PyDict_GetItemString(modules, "sys");
524 if (value != NULL && PyModule_Check(value)) {
525 if (Py_VerboseFlag)
526 PySys_WriteStderr("# cleanup sys\n");
527 _PyModule_Clear(value);
528 PyDict_SetItemString(modules, "sys", Py_None);
529 }
530 value = PyDict_GetItemString(modules, "builtins");
531 if (value != NULL && PyModule_Check(value)) {
532 if (Py_VerboseFlag)
533 PySys_WriteStderr("# cleanup builtins\n");
534 _PyModule_Clear(value);
535 PyDict_SetItemString(modules, "builtins", Py_None);
536 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 /* Finally, clear and delete the modules directory */
539 PyDict_Clear(modules);
540 interp->modules = NULL;
541 Py_DECREF(modules);
542 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000543}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000544
545
Barry Warsaw28a691b2010-04-17 00:19:56 +0000546/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547
548long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000552}
553
554
Barry Warsaw28a691b2010-04-17 00:19:56 +0000555const char *
556PyImport_GetMagicTag(void)
557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000559}
560
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561/* Magic for extension modules (built-in as well as dynamically
562 loaded). To prevent initializing an extension module more than
563 once, we keep a static dictionary 'extensions' keyed by module name
564 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000565 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100566 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567 immediately after the module initialization function succeeds. A
568 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100569 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000571 Modules which do support multiple initialization set their m_size
572 field to a non-negative number (indicating the size of the
573 module-specific state). They are still recorded in the extensions
574 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000575*/
576
577int
Victor Stinner95872862011-03-07 18:20:56 +0100578_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
579 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyObject *modules, *dict;
582 struct PyModuleDef *def;
583 if (extensions == NULL) {
584 extensions = PyDict_New();
585 if (extensions == NULL)
586 return -1;
587 }
588 if (mod == NULL || !PyModule_Check(mod)) {
589 PyErr_BadInternalCall();
590 return -1;
591 }
592 def = PyModule_GetDef(mod);
593 if (!def) {
594 PyErr_BadInternalCall();
595 return -1;
596 }
597 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100598 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 return -1;
600 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100601 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 return -1;
603 }
604 if (def->m_size == -1) {
605 if (def->m_base.m_copy) {
606 /* Somebody already imported the module,
607 likely under a different name.
608 XXX this should really not happen. */
609 Py_DECREF(def->m_base.m_copy);
610 def->m_base.m_copy = NULL;
611 }
612 dict = PyModule_GetDict(mod);
613 if (dict == NULL)
614 return -1;
615 def->m_base.m_copy = PyDict_Copy(dict);
616 if (def->m_base.m_copy == NULL)
617 return -1;
618 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000619 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621}
622
Victor Stinner49d3f252010-10-17 01:24:53 +0000623int
624_PyImport_FixupBuiltin(PyObject *mod, char *name)
625{
626 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100627 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100628 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100629 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000630 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100631 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
632 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000633 return res;
634}
635
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100637_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyObject *mod, *mdict;
640 PyModuleDef* def;
641 if (extensions == NULL)
642 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000643 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (def == NULL)
645 return NULL;
646 if (def->m_size == -1) {
647 /* Module does not support repeated initialization */
648 if (def->m_base.m_copy == NULL)
649 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100650 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (mod == NULL)
652 return NULL;
653 mdict = PyModule_GetDict(mod);
654 if (mdict == NULL)
655 return NULL;
656 if (PyDict_Update(mdict, def->m_base.m_copy))
657 return NULL;
658 }
659 else {
660 if (def->m_base.m_init == NULL)
661 return NULL;
662 mod = def->m_base.m_init();
663 if (mod == NULL)
664 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100665 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 Py_DECREF(mod);
667 }
668 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100669 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 Py_DECREF(mod);
671 return NULL;
672 }
673 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100674 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 name, filename);
676 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000677
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000678}
679
Victor Stinner49d3f252010-10-17 01:24:53 +0000680PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000681_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000682{
Victor Stinner95872862011-03-07 18:20:56 +0100683 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100684 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100685 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000686 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100687 res = _PyImport_FindExtensionObject(nameobj, nameobj);
688 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000689 return res;
690}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691
692/* Get the module object corresponding to a module name.
693 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000694 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000695 Because the former action is most common, THIS DOES NOT RETURN A
696 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697
Guido van Rossum79f25d91997-04-29 20:08:16 +0000698PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000699PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *modules = PyImport_GetModuleDict();
702 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000703
Victor Stinner27ee0892011-03-04 12:57:09 +0000704 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyModule_Check(m))
706 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000707 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (m == NULL)
709 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000710 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 Py_DECREF(m);
712 return NULL;
713 }
714 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717}
718
Victor Stinner27ee0892011-03-04 12:57:09 +0000719PyObject *
720PyImport_AddModule(const char *name)
721{
722 PyObject *nameobj, *module;
723 nameobj = PyUnicode_FromString(name);
724 if (nameobj == NULL)
725 return NULL;
726 module = PyImport_AddModuleObject(nameobj);
727 Py_DECREF(nameobj);
728 return module;
729}
730
731
Tim Peters1cd70172004-08-02 03:52:12 +0000732/* Remove name from sys.modules, if it's there. */
733static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000734remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000737 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000739 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_FatalError("import: deleting existing key in"
741 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000742}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743
Barry Warsaw28a691b2010-04-17 00:19:56 +0000744static PyObject * get_sourcefile(char *file);
745static char *make_source_pathname(char *pathname, char *buf);
746static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000748
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000749/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000750 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
751 * removed from sys.modules, to avoid leaving damaged module objects
752 * in sys.modules. The caller may wish to restore the original
753 * module object (if any) in this case; PyImport_ReloadModule is an
754 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000755 *
756 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
757 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000758 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000759PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000760PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 return PyImport_ExecCodeModuleWithPathnames(
763 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000764}
765
766PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000767PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 return PyImport_ExecCodeModuleWithPathnames(
770 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000771}
772
773PyObject *
774PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000776{
Victor Stinner27ee0892011-03-04 12:57:09 +0000777 PyObject *m = NULL;
778 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
779
780 nameobj = PyUnicode_FromString(name);
781 if (nameobj == NULL)
782 return NULL;
783
784 if (pathname != NULL) {
785 pathobj = PyUnicode_DecodeFSDefault(pathname);
786 if (pathobj == NULL)
787 goto error;
788 } else
789 pathobj = NULL;
790 if (cpathname != NULL) {
791 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
792 if (cpathobj == NULL)
793 goto error;
794 } else
795 cpathobj = NULL;
796 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
797error:
798 Py_DECREF(nameobj);
799 Py_XDECREF(pathobj);
800 Py_XDECREF(cpathobj);
801 return m;
802}
803
804PyObject*
805PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
806 PyObject *cpathname)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyObject *modules = PyImport_GetModuleDict();
809 PyObject *m, *d, *v;
Victor Stinner27ee0892011-03-04 12:57:09 +0000810 PyObject *pathbytes;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000811
Victor Stinner27ee0892011-03-04 12:57:09 +0000812 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (m == NULL)
814 return NULL;
815 /* If the module is being reloaded, we get the old module back
816 and re-use its dict to exec the new code. */
817 d = PyModule_GetDict(m);
818 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
819 if (PyDict_SetItemString(d, "__builtins__",
820 PyEval_GetBuiltins()) != 0)
821 goto error;
822 }
823 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (pathname != NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000825 pathbytes = PyUnicode_EncodeFSDefault(pathname);
826 if (pathbytes != NULL) {
827 v = get_sourcefile(PyBytes_AS_STRING(pathbytes));
828 Py_DECREF(pathbytes);
829 } else
830 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 if (v == NULL)
832 PyErr_Clear();
833 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000834 else
835 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (v == NULL) {
837 v = ((PyCodeObject *)co)->co_filename;
838 Py_INCREF(v);
839 }
840 if (PyDict_SetItemString(d, "__file__", v) != 0)
841 PyErr_Clear(); /* Not important enough to report */
842 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000845 if (cpathname != NULL)
846 v = cpathname;
847 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (PyDict_SetItemString(d, "__cached__", v) != 0)
850 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000851
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000852 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (v == NULL)
854 goto error;
855 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000856
Victor Stinner27ee0892011-03-04 12:57:09 +0000857 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000859 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 name);
861 return NULL;
862 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000867
868 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 remove_module(name);
870 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000871}
872
873
Barry Warsaw28a691b2010-04-17 00:19:56 +0000874/* Like strrchr(string, '/') but searches for the rightmost of either SEP
875 or ALTSEP, if the latter is defined.
876*/
877static char *
878rightmost_sep(char *s)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 char *found, c;
881 for (found = NULL; (c = *s); s++) {
882 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000883#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000885#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 )
887 {
888 found = s;
889 }
890 }
891 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000892}
893
894
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000895/* Given a pathname for a Python source file, fill a buffer with the
896 pathname for the corresponding compiled file. Return the pathname
897 for the compiled file, or NULL if there's no space in the buffer.
898 Doesn't set an exception. */
899
900static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000901make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* foo.py -> __pycache__/foo.<tag>.pyc */
904 size_t len = strlen(pathname);
905 size_t i, save;
906 char *pos;
907 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* Sanity check that the buffer has roughly enough space to hold what
910 will eventually be the full path to the compiled file. The 5 extra
911 bytes include the slash afer __pycache__, the two extra dots, the
912 extra trailing character ('c' or 'o') and null. This isn't exact
913 because the contents of the buffer can affect how many actual
914 characters of the string get into the buffer. We'll do a final
915 sanity check before writing the extension to ensure we do not
916 overflow the buffer.
917 */
918 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
919 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Find the last path separator and copy everything from the start of
922 the source string up to and including the separator.
923 */
924 if ((pos = rightmost_sep(pathname)) == NULL) {
925 i = 0;
926 }
927 else {
928 sep = *pos;
929 i = pos - pathname + 1;
930 strncpy(buf, pathname, i);
931 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 save = i;
934 buf[i++] = '\0';
935 /* Add __pycache__/ */
936 strcat(buf, CACHEDIR);
937 i += strlen(CACHEDIR) - 1;
938 buf[i++] = sep;
939 buf[i++] = '\0';
940 /* Add the base filename, but remove the .py or .pyw extension, since
941 the tag name must go before the extension.
942 */
943 strcat(buf, pathname + save);
944 if ((pos = strrchr(buf, '.')) != NULL)
945 *++pos = '\0';
946 strcat(buf, pyc_tag);
947 /* The length test above assumes that we're only adding one character
948 to the end of what would normally be the extension. What if there
949 is no extension, or the string ends in '.' or '.p', and otherwise
950 fills the buffer? By appending 4 more characters onto the string
951 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 As a simple example, let's say buflen=32 and the input string is
954 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 which is false and so the name mangling would continue. This would
959 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
964 We can even handle an input string of say 'xxxxx' above because
965 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
966 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 which is 32 characters including the nul, and thus fits in the
971 buffer. However, an input string of 'xxxxxx' would yield a result
972 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 which is 33 characters long (including the nul), thus overflowing
977 the buffer, even though the first test would fail, i.e.: the input
978 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 The reason the first test fails but we still overflow the buffer is
981 that the test above only expects to add one extra character to be
982 added to the extension, and here we're adding three (pyc). We
983 don't add the first dot, so that reclaims one of expected
984 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
985 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 The best we can do is ensure that we still have enough room in the
988 target buffer before we write the extension. Because it's always
989 only the extension that can cause the overflow, and never the other
990 path bytes we've written, it's sufficient to just do one more test
991 here. Still, the assertion that follows can't hurt.
992 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000993#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000995#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (strlen(buf) + 5 > buflen)
997 return NULL;
998 strcat(buf, debug ? ".pyc" : ".pyo");
999 assert(strlen(buf) < buflen);
1000 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001001}
1002
1003
Barry Warsaw28a691b2010-04-17 00:19:56 +00001004/* Given a pathname to a Python byte compiled file, return the path to the
1005 source file, if the path matches the PEP 3147 format. This does not check
1006 for any file existence, however, if the pyc file name does not match PEP
1007 3147 style, NULL is returned. buf must be at least as big as pathname;
1008 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009
Barry Warsaw28a691b2010-04-17 00:19:56 +00001010static char *
1011make_source_pathname(char *pathname, char *buf)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* __pycache__/foo.<tag>.pyc -> foo.py */
1014 size_t i, j;
1015 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Look back two slashes from the end. In between these two slashes
1018 must be the string __pycache__ or this is not a PEP 3147 style
1019 path. It's possible for there to be only one slash.
1020 */
1021 if ((right = rightmost_sep(pathname)) == NULL)
1022 return NULL;
1023 sep = *right;
1024 *right = '\0';
1025 left = rightmost_sep(pathname);
1026 *right = sep;
1027 if (left == NULL)
1028 left = pathname;
1029 else
1030 left++;
1031 if (right-left != strlen(CACHEDIR) ||
1032 strncmp(left, CACHEDIR, right-left) != 0)
1033 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Now verify that the path component to the right of the last slash
1036 has two dots in it.
1037 */
1038 if ((dot0 = strchr(right + 1, '.')) == NULL)
1039 return NULL;
1040 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
1041 return NULL;
1042 /* Too many dots? */
1043 if (strchr(dot1 + 1, '.') != NULL)
1044 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 /* This is a PEP 3147 path. Start by copying everything from the
1047 start of pathname up to and including the leftmost slash. Then
1048 copy the file's basename, removing the magic tag and adding a .py
1049 suffix.
1050 */
1051 strncpy(buf, pathname, (i=left-pathname));
1052 strncpy(buf+i, right+1, (j=dot0-right));
1053 strcpy(buf+i+j, "py");
1054 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001055}
1056
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001057/* Given a pathname for a Python source file, its time of last
1058 modification, and a pathname for a compiled file, check whether the
1059 compiled file represents the same version of the source. If so,
1060 return a FILE pointer for the compiled file, positioned just after
1061 the header; if not, return NULL.
1062 Doesn't set an exception. */
1063
1064static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 FILE *fp;
1068 long magic;
1069 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 fp = fopen(cpathname, "rb");
1072 if (fp == NULL)
1073 return NULL;
1074 magic = PyMarshal_ReadLongFromFile(fp);
1075 if (magic != pyc_magic) {
1076 if (Py_VerboseFlag)
1077 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1078 fclose(fp);
1079 return NULL;
1080 }
1081 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1082 if (pyc_mtime != mtime) {
1083 if (Py_VerboseFlag)
1084 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1085 fclose(fp);
1086 return NULL;
1087 }
1088 if (Py_VerboseFlag)
1089 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1090 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001091}
1092
1093
1094/* Read a code object from a file and check it for validity */
1095
Guido van Rossum79f25d91997-04-29 20:08:16 +00001096static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001097read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 co = PyMarshal_ReadLastObjectFromFile(fp);
1102 if (co == NULL)
1103 return NULL;
1104 if (!PyCode_Check(co)) {
1105 PyErr_Format(PyExc_ImportError,
1106 "Non-code object in %.200s", cpathname);
1107 Py_DECREF(co);
1108 return NULL;
1109 }
1110 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001111}
1112
1113
1114/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001115 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001116
Guido van Rossum79f25d91997-04-29 20:08:16 +00001117static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001118load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 long magic;
1121 PyCodeObject *co;
1122 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 magic = PyMarshal_ReadLongFromFile(fp);
1125 if (magic != pyc_magic) {
1126 PyErr_Format(PyExc_ImportError,
1127 "Bad magic number in %.200s", cpathname);
1128 return NULL;
1129 }
1130 (void) PyMarshal_ReadLongFromFile(fp);
1131 co = read_compiled_module(cpathname, fp);
1132 if (co == NULL)
1133 return NULL;
1134 if (Py_VerboseFlag)
1135 PySys_WriteStderr("import %s # precompiled from %s\n",
1136 name, cpathname);
1137 m = PyImport_ExecCodeModuleWithPathnames(
1138 name, (PyObject *)co, cpathname, cpathname);
1139 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001142}
1143
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001144/* Parse a source file and return the corresponding code object */
1145
Guido van Rossum79f25d91997-04-29 20:08:16 +00001146static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001147parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyCodeObject *co = NULL;
1150 mod_ty mod;
1151 PyCompilerFlags flags;
1152 PyArena *arena = PyArena_New();
1153 if (arena == NULL)
1154 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 flags.cf_flags = 0;
1157 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1158 Py_file_input, 0, 0, &flags,
1159 NULL, arena);
1160 if (mod) {
1161 co = PyAST_Compile(mod, pathname, NULL, arena);
1162 }
1163 PyArena_Free(arena);
1164 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001165}
1166
1167
Guido van Rossum55a83382000-09-20 20:31:38 +00001168/* Helper to open a bytecode file for writing in exclusive mode */
1169
1170static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001171open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001172{
1173#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Use O_EXCL to avoid a race condition when another process tries to
1175 write the same file. When that happens, our open() call fails,
1176 which is just fine (since it's only a cache).
1177 XXX If the file exists and is writable but the directory is not
1178 writable, the file will never be written. Oh well.
1179 */
1180 int fd;
1181 (void) unlink(filename);
1182 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001183#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001185#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001186#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001188#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001190#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 );
1192 if (fd < 0)
1193 return NULL;
1194 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001195#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 /* Best we can do -- on Windows this can't happen anyway */
1197 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001198#endif
1199}
1200
1201
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202/* Write a compiled module to a file, placing the time of last
1203 modification of its source into the header.
1204 Errors are ignored, if a write error occurs an attempt is made to
1205 remove the file. */
1206
1207static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001208write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 FILE *fp;
1211 char *dirpath;
1212 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001213#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001215#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1217 mode_t dirmode = (srcstat->st_mode |
1218 S_IXUSR | S_IXGRP | S_IXOTH |
1219 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001220#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* Ensure that the __pycache__ directory exists. */
1224 dirpath = rightmost_sep(cpathname);
1225 if (dirpath == NULL) {
1226 if (Py_VerboseFlag)
1227 PySys_WriteStderr(
1228 "# no %s path found %s\n",
1229 CACHEDIR, cpathname);
1230 return;
1231 }
1232 saved = *dirpath;
1233 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001234
1235#ifdef MS_WINDOWS
1236 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1237#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001239#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 *dirpath = saved;
1241 if (Py_VerboseFlag)
1242 PySys_WriteStderr(
1243 "# cannot create cache dir %s\n", cpathname);
1244 return;
1245 }
1246 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 fp = open_exclusive(cpathname, mode);
1249 if (fp == NULL) {
1250 if (Py_VerboseFlag)
1251 PySys_WriteStderr(
1252 "# can't create %s\n", cpathname);
1253 return;
1254 }
1255 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1256 /* First write a 0 for mtime */
1257 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1258 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1259 if (fflush(fp) != 0 || ferror(fp)) {
1260 if (Py_VerboseFlag)
1261 PySys_WriteStderr("# can't write %s\n", cpathname);
1262 /* Don't keep partial file */
1263 fclose(fp);
1264 (void) unlink(cpathname);
1265 return;
1266 }
1267 /* Now write the true mtime */
1268 fseek(fp, 4L, 0);
1269 assert(mtime < LONG_MAX);
1270 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1271 fflush(fp);
1272 fclose(fp);
1273 if (Py_VerboseFlag)
1274 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001275}
1276
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001277static void
1278update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyObject *constants, *tmp;
1281 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (PyUnicode_Compare(co->co_filename, oldname))
1284 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 tmp = co->co_filename;
1287 co->co_filename = newname;
1288 Py_INCREF(co->co_filename);
1289 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 constants = co->co_consts;
1292 n = PyTuple_GET_SIZE(constants);
1293 for (i = 0; i < n; i++) {
1294 tmp = PyTuple_GET_ITEM(constants, i);
1295 if (PyCode_Check(tmp))
1296 update_code_filenames((PyCodeObject *)tmp,
1297 oldname, newname);
1298 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001299}
1300
1301static int
1302update_compiled_module(PyCodeObject *co, char *pathname)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 newname = PyUnicode_DecodeFSDefault(pathname);
1307 if (newname == NULL)
1308 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!PyUnicode_Compare(co->co_filename, newname)) {
1311 Py_DECREF(newname);
1312 return 0;
1313 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 oldname = co->co_filename;
1316 Py_INCREF(oldname);
1317 update_code_filenames(co, oldname, newname);
1318 Py_DECREF(oldname);
1319 Py_DECREF(newname);
1320 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001321}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001322
1323/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001324 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1325 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001326
Guido van Rossum79f25d91997-04-29 20:08:16 +00001327static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001328load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 struct stat st;
1331 FILE *fpc;
1332 char buf[MAXPATHLEN+1];
1333 char *cpathname;
1334 PyCodeObject *co;
1335 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (fstat(fileno(fp), &st) != 0) {
1338 PyErr_Format(PyExc_RuntimeError,
1339 "unable to get file status from '%s'",
1340 pathname);
1341 return NULL;
1342 }
Fred Drake4c82b232000-06-30 16:18:57 +00001343#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 /* Python's .pyc timestamp handling presumes that the timestamp fits
1345 in 4 bytes. This will be fine until sometime in the year 2038,
1346 when a 4-byte signed time_t will overflow.
1347 */
1348 if (st.st_mtime >> 32) {
1349 PyErr_SetString(PyExc_OverflowError,
1350 "modification time overflows a 4 byte field");
1351 return NULL;
1352 }
Fred Drake4c82b232000-06-30 16:18:57 +00001353#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 cpathname = make_compiled_pathname(
1355 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1356 if (cpathname != NULL &&
1357 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1358 co = read_compiled_module(cpathname, fpc);
1359 fclose(fpc);
1360 if (co == NULL)
1361 return NULL;
1362 if (update_compiled_module(co, pathname) < 0)
1363 return NULL;
1364 if (Py_VerboseFlag)
1365 PySys_WriteStderr("import %s # precompiled from %s\n",
1366 name, cpathname);
1367 pathname = cpathname;
1368 }
1369 else {
1370 co = parse_source_module(pathname, fp);
1371 if (co == NULL)
1372 return NULL;
1373 if (Py_VerboseFlag)
1374 PySys_WriteStderr("import %s # from %s\n",
1375 name, pathname);
1376 if (cpathname) {
1377 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1378 if (ro == NULL || !PyObject_IsTrue(ro))
1379 write_compiled_module(co, cpathname, &st);
1380 }
1381 }
1382 m = PyImport_ExecCodeModuleWithPathnames(
1383 name, (PyObject *)co, pathname, cpathname);
1384 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001387}
1388
Christian Heimes3b06e532008-01-07 20:12:44 +00001389/* Get source file -> unicode or None
1390 * Returns the path to the py file if available, else the given path
1391 */
1392static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001393get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 char py[MAXPATHLEN + 1];
1396 Py_ssize_t len;
1397 PyObject *u;
1398 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (!file || !*file) {
1401 Py_RETURN_NONE;
1402 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 len = strlen(file);
1405 /* match '*.py?' */
1406 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1407 return PyUnicode_DecodeFSDefault(file);
1408 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 /* Start by trying to turn PEP 3147 path into source path. If that
1411 * fails, just chop off the trailing character, i.e. legacy pyc path
1412 * to py.
1413 */
1414 if (make_source_pathname(file, py) == NULL) {
1415 strncpy(py, file, len-1);
1416 py[len-1] = '\0';
1417 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (stat(py, &statbuf) == 0 &&
1420 S_ISREG(statbuf.st_mode)) {
1421 u = PyUnicode_DecodeFSDefault(py);
1422 }
1423 else {
1424 u = PyUnicode_DecodeFSDefault(file);
1425 }
1426 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001427}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001428
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001429/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001430static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
Victor Stinnerc6963162011-03-12 09:26:54 -05001431static struct filedescr *find_module(char *, const char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 char *, size_t, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001433static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001434
1435/* Load a package and return its module object WITH INCREMENTED
1436 REFERENCE COUNT */
1437
1438static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001439load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *m, *d;
1442 PyObject *file = NULL;
1443 PyObject *path = NULL;
1444 int err;
1445 char buf[MAXPATHLEN+1];
Victor Stinner7d8b77c2011-03-12 08:45:02 -05001446 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 m = PyImport_AddModule(name);
1450 if (m == NULL)
1451 return NULL;
1452 if (Py_VerboseFlag)
1453 PySys_WriteStderr("import %s # directory %s\n",
1454 name, pathname);
1455 d = PyModule_GetDict(m);
1456 file = get_sourcefile(pathname);
1457 if (file == NULL)
1458 goto error;
1459 path = Py_BuildValue("[O]", file);
1460 if (path == NULL)
1461 goto error;
1462 err = PyDict_SetItemString(d, "__file__", file);
1463 if (err == 0)
1464 err = PyDict_SetItemString(d, "__path__", path);
1465 if (err != 0)
1466 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1468 if (fdp == NULL) {
1469 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1470 PyErr_Clear();
1471 Py_INCREF(m);
1472 }
1473 else
1474 m = NULL;
1475 goto cleanup;
1476 }
1477 m = load_module(name, fp, buf, fdp->type, NULL);
1478 if (fp != NULL)
1479 fclose(fp);
1480 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001481
1482 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001484 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_XDECREF(path);
1486 Py_XDECREF(file);
1487 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001488}
1489
1490
1491/* Helper to test for built-in module */
1492
1493static int
Victor Stinner95872862011-03-07 18:20:56 +01001494is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001495{
Victor Stinner95872862011-03-07 18:20:56 +01001496 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001498 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1499 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (PyImport_Inittab[i].initfunc == NULL)
1501 return -1;
1502 else
1503 return 1;
1504 }
1505 }
1506 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001507}
1508
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001509
Just van Rossum52e14d62002-12-30 22:08:05 +00001510/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1511 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001512 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001513 that can handle the path item. Return None if no hook could;
1514 this tells our caller it should fall back to the builtin
1515 import mechanism. Cache the result in path_importer_cache.
1516 Returns a borrowed reference. */
1517
1518static PyObject *
1519get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyObject *importer;
1523 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 /* These conditions are the caller's responsibility: */
1526 assert(PyList_Check(path_hooks));
1527 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 nhooks = PyList_Size(path_hooks);
1530 if (nhooks < 0)
1531 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 importer = PyDict_GetItem(path_importer_cache, p);
1534 if (importer != NULL)
1535 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 /* set path_importer_cache[p] to None to avoid recursion */
1538 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1539 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 for (j = 0; j < nhooks; j++) {
1542 PyObject *hook = PyList_GetItem(path_hooks, j);
1543 if (hook == NULL)
1544 return NULL;
1545 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1546 if (importer != NULL)
1547 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1550 return NULL;
1551 }
1552 PyErr_Clear();
1553 }
1554 if (importer == NULL) {
1555 importer = PyObject_CallFunctionObjArgs(
1556 (PyObject *)&PyNullImporter_Type, p, NULL
1557 );
1558 if (importer == NULL) {
1559 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1560 PyErr_Clear();
1561 return Py_None;
1562 }
1563 }
1564 }
1565 if (importer != NULL) {
1566 int err = PyDict_SetItem(path_importer_cache, p, importer);
1567 Py_DECREF(importer);
1568 if (err != 0)
1569 return NULL;
1570 }
1571 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001572}
1573
Christian Heimes9cd17752007-11-18 19:35:23 +00001574PyAPI_FUNC(PyObject *)
1575PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1579 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1580 importer = get_path_importer(path_importer_cache,
1581 path_hooks, path);
1582 }
1583 }
1584 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1585 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001586}
1587
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001588/* Search the path (default sys.path) for a module. Return the
1589 corresponding filedescr struct, and (via return arguments) the
1590 pathname and an open file. Return NULL if the module is not found. */
1591
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001592#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001593extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1594 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001595#endif
1596
Victor Stinnerc6963162011-03-12 09:26:54 -05001597static int case_ok(char *, Py_ssize_t, Py_ssize_t, const char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001598static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001599static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001600
Victor Stinner7d8b77c2011-03-12 08:45:02 -05001601/* Find a module:
1602
1603 - try find_module() of each sys.meta_path hook
1604 - try find_frozen()
1605 - try is_builtin()
1606 - try _PyWin_FindRegisteredModule() (Windows only)
1607 - otherwise, call find_module_path_list() with search_path_list (if not
1608 NULL) or sys.path
1609
1610 Return:
1611
1612 - &fd_builtin (C_BUILTIN) if it is a builtin
1613 - &fd_frozen (PY_FROZEN) if it is frozen
1614 - &fd_package (PKG_DIRECTORY) and write the filename into *buf
1615 if it is a package
1616 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
1617 importer loader was found
1618 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
1619 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
1620 *buf and the pointer to the open file into *p_fp
1621 - NULL on error
1622
1623 By default, write an empty string into *buf, and *p_fp and *p_loader (if
1624 set) are set to NULL. Eg. *buf is an empty string for a builtin package. */
1625
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001626static struct filedescr *
Victor Stinnerc6963162011-03-12 09:26:54 -05001627find_module(char *fullname, const char *name, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 Py_ssize_t i, npath;
1631 size_t len, namelen;
1632 struct filedescr *fdp = NULL;
1633 char *filemode;
1634 FILE *fp = NULL;
1635 PyObject *path_hooks, *path_importer_cache;
1636 struct stat statbuf;
1637 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1638 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1639 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Andrew MacIntyred9400542002-02-26 11:41:34 +00001640#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 size_t saved_len;
1642 size_t saved_namelen;
1643 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001644#endif
Victor Stinner95872862011-03-07 18:20:56 +01001645 PyObject *fullname_obj, *nameobj;
Victor Stinner53dc7352011-03-20 01:50:21 +01001646
Victor Stinner7d8b77c2011-03-12 08:45:02 -05001647 *buf = '\0';
1648 *p_fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 if (p_loader != NULL)
1650 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001651
Victor Stinnerc6963162011-03-12 09:26:54 -05001652 if (strlen(name) > MAXPATHLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 PyErr_SetString(PyExc_OverflowError,
1654 "module name is too long");
1655 return NULL;
1656 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* sys.meta_path import hook */
1659 if (p_loader != NULL) {
1660 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 meta_path = PySys_GetObject("meta_path");
1663 if (meta_path == NULL || !PyList_Check(meta_path)) {
1664 PyErr_SetString(PyExc_ImportError,
1665 "sys.meta_path must be a list of "
1666 "import hooks");
1667 return NULL;
1668 }
1669 Py_INCREF(meta_path); /* zap guard */
1670 npath = PyList_Size(meta_path);
1671 for (i = 0; i < npath; i++) {
1672 PyObject *loader;
1673 PyObject *hook = PyList_GetItem(meta_path, i);
1674 loader = PyObject_CallMethod(hook, "find_module",
1675 "sO", fullname,
1676 path != NULL ?
1677 path : Py_None);
1678 if (loader == NULL) {
1679 Py_DECREF(meta_path);
1680 return NULL; /* true error */
1681 }
1682 if (loader != Py_None) {
1683 /* a loader was found */
1684 *p_loader = loader;
1685 Py_DECREF(meta_path);
1686 return &importhookdescr;
1687 }
1688 Py_DECREF(loader);
1689 }
1690 Py_DECREF(meta_path);
1691 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001692
Victor Stinner53dc7352011-03-20 01:50:21 +01001693 if (fullname != NULL) {
1694 fullname_obj = PyUnicode_FromString(fullname);
1695 if (fullname == NULL)
1696 return NULL;
1697 if (find_frozen(fullname_obj) != NULL) {
1698 Py_DECREF(fullname_obj);
1699 strcpy(buf, fullname);
1700 return &fd_frozen;
1701 }
1702 Py_DECREF(fullname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (path == NULL) {
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001706#ifdef MS_COREDLL
1707 PyObject *filename, *filename_bytes;
1708#endif
Victor Stinner95872862011-03-07 18:20:56 +01001709 nameobj = PyUnicode_FromString(name);
1710 if (nameobj == NULL)
1711 return NULL;
1712 if (is_builtin(nameobj)) {
1713 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 strcpy(buf, name);
1715 return &fd_builtin;
1716 }
Guido van Rossumac279101996-08-22 23:10:58 +00001717#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001718 fp = _PyWin_FindRegisteredModule(nameobj, &fdp, &filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (fp != NULL) {
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001720 Py_DECREF(nameobj);
1721 filename_bytes = PyUnicode_EncodeFSDefault(filename);
1722 Py_DECREF(filename);
1723 if (filename_bytes == NULL)
1724 return NULL;
1725 strncpy(buf, PyBytes_AS_STRING(filename_bytes), buflen);
1726 buf[buflen-1] = '\0';
1727 Py_DECREF(filename_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 *p_fp = fp;
1729 return fdp;
1730 }
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001731 else if (PyErr_Occurred())
1732 return NULL;
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001733#endif
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001734 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 path = PySys_GetObject("path");
1736 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (path == NULL || !PyList_Check(path)) {
1739 PyErr_SetString(PyExc_ImportError,
1740 "sys.path must be a list of directory names");
1741 return NULL;
1742 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 path_hooks = PySys_GetObject("path_hooks");
1745 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1746 PyErr_SetString(PyExc_ImportError,
1747 "sys.path_hooks must be a list of "
1748 "import hooks");
1749 return NULL;
1750 }
1751 path_importer_cache = PySys_GetObject("path_importer_cache");
1752 if (path_importer_cache == NULL ||
1753 !PyDict_Check(path_importer_cache)) {
1754 PyErr_SetString(PyExc_ImportError,
1755 "sys.path_importer_cache must be a dict");
1756 return NULL;
1757 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 npath = PyList_Size(path);
1760 namelen = strlen(name);
1761 for (i = 0; i < npath; i++) {
1762 PyObject *v = PyList_GetItem(path, i);
1763 PyObject *origv = v;
1764 const char *base;
1765 Py_ssize_t size;
1766 if (!v)
1767 return NULL;
1768 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001769 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (v == NULL)
1771 return NULL;
1772 }
1773 else if (!PyBytes_Check(v))
1774 continue;
1775 else
1776 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 base = PyBytes_AS_STRING(v);
1779 size = PyBytes_GET_SIZE(v);
1780 len = size;
1781 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1782 Py_DECREF(v);
1783 continue; /* Too long */
1784 }
1785 strcpy(buf, base);
1786 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (strlen(buf) != len) {
1789 continue; /* v contains '\0' */
1790 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* sys.path_hooks import hook */
1793 if (p_loader != NULL) {
1794 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 importer = get_path_importer(path_importer_cache,
1797 path_hooks, origv);
1798 if (importer == NULL) {
1799 return NULL;
1800 }
1801 /* Note: importer is a borrowed reference */
1802 if (importer != Py_None) {
1803 PyObject *loader;
1804 loader = PyObject_CallMethod(importer,
1805 "find_module",
1806 "s", fullname);
1807 if (loader == NULL)
1808 return NULL; /* error */
1809 if (loader != Py_None) {
1810 /* a loader was found */
1811 *p_loader = loader;
1812 return &importhookdescr;
1813 }
1814 Py_DECREF(loader);
1815 continue;
1816 }
1817 }
1818 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001821#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001823#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 )
1825 buf[len++] = SEP;
1826 strcpy(buf+len, name);
1827 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 /* Check for package import (buf holds a directory name,
1830 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001831#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (stat(buf, &statbuf) == 0 && /* it exists */
1833 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1834 case_ok(buf, len, namelen, name)) { /* case matches */
1835 if (find_init_module(buf)) { /* and has __init__.py */
1836 return &fd_package;
1837 }
1838 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001839 int err;
1840 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1841 if (unicode == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 return NULL;
Victor Stinnered7916d2010-10-17 02:07:09 +00001843 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1844 "Not importing directory '%U': missing __init__.py",
1845 unicode);
1846 Py_DECREF(unicode);
1847 if (err)
1848 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
1850 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001851#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001852#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* take a snapshot of the module spec for restoration
1854 * after the 8 character DLL hackery
1855 */
1856 saved_buf = strdup(buf);
1857 saved_len = len;
1858 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001859#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001861#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 /* OS/2 limits DLLs to 8 character names (w/o
1863 extension)
1864 * so if the name is longer than that and its a
1865 * dynamically loaded module we're going to try,
1866 * truncate the name before trying
1867 */
Victor Stinnerc6963162011-03-12 09:26:54 -05001868 if (strlen(name) > 8) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 /* is this an attempt to load a C extension? */
1870 const struct filedescr *scan;
1871 scan = _PyImport_DynLoadFiletab;
1872 while (scan->suffix != NULL) {
1873 if (!strcmp(scan->suffix, fdp->suffix))
1874 break;
1875 else
1876 scan++;
1877 }
1878 if (scan->suffix != NULL) {
1879 /* yes, so truncate the name */
1880 namelen = 8;
Victor Stinnerc6963162011-03-12 09:26:54 -05001881 len -= strlen(name) - namelen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 buf[len] = '\0';
1883 }
1884 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001885#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 strcpy(buf+len, fdp->suffix);
1887 if (Py_VerboseFlag > 1)
1888 PySys_WriteStderr("# trying %s\n", buf);
1889 filemode = fdp->mode;
1890 if (filemode[0] == 'U')
1891 filemode = "r" PY_STDIOTEXTMODE;
1892 fp = fopen(buf, filemode);
1893 if (fp != NULL) {
1894 if (case_ok(buf, len, namelen, name))
1895 break;
1896 else { /* continue search */
1897 fclose(fp);
1898 fp = NULL;
1899 }
1900 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001901#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 /* restore the saved snapshot */
1903 strcpy(buf, saved_buf);
1904 len = saved_len;
1905 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001906#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001908#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 /* don't need/want the module name snapshot anymore */
1910 if (saved_buf)
1911 {
1912 free(saved_buf);
1913 saved_buf = NULL;
1914 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001915#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (fp != NULL)
1917 break;
1918 }
1919 if (fp == NULL) {
1920 PyErr_Format(PyExc_ImportError,
1921 "No module named %.200s", name);
1922 return NULL;
1923 }
1924 *p_fp = fp;
1925 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001926}
1927
Martin v. Löwis18e16552006-02-15 17:27:45 +00001928/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001929 * The arguments here are tricky, best shown by example:
1930 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1931 * ^ ^ ^ ^
1932 * |--------------------- buf ---------------------|
1933 * |------------------- len ------------------|
1934 * |------ name -------|
1935 * |----- namelen -----|
1936 * buf is the full path, but len only counts up to (& exclusive of) the
1937 * extension. name is the module name, also exclusive of extension.
1938 *
1939 * We've already done a successful stat() or fopen() on buf, so know that
1940 * there's some match, possibly case-insensitive.
1941 *
Tim Peters50d8d372001-02-28 05:34:27 +00001942 * case_ok() is to return 1 if there's a case-sensitive match for
1943 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1944 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001945 *
Tim Peters50d8d372001-02-28 05:34:27 +00001946 * case_ok() is used to implement case-sensitive import semantics even
1947 * on platforms with case-insensitive filesystems. It's trivial to implement
1948 * for case-sensitive filesystems. It's pretty much a cross-platform
1949 * nightmare for systems with case-insensitive filesystems.
1950 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001951
Tim Peters50d8d372001-02-28 05:34:27 +00001952/* First we may need a pile of platform-specific header files; the sequence
1953 * of #if's here should match the sequence in the body of case_ok().
1954 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001955#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001956#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001957
Tim Peters50d8d372001-02-28 05:34:27 +00001958#elif defined(DJGPP)
1959#include <dir.h>
1960
Jason Tishler7961aa62005-05-20 00:56:54 +00001961#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001962#include <sys/types.h>
1963#include <dirent.h>
1964
Andrew MacIntyred9400542002-02-26 11:41:34 +00001965#elif defined(PYOS_OS2)
1966#define INCL_DOS
1967#define INCL_DOSERRORS
1968#define INCL_NOPMAPI
1969#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001970#endif
1971
Guido van Rossum0980bd91998-02-13 17:18:36 +00001972static int
Victor Stinnerc6963162011-03-12 09:26:54 -05001973case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001974{
Tim Peters50d8d372001-02-28 05:34:27 +00001975/* Pick a platform-specific implementation; the sequence of #if's here should
1976 * match the sequence just above.
1977 */
1978
Jason Tishler7961aa62005-05-20 00:56:54 +00001979/* MS_WINDOWS */
1980#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 WIN32_FIND_DATA data;
1982 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (Py_GETENV("PYTHONCASEOK") != NULL)
1985 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 h = FindFirstFile(buf, &data);
1988 if (h == INVALID_HANDLE_VALUE) {
1989 PyErr_Format(PyExc_NameError,
1990 "Can't find file for module %.100s\n(filename %.300s)",
1991 name, buf);
1992 return 0;
1993 }
1994 FindClose(h);
1995 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001996
1997/* DJGPP */
1998#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 struct ffblk ffblk;
2000 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (Py_GETENV("PYTHONCASEOK") != NULL)
2003 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2006 if (done) {
2007 PyErr_Format(PyExc_NameError,
2008 "Can't find file for module %.100s\n(filename %.300s)",
2009 name, buf);
2010 return 0;
2011 }
2012 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002013
Jason Tishler7961aa62005-05-20 00:56:54 +00002014/* new-fangled macintosh (macosx) or Cygwin */
2015#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 DIR *dirp;
2017 struct dirent *dp;
2018 char dirname[MAXPATHLEN + 1];
2019 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (Py_GETENV("PYTHONCASEOK") != NULL)
2022 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Copy the dir component into dirname; substitute "." if empty */
2025 if (dirlen <= 0) {
2026 dirname[0] = '.';
2027 dirname[1] = '\0';
2028 }
2029 else {
2030 assert(dirlen <= MAXPATHLEN);
2031 memcpy(dirname, buf, dirlen);
2032 dirname[dirlen] = '\0';
2033 }
2034 /* Open the directory and search the entries for an exact match. */
2035 dirp = opendir(dirname);
2036 if (dirp) {
2037 char *nameWithExt = buf + len - namelen;
2038 while ((dp = readdir(dirp)) != NULL) {
2039 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002040#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002042#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002044#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 if (thislen >= namelen &&
2046 strcmp(dp->d_name, nameWithExt) == 0) {
2047 (void)closedir(dirp);
2048 return 1; /* Found */
2049 }
2050 }
2051 (void)closedir(dirp);
2052 }
2053 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002054
Andrew MacIntyred9400542002-02-26 11:41:34 +00002055/* OS/2 */
2056#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 HDIR hdir = 1;
2058 ULONG srchcnt = 1;
2059 FILEFINDBUF3 ffbuf;
2060 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (Py_GETENV("PYTHONCASEOK") != NULL)
2063 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 rc = DosFindFirst(buf,
2066 &hdir,
2067 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2068 &ffbuf, sizeof(ffbuf),
2069 &srchcnt,
2070 FIL_STANDARD);
2071 if (rc != NO_ERROR)
2072 return 0;
2073 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002074
Tim Peters50d8d372001-02-28 05:34:27 +00002075/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2076#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002078
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002079#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002080}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002081
Guido van Rossum197346f1997-10-31 18:38:52 +00002082#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002083
Guido van Rossum197346f1997-10-31 18:38:52 +00002084/* Helper to look for __init__.py or __init__.py[co] in potential package */
2085static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002086find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 const size_t save_len = strlen(buf);
2089 size_t i = save_len;
2090 char *pname; /* pointer to start of __init__ */
2091 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093/* For calling case_ok(buf, len, namelen, name):
2094 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2095 * ^ ^ ^ ^
2096 * |--------------------- buf ---------------------|
2097 * |------------------- len ------------------|
2098 * |------ name -------|
2099 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002100 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (save_len + 13 >= MAXPATHLEN)
2102 return 0;
2103 buf[i++] = SEP;
2104 pname = buf + i;
2105 strcpy(pname, "__init__.py");
2106 if (stat(buf, &statbuf) == 0) {
2107 if (case_ok(buf,
2108 save_len + 9, /* len("/__init__") */
2109 8, /* len("__init__") */
2110 pname)) {
2111 buf[save_len] = '\0';
2112 return 1;
2113 }
2114 }
2115 i += strlen(pname);
2116 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2117 if (stat(buf, &statbuf) == 0) {
2118 if (case_ok(buf,
2119 save_len + 9, /* len("/__init__") */
2120 8, /* len("__init__") */
2121 pname)) {
2122 buf[save_len] = '\0';
2123 return 1;
2124 }
2125 }
2126 buf[save_len] = '\0';
2127 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002128}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002129
Guido van Rossum197346f1997-10-31 18:38:52 +00002130#endif /* HAVE_STAT */
2131
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002132
Victor Stinner95872862011-03-07 18:20:56 +01002133static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002134
Victor Stinner44c6c152010-08-09 00:59:10 +00002135static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002136load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002137{
2138 PyObject *m, *modules;
2139 int err;
2140
Victor Stinner44c6c152010-08-09 00:59:10 +00002141 if (type == C_BUILTIN)
2142 err = init_builtin(name);
2143 else
Victor Stinner95872862011-03-07 18:20:56 +01002144 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002145 if (err < 0)
2146 return NULL;
2147 if (err == 0) {
2148 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002149 "Purported %s module %R not found",
2150 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002151 name);
2152 return NULL;
2153 }
2154
2155 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002156 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002157 if (m == NULL) {
2158 PyErr_Format(
2159 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002160 "%s module %R not properly initialized",
2161 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002162 name);
2163 return NULL;
2164 }
2165 Py_INCREF(m);
2166 return m;
2167}
2168
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002169/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002170 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002171
Guido van Rossum79f25d91997-04-29 20:08:16 +00002172static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002173load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* First check that there's an open file (if we need one) */
2178 switch (type) {
2179 case PY_SOURCE:
2180 case PY_COMPILED:
2181 if (fp == NULL) {
2182 PyErr_Format(PyExc_ValueError,
2183 "file object required for import (type code %d)",
2184 type);
2185 return NULL;
2186 }
2187 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 case PY_SOURCE:
2192 m = load_source_module(name, pathname, fp);
2193 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 case PY_COMPILED:
2196 m = load_compiled_module(name, pathname, fp);
2197 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002198
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002199#ifdef HAVE_DYNAMIC_LOADING
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002200 case C_EXTENSION: {
2201 PyObject *nameobj, *pathobj;
2202 nameobj = PyUnicode_FromString(name);
2203 if (nameobj == NULL)
2204 return NULL;
2205 pathobj = PyUnicode_DecodeFSDefault(pathname);
2206 if (pathobj == NULL) {
2207 Py_DECREF(nameobj);
2208 return NULL;
2209 }
2210 m = _PyImport_LoadDynamicModule(nameobj, pathobj, fp);
2211 Py_DECREF(nameobj);
2212 Py_DECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 break;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002214 }
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002215#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 case PKG_DIRECTORY:
2218 m = load_package(name, pathname);
2219 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 case C_BUILTIN:
Victor Stinner95872862011-03-07 18:20:56 +01002222 case PY_FROZEN: {
2223 PyObject *nameobj = PyUnicode_FromString(name);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002224 if (nameobj == NULL)
2225 return NULL;
2226 m = load_builtin(nameobj, type);
2227 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 break;
Victor Stinner95872862011-03-07 18:20:56 +01002229 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 case IMP_HOOK: {
2232 if (loader == NULL) {
2233 PyErr_SetString(PyExc_ImportError,
2234 "import hook without loader");
2235 return NULL;
2236 }
2237 m = PyObject_CallMethod(loader, "load_module", "s", name);
2238 break;
2239 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 default:
2242 PyErr_Format(PyExc_ImportError,
2243 "Don't know how to import %.200s (type code %d)",
2244 name, type);
2245 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002250}
2251
2252
2253/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002254 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002255 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002256
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002257static int
Victor Stinner95872862011-03-07 18:20:56 +01002258init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002261
Victor Stinner95872862011-03-07 18:20:56 +01002262 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 for (p = PyImport_Inittab; p->name != NULL; p++) {
2266 PyObject *mod;
Victor Stinner95872862011-03-07 18:20:56 +01002267 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (p->initfunc == NULL) {
2269 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002270 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 name);
2272 return -1;
2273 }
2274 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +01002275 PySys_FormatStderr("import %U # builtin\n", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 mod = (*p->initfunc)();
2277 if (mod == 0)
2278 return -1;
Victor Stinner95872862011-03-07 18:20:56 +01002279 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 return -1;
2281 /* FixupExtension has put the module into sys.modules,
2282 so we can release our own reference. */
2283 Py_DECREF(mod);
2284 return 1;
2285 }
2286 }
2287 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002288}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002289
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002290
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002291/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002292
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002293static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002294find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002297
Victor Stinner53dc7352011-03-20 01:50:21 +01002298 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 for (p = PyImport_FrozenModules; ; p++) {
2302 if (p->name == NULL)
2303 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002304 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 break;
2306 }
2307 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002308}
2309
Guido van Rossum79f25d91997-04-29 20:08:16 +00002310static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002311get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 struct _frozen *p = find_frozen(name);
2314 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 if (p == NULL) {
2317 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002318 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 name);
2320 return NULL;
2321 }
2322 if (p->code == NULL) {
2323 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002324 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 name);
2326 return NULL;
2327 }
2328 size = p->size;
2329 if (size < 0)
2330 size = -size;
2331 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002332}
2333
Brett Cannon8d110132009-03-15 02:20:16 +00002334static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002335is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 struct _frozen *p = find_frozen(name);
2338 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 if (p == NULL) {
2341 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002342 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 name);
2344 return NULL;
2345 }
Brett Cannon8d110132009-03-15 02:20:16 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 if (size < 0)
2350 Py_RETURN_TRUE;
2351 else
2352 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002353}
2354
2355
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002356/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002357 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002358 an exception set if the initialization failed.
2359 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002360
2361int
Victor Stinner53dc7352011-03-20 01:50:21 +01002362PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002363{
Victor Stinner53dc7352011-03-20 01:50:21 +01002364 struct _frozen *p;
2365 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 int ispackage;
2367 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002368
Victor Stinner53dc7352011-03-20 01:50:21 +01002369 p = find_frozen(name);
2370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 if (p == NULL)
2372 return 0;
2373 if (p->code == NULL) {
2374 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002375 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 name);
2377 return -1;
2378 }
2379 size = p->size;
2380 ispackage = (size < 0);
2381 if (ispackage)
2382 size = -size;
2383 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002384 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 name, ispackage ? " package" : "");
2386 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2387 if (co == NULL)
2388 return -1;
2389 if (!PyCode_Check(co)) {
2390 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002391 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 name);
2393 goto err_return;
2394 }
2395 if (ispackage) {
2396 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002397 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002399 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 if (m == NULL)
2401 goto err_return;
2402 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 l = PyList_New(1);
2404 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 goto err_return;
2406 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002407 Py_INCREF(name);
2408 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 err = PyDict_SetItemString(d, "__path__", l);
2410 Py_DECREF(l);
2411 if (err != 0)
2412 goto err_return;
2413 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002414 path = PyUnicode_FromString("<frozen>");
2415 if (path == NULL)
2416 goto err_return;
2417 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2418 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (m == NULL)
2420 goto err_return;
2421 Py_DECREF(co);
2422 Py_DECREF(m);
2423 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002424err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 Py_DECREF(co);
2426 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002427}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002428
Victor Stinner53dc7352011-03-20 01:50:21 +01002429int
2430PyImport_ImportFrozenModule(char *name)
2431{
2432 PyObject *nameobj;
2433 int ret;
2434 nameobj = PyUnicode_InternFromString(name);
2435 if (nameobj == NULL)
2436 return -1;
2437 ret = PyImport_ImportFrozenModuleObject(nameobj);
2438 Py_DECREF(nameobj);
2439 return ret;
2440}
2441
Guido van Rossum74e6a111994-08-29 12:54:38 +00002442
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002443/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002444 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002445
Guido van Rossum79f25d91997-04-29 20:08:16 +00002446PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002447PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 PyObject *pname;
2450 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 pname = PyUnicode_FromString(name);
2453 if (pname == NULL)
2454 return NULL;
2455 result = PyImport_Import(pname);
2456 Py_DECREF(pname);
2457 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002458}
2459
Christian Heimes072c0f12008-01-03 23:01:04 +00002460/* Import a module without blocking
2461 *
2462 * At first it tries to fetch the module from sys.modules. If the module was
2463 * never loaded before it loads it with PyImport_ImportModule() unless another
2464 * thread holds the import lock. In the latter case the function raises an
2465 * ImportError instead of blocking.
2466 *
2467 * Returns the module object with incremented ref count.
2468 */
2469PyObject *
2470PyImport_ImportModuleNoBlock(const char *name)
2471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 PyObject *result;
2473 PyObject *modules;
2474 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* Try to get the module from sys.modules[name] */
2477 modules = PyImport_GetModuleDict();
2478 if (modules == NULL)
2479 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 result = PyDict_GetItemString(modules, name);
2482 if (result != NULL) {
2483 Py_INCREF(result);
2484 return result;
2485 }
2486 else {
2487 PyErr_Clear();
2488 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002489#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* check the import lock
2491 * me might be -1 but I ignore the error here, the lock function
2492 * takes care of the problem */
2493 me = PyThread_get_thread_ident();
2494 if (import_lock_thread == -1 || import_lock_thread == me) {
2495 /* no thread or me is holding the lock */
2496 return PyImport_ImportModule(name);
2497 }
2498 else {
2499 PyErr_Format(PyExc_ImportError,
2500 "Failed to import %.200s because the import lock"
2501 "is held by another thread.",
2502 name);
2503 return NULL;
2504 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002505#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002507#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002508}
2509
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002510/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002511static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002513static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002515static int mark_miss(char *name);
2516static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002518static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002519
2520/* The Magnum Opus of dotted-name import :-) */
2521
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002522static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002523import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 char buf[MAXPATHLEN+1];
2527 Py_ssize_t buflen = 0;
2528 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002531#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002533#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 ) {
2535 PyErr_SetString(PyExc_ImportError,
2536 "Import by filename is not supported.");
2537 return NULL;
2538 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 parent = get_parent(globals, buf, &buflen, level);
2541 if (parent == NULL)
2542 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002543
Benjamin Peterson556d8002010-06-27 22:37:28 +00002544 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2545 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (head == NULL)
2547 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 tail = head;
2550 Py_INCREF(tail);
2551 while (name) {
2552 next = load_next(tail, tail, &name, buf, &buflen);
2553 Py_DECREF(tail);
2554 if (next == NULL) {
2555 Py_DECREF(head);
2556 return NULL;
2557 }
2558 tail = next;
2559 }
2560 if (tail == Py_None) {
2561 /* If tail is Py_None, both get_parent and load_next found
2562 an empty module name: someone called __import__("") or
2563 doctored faulty bytecode */
2564 Py_DECREF(tail);
2565 Py_DECREF(head);
2566 PyErr_SetString(PyExc_ValueError,
2567 "Empty module name");
2568 return NULL;
2569 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (fromlist != NULL) {
2572 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2573 fromlist = NULL;
2574 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 if (fromlist == NULL) {
2577 Py_DECREF(tail);
2578 return head;
2579 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 Py_DECREF(head);
2582 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2583 Py_DECREF(tail);
2584 return NULL;
2585 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002588}
2589
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002590PyObject *
2591PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 PyObject *result;
2595 _PyImport_AcquireLock();
2596 result = import_module_level(name, globals, locals, fromlist, level);
2597 if (_PyImport_ReleaseLock() < 0) {
2598 Py_XDECREF(result);
2599 PyErr_SetString(PyExc_RuntimeError,
2600 "not holding the import lock");
2601 return NULL;
2602 }
2603 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002604}
2605
Fred Drake87590902004-05-28 20:21:36 +00002606/* Return the package that an import is being performed in. If globals comes
2607 from the module foo.bar.bat (not itself a package), this returns the
2608 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002609 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002610
2611 The *name* of the returned package is returned in buf, with the length of
2612 the name in *p_buflen.
2613
2614 If globals doesn't come from a package or a module in a package, or a
2615 corresponding entry is not found in sys.modules, Py_None is returned.
2616*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002617static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002618get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 static PyObject *namestr = NULL;
2621 static PyObject *pathstr = NULL;
2622 static PyObject *pkgstr = NULL;
2623 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2624 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 if (globals == NULL || !PyDict_Check(globals) || !level)
2627 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (namestr == NULL) {
2630 namestr = PyUnicode_InternFromString("__name__");
2631 if (namestr == NULL)
2632 return NULL;
2633 }
2634 if (pathstr == NULL) {
2635 pathstr = PyUnicode_InternFromString("__path__");
2636 if (pathstr == NULL)
2637 return NULL;
2638 }
2639 if (pkgstr == NULL) {
2640 pkgstr = PyUnicode_InternFromString("__package__");
2641 if (pkgstr == NULL)
2642 return NULL;
2643 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 *buf = '\0';
2646 *p_buflen = 0;
2647 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if ((pkgname != NULL) && (pkgname != Py_None)) {
2650 /* __package__ is set, so use it */
2651 char *pkgname_str;
2652 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (!PyUnicode_Check(pkgname)) {
2655 PyErr_SetString(PyExc_ValueError,
2656 "__package__ set to non-string");
2657 return NULL;
2658 }
2659 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2660 if (len == 0) {
2661 if (level > 0) {
2662 PyErr_SetString(PyExc_ValueError,
2663 "Attempted relative import in non-package");
2664 return NULL;
2665 }
2666 return Py_None;
2667 }
2668 if (len > MAXPATHLEN) {
2669 PyErr_SetString(PyExc_ValueError,
2670 "Package name too long");
2671 return NULL;
2672 }
2673 strcpy(buf, pkgname_str);
2674 } else {
2675 /* __package__ not set, so figure it out and set it */
2676 modname = PyDict_GetItem(globals, namestr);
2677 if (modname == NULL || !PyUnicode_Check(modname))
2678 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 modpath = PyDict_GetItem(globals, pathstr);
2681 if (modpath != NULL) {
2682 /* __path__ is set, so modname is already the package name */
2683 char *modname_str;
2684 Py_ssize_t len;
2685 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2688 if (len > MAXPATHLEN) {
2689 PyErr_SetString(PyExc_ValueError,
2690 "Module name too long");
2691 return NULL;
2692 }
2693 strcpy(buf, modname_str);
2694 error = PyDict_SetItem(globals, pkgstr, modname);
2695 if (error) {
2696 PyErr_SetString(PyExc_ValueError,
2697 "Could not set __package__");
2698 return NULL;
2699 }
2700 } else {
2701 /* Normal module, so work out the package name if any */
2702 char *start = _PyUnicode_AsString(modname);
2703 char *lastdot = strrchr(start, '.');
2704 size_t len;
2705 int error;
2706 if (lastdot == NULL && level > 0) {
2707 PyErr_SetString(PyExc_ValueError,
2708 "Attempted relative import in non-package");
2709 return NULL;
2710 }
2711 if (lastdot == NULL) {
2712 error = PyDict_SetItem(globals, pkgstr, Py_None);
2713 if (error) {
2714 PyErr_SetString(PyExc_ValueError,
2715 "Could not set __package__");
2716 return NULL;
2717 }
2718 return Py_None;
2719 }
2720 len = lastdot - start;
2721 if (len >= MAXPATHLEN) {
2722 PyErr_SetString(PyExc_ValueError,
2723 "Module name too long");
2724 return NULL;
2725 }
2726 strncpy(buf, start, len);
2727 buf[len] = '\0';
2728 pkgname = PyUnicode_FromString(buf);
2729 if (pkgname == NULL) {
2730 return NULL;
2731 }
2732 error = PyDict_SetItem(globals, pkgstr, pkgname);
2733 Py_DECREF(pkgname);
2734 if (error) {
2735 PyErr_SetString(PyExc_ValueError,
2736 "Could not set __package__");
2737 return NULL;
2738 }
2739 }
2740 }
2741 while (--level > 0) {
2742 char *dot = strrchr(buf, '.');
2743 if (dot == NULL) {
2744 PyErr_SetString(PyExc_ValueError,
2745 "Attempted relative import beyond "
2746 "toplevel package");
2747 return NULL;
2748 }
2749 *dot = '\0';
2750 }
2751 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 modules = PyImport_GetModuleDict();
2754 parent = PyDict_GetItemString(modules, buf);
2755 if (parent == NULL) {
2756 if (orig_level < 1) {
2757 PyObject *err_msg = PyBytes_FromFormat(
2758 "Parent module '%.200s' not found "
2759 "while handling absolute import", buf);
2760 if (err_msg == NULL) {
2761 return NULL;
2762 }
2763 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2764 PyBytes_AsString(err_msg), 1)) {
2765 *buf = '\0';
2766 *p_buflen = 0;
2767 parent = Py_None;
2768 }
2769 Py_DECREF(err_msg);
2770 } else {
2771 PyErr_Format(PyExc_SystemError,
2772 "Parent module '%.200s' not loaded, "
2773 "cannot perform relative import", buf);
2774 }
2775 }
2776 return parent;
2777 /* We expect, but can't guarantee, if parent != None, that:
2778 - parent.__name__ == buf
2779 - parent.__dict__ is globals
2780 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002781}
2782
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002783/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002784static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002785load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 char *name = *p_name;
2789 char *dot = strchr(name, '.');
2790 size_t len;
2791 char *p;
2792 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 if (strlen(name) == 0) {
2795 /* completely empty module name should only happen in
2796 'from . import' (or '__import__("")')*/
2797 Py_INCREF(mod);
2798 *p_name = NULL;
2799 return mod;
2800 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 if (dot == NULL) {
2803 *p_name = NULL;
2804 len = strlen(name);
2805 }
2806 else {
2807 *p_name = dot+1;
2808 len = dot-name;
2809 }
2810 if (len == 0) {
2811 PyErr_SetString(PyExc_ValueError,
2812 "Empty module name");
2813 return NULL;
2814 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 p = buf + *p_buflen;
2817 if (p != buf)
2818 *p++ = '.';
2819 if (p+len-buf >= MAXPATHLEN) {
2820 PyErr_SetString(PyExc_ValueError,
2821 "Module name too long");
2822 return NULL;
2823 }
2824 strncpy(p, name, len);
2825 p[len] = '\0';
2826 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 result = import_submodule(mod, p, buf);
2829 if (result == Py_None && altmod != mod) {
2830 Py_DECREF(result);
2831 /* Here, altmod must be None and mod must not be None */
2832 result = import_submodule(altmod, p, p);
2833 if (result != NULL && result != Py_None) {
2834 if (mark_miss(buf) != 0) {
2835 Py_DECREF(result);
2836 return NULL;
2837 }
2838 strncpy(buf, name, len);
2839 buf[len] = '\0';
2840 *p_buflen = len;
2841 }
2842 }
2843 if (result == NULL)
2844 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 if (result == Py_None) {
2847 Py_DECREF(result);
2848 PyErr_Format(PyExc_ImportError,
2849 "No module named %.200s", name);
2850 return NULL;
2851 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002854}
2855
2856static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002857mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 PyObject *modules = PyImport_GetModuleDict();
2860 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002861}
2862
2863static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002864ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 if (!PyObject_HasAttrString(mod, "__path__"))
2870 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 for (i = 0; ; i++) {
2873 PyObject *item = PySequence_GetItem(fromlist, i);
2874 int hasit;
2875 if (item == NULL) {
2876 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2877 PyErr_Clear();
2878 return 1;
2879 }
2880 return 0;
2881 }
2882 if (!PyUnicode_Check(item)) {
2883 PyErr_SetString(PyExc_TypeError,
2884 "Item in ``from list'' not a string");
2885 Py_DECREF(item);
2886 return 0;
2887 }
2888 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2889 PyObject *all;
2890 Py_DECREF(item);
2891 /* See if the package defines __all__ */
2892 if (recursive)
2893 continue; /* Avoid endless recursion */
2894 all = PyObject_GetAttrString(mod, "__all__");
2895 if (all == NULL)
2896 PyErr_Clear();
2897 else {
2898 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2899 Py_DECREF(all);
2900 if (!ret)
2901 return 0;
2902 }
2903 continue;
2904 }
2905 hasit = PyObject_HasAttr(mod, item);
2906 if (!hasit) {
2907 PyObject *item8;
2908 char *subname;
2909 PyObject *submod;
2910 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002911 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 if (!item8) {
2913 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2914 return 0;
2915 }
2916 subname = PyBytes_AS_STRING(item8);
2917 if (buflen + strlen(subname) >= MAXPATHLEN) {
2918 PyErr_SetString(PyExc_ValueError,
2919 "Module name too long");
2920 Py_DECREF(item);
2921 return 0;
2922 }
2923 p = buf + buflen;
2924 *p++ = '.';
2925 strcpy(p, subname);
2926 submod = import_submodule(mod, subname, buf);
2927 Py_DECREF(item8);
2928 Py_XDECREF(submod);
2929 if (submod == NULL) {
2930 Py_DECREF(item);
2931 return 0;
2932 }
2933 }
2934 Py_DECREF(item);
2935 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002938}
2939
Neil Schemenauer00b09662003-06-16 21:03:07 +00002940static int
2941add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 if (mod == Py_None)
2945 return 1;
2946 /* Irrespective of the success of this load, make a
2947 reference to it in the parent package module. A copy gets
2948 saved in the modules dictionary under the full name, so get a
2949 reference from there, if need be. (The exception is when the
2950 load failed with a SyntaxError -- then there's no trace in
2951 sys.modules. In that case, of course, do nothing extra.) */
2952 if (submod == NULL) {
2953 submod = PyDict_GetItemString(modules, fullname);
2954 if (submod == NULL)
2955 return 1;
2956 }
2957 if (PyModule_Check(mod)) {
2958 /* We can't use setattr here since it can give a
2959 * spurious warning if the submodule name shadows a
2960 * builtin name */
2961 PyObject *dict = PyModule_GetDict(mod);
2962 if (!dict)
2963 return 0;
2964 if (PyDict_SetItemString(dict, subname, submod) < 0)
2965 return 0;
2966 }
2967 else {
2968 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2969 return 0;
2970 }
2971 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002972}
2973
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002974static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002975import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 PyObject *modules = PyImport_GetModuleDict();
2978 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 /* Require:
2981 if mod == None: subname == fullname
2982 else: mod.__name__ + "." + subname == fullname
2983 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2986 Py_INCREF(m);
2987 }
2988 else {
Victor Stinner7d8b77c2011-03-12 08:45:02 -05002989 PyObject *path, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 char buf[MAXPATHLEN+1];
2991 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05002992 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 if (mod == Py_None)
2995 path = NULL;
2996 else {
2997 path = PyObject_GetAttrString(mod, "__path__");
2998 if (path == NULL) {
2999 PyErr_Clear();
3000 Py_INCREF(Py_None);
3001 return Py_None;
3002 }
3003 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
3006 &fp, &loader);
3007 Py_XDECREF(path);
3008 if (fdp == NULL) {
3009 if (!PyErr_ExceptionMatches(PyExc_ImportError))
3010 return NULL;
3011 PyErr_Clear();
3012 Py_INCREF(Py_None);
3013 return Py_None;
3014 }
3015 m = load_module(fullname, fp, buf, fdp->type, loader);
3016 Py_XDECREF(loader);
3017 if (fp)
3018 fclose(fp);
3019 if (!add_submodule(mod, m, fullname, subname, modules)) {
3020 Py_XDECREF(m);
3021 m = NULL;
3022 }
3023 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00003026}
3027
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003028
3029/* Re-import a module of any kind and return its module object, WITH
3030 INCREMENTED REFERENCE COUNT */
3031
Guido van Rossum79f25d91997-04-29 20:08:16 +00003032PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003033PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 PyInterpreterState *interp = PyThreadState_Get()->interp;
3036 PyObject *modules_reloading = interp->modules_reloading;
3037 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003038 PyObject *path = NULL, *loader, *existing_m = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 char *name, *subname;
3040 char buf[MAXPATHLEN+1];
3041 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003042 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 if (modules_reloading == NULL) {
3046 Py_FatalError("PyImport_ReloadModule: "
3047 "no modules_reloading dictionary!");
3048 return NULL;
3049 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (m == NULL || !PyModule_Check(m)) {
3052 PyErr_SetString(PyExc_TypeError,
3053 "reload() argument must be module");
3054 return NULL;
3055 }
3056 name = (char*)PyModule_GetName(m);
3057 if (name == NULL)
3058 return NULL;
3059 if (m != PyDict_GetItemString(modules, name)) {
3060 PyErr_Format(PyExc_ImportError,
3061 "reload(): module %.200s not in sys.modules",
3062 name);
3063 return NULL;
3064 }
3065 existing_m = PyDict_GetItemString(modules_reloading, name);
3066 if (existing_m != NULL) {
3067 /* Due to a recursive reload, this module is already
3068 being reloaded. */
3069 Py_INCREF(existing_m);
3070 return existing_m;
3071 }
3072 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
3073 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 subname = strrchr(name, '.');
3076 if (subname == NULL)
3077 subname = name;
3078 else {
3079 PyObject *parentname, *parent;
3080 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
3081 if (parentname == NULL) {
3082 imp_modules_reloading_clear();
3083 return NULL;
3084 }
3085 parent = PyDict_GetItem(modules, parentname);
3086 if (parent == NULL) {
3087 PyErr_Format(PyExc_ImportError,
3088 "reload(): parent %U not in sys.modules",
3089 parentname);
3090 Py_DECREF(parentname);
3091 imp_modules_reloading_clear();
3092 return NULL;
3093 }
3094 Py_DECREF(parentname);
3095 subname++;
3096 path = PyObject_GetAttrString(parent, "__path__");
3097 if (path == NULL)
3098 PyErr_Clear();
3099 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3101 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 if (fdp == NULL) {
3104 Py_XDECREF(loader);
3105 imp_modules_reloading_clear();
3106 return NULL;
3107 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 newm = load_module(name, fp, buf, fdp->type, loader);
3110 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 if (fp)
3113 fclose(fp);
3114 if (newm == NULL) {
3115 /* load_module probably removed name from modules because of
3116 * the error. Put back the original module object. We're
3117 * going to return NULL in this case regardless of whether
3118 * replacing name succeeds, so the return value is ignored.
3119 */
3120 PyDict_SetItemString(modules, name, m);
3121 }
3122 imp_modules_reloading_clear();
3123 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003124}
3125
3126
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003127/* Higher-level import emulator which emulates the "import" statement
3128 more accurately -- it invokes the __import__() function from the
3129 builtins of the current globals. This means that the import is
3130 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003131 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003132 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003133 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003134 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003135
3136PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003137PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 static PyObject *silly_list = NULL;
3140 static PyObject *builtins_str = NULL;
3141 static PyObject *import_str = NULL;
3142 PyObject *globals = NULL;
3143 PyObject *import = NULL;
3144 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003145 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* Initialize constant string objects */
3149 if (silly_list == NULL) {
3150 import_str = PyUnicode_InternFromString("__import__");
3151 if (import_str == NULL)
3152 return NULL;
3153 builtins_str = PyUnicode_InternFromString("__builtins__");
3154 if (builtins_str == NULL)
3155 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003156 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 if (silly_list == NULL)
3158 return NULL;
3159 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 /* Get the builtins from current globals */
3162 globals = PyEval_GetGlobals();
3163 if (globals != NULL) {
3164 Py_INCREF(globals);
3165 builtins = PyObject_GetItem(globals, builtins_str);
3166 if (builtins == NULL)
3167 goto err;
3168 }
3169 else {
3170 /* No globals -- use standard builtins, and fake globals */
3171 builtins = PyImport_ImportModuleLevel("builtins",
3172 NULL, NULL, NULL, 0);
3173 if (builtins == NULL)
3174 return NULL;
3175 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3176 if (globals == NULL)
3177 goto err;
3178 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 /* Get the __import__ function from the builtins */
3181 if (PyDict_Check(builtins)) {
3182 import = PyObject_GetItem(builtins, import_str);
3183 if (import == NULL)
3184 PyErr_SetObject(PyExc_KeyError, import_str);
3185 }
3186 else
3187 import = PyObject_GetAttr(builtins, import_str);
3188 if (import == NULL)
3189 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003192 Always use absolute import here.
3193 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3195 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003196 if (r == NULL)
3197 goto err;
3198 Py_DECREF(r);
3199
3200 modules = PyImport_GetModuleDict();
3201 r = PyDict_GetItem(modules, module_name);
3202 if (r != NULL)
3203 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003204
3205 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 Py_XDECREF(globals);
3207 Py_XDECREF(builtins);
3208 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003211}
3212
3213
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003214/* Module 'imp' provides Python access to the primitives used for
3215 importing modules.
3216*/
3217
Guido van Rossum79f25d91997-04-29 20:08:16 +00003218static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003219imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 buf[0] = (char) ((magic >> 0) & 0xff);
3224 buf[1] = (char) ((magic >> 8) & 0xff);
3225 buf[2] = (char) ((magic >> 16) & 0xff);
3226 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003229}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003230
3231static PyObject *
3232imp_get_magic(PyObject *self, PyObject *noargs)
3233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003235}
3236
3237static PyObject *
3238imp_get_tag(PyObject *self, PyObject *noargs)
3239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003241}
3242
Guido van Rossum79f25d91997-04-29 20:08:16 +00003243static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003244imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 PyObject *list;
3247 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 list = PyList_New(0);
3250 if (list == NULL)
3251 return NULL;
3252 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3253 PyObject *item = Py_BuildValue("ssi",
3254 fdp->suffix, fdp->mode, fdp->type);
3255 if (item == NULL) {
3256 Py_DECREF(list);
3257 return NULL;
3258 }
3259 if (PyList_Append(list, item) < 0) {
3260 Py_DECREF(list);
3261 Py_DECREF(item);
3262 return NULL;
3263 }
3264 Py_DECREF(item);
3265 }
3266 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003267}
3268
Guido van Rossum79f25d91997-04-29 20:08:16 +00003269static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003270call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 extern int fclose(FILE *);
3273 PyObject *fob, *ret;
3274 PyObject *pathobj;
3275 struct filedescr *fdp;
3276 char pathname[MAXPATHLEN+1];
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003277 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 int fd = -1;
3279 char *found_encoding = NULL;
3280 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 pathname[0] = '\0';
3283 if (path == Py_None)
3284 path = NULL;
3285 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3286 if (fdp == NULL)
3287 return NULL;
3288 if (fp != NULL) {
3289 fd = fileno(fp);
3290 if (fd != -1)
3291 fd = dup(fd);
3292 fclose(fp);
3293 fp = NULL;
3294 }
3295 if (fd != -1) {
3296 if (strchr(fdp->mode, 'b') == NULL) {
3297 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3298 memory. */
3299 found_encoding = PyTokenizer_FindEncoding(fd);
3300 lseek(fd, 0, 0); /* Reset position */
3301 if (found_encoding == NULL && PyErr_Occurred())
3302 return NULL;
3303 encoding = (found_encoding != NULL) ? found_encoding :
3304 (char*)PyUnicode_GetDefaultEncoding();
3305 }
3306 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3307 (char*)encoding, NULL, NULL, 1);
3308 if (fob == NULL) {
3309 close(fd);
3310 PyMem_FREE(found_encoding);
3311 return NULL;
3312 }
3313 }
3314 else {
3315 fob = Py_None;
3316 Py_INCREF(fob);
3317 }
3318 pathobj = PyUnicode_DecodeFSDefault(pathname);
3319 ret = Py_BuildValue("NN(ssi)",
3320 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3321 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003324}
3325
Guido van Rossum79f25d91997-04-29 20:08:16 +00003326static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003327imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003328{
Victor Stinnerebc00522010-12-03 17:06:43 +00003329 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 PyObject *ret, *path = NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003331 if (!PyArg_ParseTuple(args, "O&|O:find_module",
3332 PyUnicode_FSConverter, &name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 &path))
3334 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003335 ret = call_find_module(PyBytes_AS_STRING(name), path);
3336 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003338}
3339
3340static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003341imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003342{
Victor Stinner95872862011-03-07 18:20:56 +01003343 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 int ret;
3345 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003346 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 return NULL;
3348 ret = init_builtin(name);
3349 if (ret < 0)
3350 return NULL;
3351 if (ret == 0) {
3352 Py_INCREF(Py_None);
3353 return Py_None;
3354 }
Victor Stinner95872862011-03-07 18:20:56 +01003355 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 Py_XINCREF(m);
3357 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003358}
3359
Guido van Rossum79f25d91997-04-29 20:08:16 +00003360static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003361imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003362{
Victor Stinner53dc7352011-03-20 01:50:21 +01003363 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 int ret;
3365 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003366 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003368 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 if (ret < 0)
3370 return NULL;
3371 if (ret == 0) {
3372 Py_INCREF(Py_None);
3373 return Py_None;
3374 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003375 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 Py_XINCREF(m);
3377 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003378}
3379
Guido van Rossum79f25d91997-04-29 20:08:16 +00003380static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003381imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003382{
Victor Stinner53dc7352011-03-20 01:50:21 +01003383 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003384
Victor Stinner53dc7352011-03-20 01:50:21 +01003385 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 return NULL;
3387 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003388}
3389
Guido van Rossum79f25d91997-04-29 20:08:16 +00003390static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003391imp_is_frozen_package(PyObject *self, PyObject *args)
3392{
Victor Stinner53dc7352011-03-20 01:50:21 +01003393 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003394
Victor Stinner53dc7352011-03-20 01:50:21 +01003395 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 return NULL;
3397 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003398}
3399
3400static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003401imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003402{
Victor Stinner95872862011-03-07 18:20:56 +01003403 PyObject *name;
3404 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 return NULL;
3406 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003407}
3408
Guido van Rossum79f25d91997-04-29 20:08:16 +00003409static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003410imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003411{
Victor Stinner53dc7352011-03-20 01:50:21 +01003412 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003414 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 return NULL;
3416 p = find_frozen(name);
3417 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003418}
3419
3420static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003421get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 FILE *fp;
3424 if (mode[0] == 'U')
3425 mode = "r" PY_STDIOTEXTMODE;
3426 if (fob == NULL) {
3427 fp = fopen(pathname, mode);
3428 }
3429 else {
3430 int fd = PyObject_AsFileDescriptor(fob);
3431 if (fd == -1)
3432 return NULL;
3433 if (!_PyVerify_fd(fd))
3434 goto error;
3435 /* the FILE struct gets a new fd, so that it can be closed
3436 * independently of the file descriptor given
3437 */
3438 fd = dup(fd);
3439 if (fd == -1)
3440 goto error;
3441 fp = fdopen(fd, mode);
3442 }
3443 if (fp)
3444 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003445error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 PyErr_SetFromErrno(PyExc_IOError);
3447 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003448}
3449
Guido van Rossum79f25d91997-04-29 20:08:16 +00003450static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003451imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003454 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 PyObject *fob = NULL;
3456 PyObject *m;
3457 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003458 if (!PyArg_ParseTuple(args, "sO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003460 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 &fob))
3462 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003463 fp = get_file(PyBytes_AS_STRING(pathname), fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003465 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 return NULL;
3467 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003468 m = load_compiled_module(name, PyBytes_AS_STRING(pathname), fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003470 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003472}
3473
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003474#ifdef HAVE_DYNAMIC_LOADING
3475
Guido van Rossum79f25d91997-04-29 20:08:16 +00003476static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003477imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003478{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003479 PyObject *name, *pathname, *fob = NULL, *mod;
3480 FILE *fp;
3481
3482 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3483 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003485 if (fob != NULL) {
3486 fp = get_file(NULL, fob, "r");
3487 if (fp == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003490 else
3491 fp = NULL;
3492 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 if (fp)
3494 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003495 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003496}
3497
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003498#endif /* HAVE_DYNAMIC_LOADING */
3499
Guido van Rossum79f25d91997-04-29 20:08:16 +00003500static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003501imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003504 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 PyObject *fob = NULL;
3506 PyObject *m;
3507 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003508 if (!PyArg_ParseTuple(args, "sO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003510 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 &fob))
3512 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003513 fp = get_file(PyBytes_AS_STRING(pathname), fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003515 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 return NULL;
3517 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003518 m = load_source_module(name, PyBytes_AS_STRING(pathname), fp);
3519 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 fclose(fp);
3521 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003522}
3523
Guido van Rossum79f25d91997-04-29 20:08:16 +00003524static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003525imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 char *name;
3528 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003529 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 PyObject * ret;
3531 char *suffix; /* Unused */
3532 char *mode;
3533 int type;
3534 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003535
Victor Stinner1a563032010-10-15 22:43:10 +00003536 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003538 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 &suffix, &mode, &type))
3540 return NULL;
3541 if (*mode) {
3542 /* Mode must start with 'r' or 'U' and must not contain '+'.
3543 Implicit in this test is the assumption that the mode
3544 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3547 PyErr_Format(PyExc_ValueError,
3548 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003549 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 return NULL;
3551 }
3552 }
3553 if (fob == Py_None)
3554 fp = NULL;
3555 else {
3556 fp = get_file(NULL, fob, mode);
3557 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003558 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 return NULL;
3560 }
3561 }
Victor Stinner1a563032010-10-15 22:43:10 +00003562 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3563 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 if (fp)
3565 fclose(fp);
3566 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003567}
3568
3569static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003570imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003573 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 PyObject * ret;
Victor Stinnerebc00522010-12-03 17:06:43 +00003575 if (!PyArg_ParseTuple(args, "sO&:load_package",
3576 &name, PyUnicode_FSConverter, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003578 ret = load_package(name, PyBytes_AS_STRING(pathname));
3579 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003581}
3582
3583static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003584imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 char *name;
3587 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3588 return NULL;
3589 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003590}
3591
Christian Heimes13a7a212008-01-07 17:13:09 +00003592static PyObject *
3593imp_reload(PyObject *self, PyObject *v)
3594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003596}
3597
3598PyDoc_STRVAR(doc_reload,
3599"reload(module) -> module\n\
3600\n\
3601Reload the module. The module must have been successfully imported before.");
3602
Barry Warsaw28a691b2010-04-17 00:19:56 +00003603static PyObject *
3604imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003609 PyObject *pathbytes;
3610 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003611 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003615 args, kws, "O&|O", kwlist,
3616 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003618
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003619 if (debug_override != NULL &&
3620 (debug = PyObject_IsTrue(debug_override)) < 0) {
3621 Py_DECREF(pathbytes);
3622 return NULL;
3623 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003624
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003625 cpathname = make_compiled_pathname(
3626 PyBytes_AS_STRING(pathbytes),
3627 buf, MAXPATHLEN+1, debug);
3628 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 if (cpathname == NULL) {
3631 PyErr_Format(PyExc_SystemError, "path buffer too short");
3632 return NULL;
3633 }
Victor Stinner88bd8912010-10-15 22:46:07 +00003634 return PyUnicode_DecodeFSDefault(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003635}
3636
3637PyDoc_STRVAR(doc_cache_from_source,
3638"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3639\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;
3654 char buf[MAXPATHLEN+1];
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);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 if (make_source_pathname(pathname, buf) == NULL) {
3663 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3664 pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003665 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 return NULL;
3667 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003668 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003670}
3671
3672PyDoc_STRVAR(doc_source_from_cache,
3673"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3674\n\
3675The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3676the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3677does not conform to PEP 3147 format, ValueError will be raised.");
3678
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003679/* Doc strings */
3680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003681PyDoc_STRVAR(doc_imp,
3682"This module provides the components needed to build your own\n\
3683__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003684
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003685PyDoc_STRVAR(doc_find_module,
3686"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003687Search for a module. If path is omitted or None, search for a\n\
3688built-in, frozen or special module and continue search in sys.path.\n\
3689The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003690package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003692PyDoc_STRVAR(doc_load_module,
3693"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003694Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003695The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003697PyDoc_STRVAR(doc_get_magic,
3698"get_magic() -> string\n\
3699Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003700
Barry Warsaw28a691b2010-04-17 00:19:56 +00003701PyDoc_STRVAR(doc_get_tag,
3702"get_tag() -> string\n\
3703Return the magic tag for .pyc or .pyo files.");
3704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003705PyDoc_STRVAR(doc_get_suffixes,
3706"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003707Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003708that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003709
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003710PyDoc_STRVAR(doc_new_module,
3711"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003712Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003713The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003715PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003716"lock_held() -> boolean\n\
3717Return True if the import lock is currently held, else False.\n\
3718On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003719
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003720PyDoc_STRVAR(doc_acquire_lock,
3721"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003722Acquires the interpreter's import lock for the current thread.\n\
3723This lock should be used by import hooks to ensure thread-safety\n\
3724when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003725On platforms without threads, this function does nothing.");
3726
3727PyDoc_STRVAR(doc_release_lock,
3728"release_lock() -> None\n\
3729Release the interpreter's import lock.\n\
3730On platforms without threads, this function does nothing.");
3731
Guido van Rossum79f25d91997-04-29 20:08:16 +00003732static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3734 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3735 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3736 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3737 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3738 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3739 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3740 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3741 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3742 {"reload", imp_reload, METH_O, doc_reload},
3743 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3744 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3745 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3746 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3747 /* The rest are obsolete */
3748 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3749 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3750 {"init_builtin", imp_init_builtin, METH_VARARGS},
3751 {"init_frozen", imp_init_frozen, METH_VARARGS},
3752 {"is_builtin", imp_is_builtin, METH_VARARGS},
3753 {"is_frozen", imp_is_frozen, METH_VARARGS},
3754 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003755#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003757#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 {"load_package", imp_load_package, METH_VARARGS},
3759 {"load_source", imp_load_source, METH_VARARGS},
3760 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003761};
3762
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003763static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003764setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 PyObject *v;
3767 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 v = PyLong_FromLong((long)value);
3770 err = PyDict_SetItemString(d, name, v);
3771 Py_XDECREF(v);
3772 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003773}
3774
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003775typedef struct {
3776 PyObject_HEAD
3777} NullImporter;
3778
3779static int
3780NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3781{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003782#ifndef MS_WINDOWS
3783 PyObject *path;
3784 struct stat statbuf;
3785 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3788 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003789
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003790 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3791 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003793
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003794 if (PyBytes_GET_SIZE(path) == 0) {
3795 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 PyErr_SetString(PyExc_ImportError, "empty pathname");
3797 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003799
3800 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3801 Py_DECREF(path);
3802 if (rv == 0) {
3803 /* it exists */
3804 if (S_ISDIR(statbuf.st_mode)) {
3805 /* it's a directory */
3806 PyErr_SetString(PyExc_ImportError, "existing directory");
3807 return -1;
3808 }
3809 }
3810#else /* MS_WINDOWS */
3811 PyObject *pathobj;
3812 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003813 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003814
3815 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3816 return -1;
3817
3818 if (!PyArg_ParseTuple(args, "U:NullImporter",
3819 &pathobj))
3820 return -1;
3821
3822 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3823 PyErr_SetString(PyExc_ImportError, "empty pathname");
3824 return -1;
3825 }
3826
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003827 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003828 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003829 return -1;
3830 /* see issue1293 and issue3677:
3831 * stat() on Windows doesn't recognise paths like
3832 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3833 */
3834 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003835 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003836 if (rv != INVALID_FILE_ATTRIBUTES) {
3837 /* it exists */
3838 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3839 /* it's a directory */
3840 PyErr_SetString(PyExc_ImportError, "existing directory");
3841 return -1;
3842 }
3843 }
3844#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003846}
3847
3848static PyObject *
3849NullImporter_find_module(NullImporter *self, PyObject *args)
3850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003852}
3853
3854static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3856 "Always return None"
3857 },
3858 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003859};
3860
3861
Christian Heimes9cd17752007-11-18 19:35:23 +00003862PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 PyVarObject_HEAD_INIT(NULL, 0)
3864 "imp.NullImporter", /*tp_name*/
3865 sizeof(NullImporter), /*tp_basicsize*/
3866 0, /*tp_itemsize*/
3867 0, /*tp_dealloc*/
3868 0, /*tp_print*/
3869 0, /*tp_getattr*/
3870 0, /*tp_setattr*/
3871 0, /*tp_reserved*/
3872 0, /*tp_repr*/
3873 0, /*tp_as_number*/
3874 0, /*tp_as_sequence*/
3875 0, /*tp_as_mapping*/
3876 0, /*tp_hash */
3877 0, /*tp_call*/
3878 0, /*tp_str*/
3879 0, /*tp_getattro*/
3880 0, /*tp_setattro*/
3881 0, /*tp_as_buffer*/
3882 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3883 "Null importer object", /* tp_doc */
3884 0, /* tp_traverse */
3885 0, /* tp_clear */
3886 0, /* tp_richcompare */
3887 0, /* tp_weaklistoffset */
3888 0, /* tp_iter */
3889 0, /* tp_iternext */
3890 NullImporter_methods, /* tp_methods */
3891 0, /* tp_members */
3892 0, /* tp_getset */
3893 0, /* tp_base */
3894 0, /* tp_dict */
3895 0, /* tp_descr_get */
3896 0, /* tp_descr_set */
3897 0, /* tp_dictoffset */
3898 (initproc)NullImporter_init, /* tp_init */
3899 0, /* tp_alloc */
3900 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003901};
3902
Martin v. Löwis1a214512008-06-11 05:26:20 +00003903static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 PyModuleDef_HEAD_INIT,
3905 "imp",
3906 doc_imp,
3907 0,
3908 imp_methods,
3909 NULL,
3910 NULL,
3911 NULL,
3912 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003913};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003914
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003915PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003916PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 if (PyType_Ready(&PyNullImporter_Type) < 0)
3921 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 m = PyModule_Create(&impmodule);
3924 if (m == NULL)
3925 goto failure;
3926 d = PyModule_GetDict(m);
3927 if (d == NULL)
3928 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3931 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3932 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3933 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3934 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3935 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3936 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3937 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3938 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3939 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 Py_INCREF(&PyNullImporter_Type);
3942 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3943 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003944 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 Py_XDECREF(m);
3946 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003947}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003948
3949
Guido van Rossumb18618d2000-05-03 23:44:39 +00003950/* API for embedding applications that want to add their own entries
3951 to the table of built-in modules. This should normally be called
3952 *before* Py_Initialize(). When the table resize fails, -1 is
3953 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003954
3955 After a similar function by Just van Rossum. */
3956
3957int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003958PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 static struct _inittab *our_copy = NULL;
3961 struct _inittab *p;
3962 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 /* Count the number of entries in both tables */
3965 for (n = 0; newtab[n].name != NULL; n++)
3966 ;
3967 if (n == 0)
3968 return 0; /* Nothing to do */
3969 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3970 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 /* Allocate new memory for the combined table */
3973 p = our_copy;
3974 PyMem_RESIZE(p, struct _inittab, i+n+1);
3975 if (p == NULL)
3976 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 /* Copy the tables into the new memory */
3979 if (our_copy != PyImport_Inittab)
3980 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3981 PyImport_Inittab = our_copy = p;
3982 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003985}
3986
3987/* Shorthand to add a single entry given a name and a function */
3988
3989int
Brett Cannona826f322009-04-02 03:41:46 +00003990PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 newtab[0].name = (char *)name;
3997 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004000}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004001
4002#ifdef __cplusplus
4003}
4004#endif