blob: 2adcb04674113b0de3b68fdb1402347fab7b26f9 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000011#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000012#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013
Guido van Rossum55a83382000-09-20 20:31:38 +000014#ifdef HAVE_FCNTL_H
15#include <fcntl.h>
16#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000018extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000020
Christian Heimesd3eb5a152008-02-24 00:38:49 +000021#ifdef MS_WINDOWS
22/* for stat.st_mode */
23typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000024/* for _mkdir */
25#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000026#endif
27
Guido van Rossum21d335e1993-10-15 13:01:11 +000028
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000029/* Magic word to reject .pyc files generated by other Python versions.
30 It should change for each incompatible change to the bytecode.
31
32 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000033 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000034 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000035
Guido van Rossum45aecf42006-03-15 04:58:47 +000036 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000037 -U interpeter flag will cause MAGIC+1 being used. They have been
38 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000040 There were a variety of old schemes for setting the magic number.
41 The current working scheme is to increment the previous value by
42 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000043
Barry Warsaw28a691b2010-04-17 00:19:56 +000044 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
45 number also includes a new "magic tag", i.e. a human readable string used
46 to represent the magic number in __pycache__ directories. When you change
47 the magic number, you must also set a new unique magic tag. Generally this
48 can be named after the Python major version of the magic number bump, but
49 it can really be anything, as long as it's different than anything else
50 that's come before. The tags are included in the following table, starting
51 with Python 3.2a0.
52
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Known values:
54 Python 1.5: 20121
55 Python 1.5.1: 20121
56 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000058 Python 2.0: 50823
59 Python 2.0.1: 50823
60 Python 2.1: 60202
61 Python 2.1.1: 60202
62 Python 2.1.2: 60202
63 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000064 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000065 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000066 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000067 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000068 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000069 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000070 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000071 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000072 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000073 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
75 Python 2.5b3: 62111 (fix wrong code: x += yield)
76 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000078 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000079 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000081 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 3010 (removed UNARY_CONVERT)
83 3020 (added BUILD_SET)
84 3030 (added keyword-only parameters)
85 3040 (added signature annotations)
86 3050 (print becomes a function)
87 3060 (PEP 3115 metaclass syntax)
88 3061 (string literals become unicode)
89 3071 (PEP 3109 raise changes)
90 3081 (PEP 3137 make __file__ and __name__ unicode)
91 3091 (kill str8 interning)
92 3101 (merge from 2.6a0, see 62151)
93 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000094 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
95 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
96 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000100 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000102 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
103 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000104 Python 3.2a2 3180 (add DELETE_DEREF)
Tim Peters36515e22001-11-18 04:06:29 +0000105*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000106
Nick Coghlancd419ab2010-09-11 00:39:25 +0000107/* MAGIC must change whenever the bytecode emitted by the compiler may no
108 longer be understood by older implementations of the eval loop (usually
109 due to the addition of new opcodes)
110 TAG must change for each major Python release. The magic number will take
111 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112*/
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000113#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114#define TAG "cpython-32"
115#define CACHEDIR "__pycache__"
116/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000117static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000119
Victor Stinner49d3f252010-10-17 01:24:53 +0000120/* See _PyImport_FixupExtensionUnicode() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000122
Guido van Rossum771c6c81997-10-31 18:37:24 +0000123/* This table is defined in config.c: */
124extern struct _inittab _PyImport_Inittab[];
125
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000126/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000127extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000128
Guido van Rossum771c6c81997-10-31 18:37:24 +0000129struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000130
Guido van Rossumed1170e1999-12-20 21:23:41 +0000131/* these tables define the module suffixes that Python recognizes */
132struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000133
Guido van Rossumed1170e1999-12-20 21:23:41 +0000134static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000136#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 {".pyc", "rb", PY_COMPILED},
140 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000141};
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000144/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145
146void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000147_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 const struct filedescr *scan;
150 struct filedescr *filetab;
151 int countD = 0;
152 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 /* prepare _PyImport_Filetab: copy entries from
155 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
156 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000157#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
159 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
162 ++countS;
163 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
164 if (filetab == NULL)
165 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000166#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 memcpy(filetab, _PyImport_DynLoadFiletab,
168 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000169#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 memcpy(filetab + countD, _PyImport_StandardFiletab,
171 countS * sizeof(struct filedescr));
172 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (Py_OptimizeFlag) {
177 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
178 for (; filetab->suffix != NULL; filetab++) {
179 if (strcmp(filetab->suffix, ".pyc") == 0)
180 filetab->suffix = ".pyo";
181 }
182 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185void
Just van Rossum52e14d62002-12-30 22:08:05 +0000186_PyImportHooks_Init(void)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyObject *v, *path_hooks = NULL, *zimpimport;
189 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* adding sys.path_hooks and sys.path_importer_cache, setting up
192 zipimport */
193 if (PyType_Ready(&PyNullImporter_Type) < 0)
194 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (Py_VerboseFlag)
197 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 v = PyList_New(0);
200 if (v == NULL)
201 goto error;
202 err = PySys_SetObject("meta_path", v);
203 Py_DECREF(v);
204 if (err)
205 goto error;
206 v = PyDict_New();
207 if (v == NULL)
208 goto error;
209 err = PySys_SetObject("path_importer_cache", v);
210 Py_DECREF(v);
211 if (err)
212 goto error;
213 path_hooks = PyList_New(0);
214 if (path_hooks == NULL)
215 goto error;
216 err = PySys_SetObject("path_hooks", path_hooks);
217 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000218 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 PyErr_Print();
220 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
221 "path_importer_cache, or NullImporter failed"
222 );
223 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 zimpimport = PyImport_ImportModule("zipimport");
226 if (zimpimport == NULL) {
227 PyErr_Clear(); /* No zip import module -- okay */
228 if (Py_VerboseFlag)
229 PySys_WriteStderr("# can't import zipimport\n");
230 }
231 else {
232 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
233 "zipimporter");
234 Py_DECREF(zimpimport);
235 if (zipimporter == NULL) {
236 PyErr_Clear(); /* No zipimporter object -- okay */
237 if (Py_VerboseFlag)
238 PySys_WriteStderr(
239 "# can't import zipimport.zipimporter\n");
240 }
241 else {
242 /* sys.path_hooks.append(zipimporter) */
243 err = PyList_Append(path_hooks, zipimporter);
244 Py_DECREF(zipimporter);
245 if (err)
246 goto error;
247 if (Py_VerboseFlag)
248 PySys_WriteStderr(
249 "# installed zipimport hook\n");
250 }
251 }
252 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000253}
254
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);
332 /* XXX: can the previous line fail? */
333 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;
421 char *name;
422 PyObject *key, *value, *dict;
423 PyInterpreterState *interp = PyThreadState_GET()->interp;
424 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (modules == NULL)
427 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Delete some special variables first. These are common
430 places where user values hide and people complain when their
431 destructors fail. Since the modules containing them are
432 deleted *last* of all, they would come too late in the normal
433 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 value = PyDict_GetItemString(modules, "builtins");
436 if (value != NULL && PyModule_Check(value)) {
437 dict = PyModule_GetDict(value);
438 if (Py_VerboseFlag)
439 PySys_WriteStderr("# clear builtins._\n");
440 PyDict_SetItemString(dict, "_", Py_None);
441 }
442 value = PyDict_GetItemString(modules, "sys");
443 if (value != NULL && PyModule_Check(value)) {
444 char **p;
445 PyObject *v;
446 dict = PyModule_GetDict(value);
447 for (p = sys_deletes; *p != NULL; p++) {
448 if (Py_VerboseFlag)
449 PySys_WriteStderr("# clear sys.%s\n", *p);
450 PyDict_SetItemString(dict, *p, Py_None);
451 }
452 for (p = sys_files; *p != NULL; p+=2) {
453 if (Py_VerboseFlag)
454 PySys_WriteStderr("# restore sys.%s\n", *p);
455 v = PyDict_GetItemString(dict, *(p+1));
456 if (v == NULL)
457 v = Py_None;
458 PyDict_SetItemString(dict, *p, v);
459 }
460 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* First, delete __main__ */
463 value = PyDict_GetItemString(modules, "__main__");
464 if (value != NULL && PyModule_Check(value)) {
465 if (Py_VerboseFlag)
466 PySys_WriteStderr("# cleanup __main__\n");
467 _PyModule_Clear(value);
468 PyDict_SetItemString(modules, "__main__", Py_None);
469 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* The special treatment of "builtins" here is because even
472 when it's not referenced as a module, its dictionary is
473 referenced by almost every module's __builtins__. Since
474 deleting a module clears its dictionary (even if there are
475 references left to it), we need to delete the "builtins"
476 module last. Likewise, we don't delete sys until the very
477 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Also note that we 'delete' modules by replacing their entry
480 in the modules dict with None, rather than really deleting
481 them; this avoids a rehash of the modules dictionary and
482 also marks them as "non existent" so they won't be
483 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Next, repeatedly delete modules with a reference count of
486 one (skipping builtins and sys) and delete them */
487 do {
488 ndone = 0;
489 pos = 0;
490 while (PyDict_Next(modules, &pos, &key, &value)) {
491 if (value->ob_refcnt != 1)
492 continue;
493 if (PyUnicode_Check(key) && PyModule_Check(value)) {
494 name = _PyUnicode_AsString(key);
495 if (strcmp(name, "builtins") == 0)
496 continue;
497 if (strcmp(name, "sys") == 0)
498 continue;
499 if (Py_VerboseFlag)
500 PySys_WriteStderr(
501 "# cleanup[1] %s\n", name);
502 _PyModule_Clear(value);
503 PyDict_SetItem(modules, key, Py_None);
504 ndone++;
505 }
506 }
507 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Next, delete all modules (still skipping builtins and sys) */
510 pos = 0;
511 while (PyDict_Next(modules, &pos, &key, &value)) {
512 if (PyUnicode_Check(key) && PyModule_Check(value)) {
513 name = _PyUnicode_AsString(key);
514 if (strcmp(name, "builtins") == 0)
515 continue;
516 if (strcmp(name, "sys") == 0)
517 continue;
518 if (Py_VerboseFlag)
519 PySys_WriteStderr("# cleanup[2] %s\n", name);
520 _PyModule_Clear(value);
521 PyDict_SetItem(modules, key, Py_None);
522 }
523 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Next, delete sys and builtins (in that order) */
526 value = PyDict_GetItemString(modules, "sys");
527 if (value != NULL && PyModule_Check(value)) {
528 if (Py_VerboseFlag)
529 PySys_WriteStderr("# cleanup sys\n");
530 _PyModule_Clear(value);
531 PyDict_SetItemString(modules, "sys", Py_None);
532 }
533 value = PyDict_GetItemString(modules, "builtins");
534 if (value != NULL && PyModule_Check(value)) {
535 if (Py_VerboseFlag)
536 PySys_WriteStderr("# cleanup builtins\n");
537 _PyModule_Clear(value);
538 PyDict_SetItemString(modules, "builtins", Py_None);
539 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 /* Finally, clear and delete the modules directory */
542 PyDict_Clear(modules);
543 interp->modules = NULL;
544 Py_DECREF(modules);
545 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000546}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000547
548
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550
551long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000552PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555}
556
557
Barry Warsaw28a691b2010-04-17 00:19:56 +0000558const char *
559PyImport_GetMagicTag(void)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000562}
563
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564/* Magic for extension modules (built-in as well as dynamically
565 loaded). To prevent initializing an extension module more than
566 once, we keep a static dictionary 'extensions' keyed by module name
567 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000568 modules), containing these modules. A copy of the module's
Victor Stinner49d3f252010-10-17 01:24:53 +0000569 dictionary is stored by calling _PyImport_FixupExtensionUnicode()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570 immediately after the module initialization function succeeds. A
571 copy can be retrieved from there by calling
Victor Stinner49d3f252010-10-17 01:24:53 +0000572 _PyImport_FindExtensionUnicode().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000574 Modules which do support multiple initialization set their m_size
575 field to a non-negative number (indicating the size of the
576 module-specific state). They are still recorded in the extensions
577 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000578*/
579
580int
Victor Stinner49d3f252010-10-17 01:24:53 +0000581_PyImport_FixupExtensionUnicode(PyObject *mod, char *name, PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyObject *modules, *dict;
584 struct PyModuleDef *def;
585 if (extensions == NULL) {
586 extensions = PyDict_New();
587 if (extensions == NULL)
588 return -1;
589 }
590 if (mod == NULL || !PyModule_Check(mod)) {
591 PyErr_BadInternalCall();
592 return -1;
593 }
594 def = PyModule_GetDef(mod);
595 if (!def) {
596 PyErr_BadInternalCall();
597 return -1;
598 }
599 modules = PyImport_GetModuleDict();
600 if (PyDict_SetItemString(modules, name, mod) < 0)
601 return -1;
602 if (_PyState_AddModule(mod, def) < 0) {
603 PyDict_DelItemString(modules, name);
604 return -1;
605 }
606 if (def->m_size == -1) {
607 if (def->m_base.m_copy) {
608 /* Somebody already imported the module,
609 likely under a different name.
610 XXX this should really not happen. */
611 Py_DECREF(def->m_base.m_copy);
612 def->m_base.m_copy = NULL;
613 }
614 dict = PyModule_GetDict(mod);
615 if (dict == NULL)
616 return -1;
617 def->m_base.m_copy = PyDict_Copy(dict);
618 if (def->m_base.m_copy == NULL)
619 return -1;
620 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000621 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623}
624
Victor Stinner49d3f252010-10-17 01:24:53 +0000625int
626_PyImport_FixupBuiltin(PyObject *mod, char *name)
627{
628 int res;
629 PyObject *filename;
630 filename = PyUnicode_FromString(name);
631 if (filename == NULL)
632 return -1;
633 res = _PyImport_FixupExtensionUnicode(mod, name, filename);
634 Py_DECREF(filename);
635 return res;
636}
637
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638PyObject *
Victor Stinner49d3f252010-10-17 01:24:53 +0000639_PyImport_FindExtensionUnicode(char *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *mod, *mdict;
642 PyModuleDef* def;
643 if (extensions == NULL)
644 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000645 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (def == NULL)
647 return NULL;
648 if (def->m_size == -1) {
649 /* Module does not support repeated initialization */
650 if (def->m_base.m_copy == NULL)
651 return NULL;
652 mod = PyImport_AddModule(name);
653 if (mod == NULL)
654 return NULL;
655 mdict = PyModule_GetDict(mod);
656 if (mdict == NULL)
657 return NULL;
658 if (PyDict_Update(mdict, def->m_base.m_copy))
659 return NULL;
660 }
661 else {
662 if (def->m_base.m_init == NULL)
663 return NULL;
664 mod = def->m_base.m_init();
665 if (mod == NULL)
666 return NULL;
667 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
668 Py_DECREF(mod);
669 }
670 if (_PyState_AddModule(mod, def) < 0) {
671 PyDict_DelItemString(PyImport_GetModuleDict(), name);
672 Py_DECREF(mod);
673 return NULL;
674 }
675 if (Py_VerboseFlag)
Victor Stinner49d3f252010-10-17 01:24:53 +0000676 PySys_FormatStderr("import %s # previously loaded (%U)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 name, filename);
678 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000679
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680}
681
Victor Stinner49d3f252010-10-17 01:24:53 +0000682PyObject *
683_PyImport_FindBuiltin(char *name)
684{
685 PyObject *res, *filename;
686 filename = PyUnicode_FromString(name);
687 if (filename == NULL)
688 return NULL;
689 res = _PyImport_FindExtensionUnicode(name, filename);
690 Py_DECREF(filename);
691 return res;
692}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693
694/* Get the module object corresponding to a module name.
695 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000696 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000697 Because the former action is most common, THIS DOES NOT RETURN A
698 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000699
Guido van Rossum79f25d91997-04-29 20:08:16 +0000700PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000701PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyObject *modules = PyImport_GetModuleDict();
704 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
707 PyModule_Check(m))
708 return m;
709 m = PyModule_New(name);
710 if (m == NULL)
711 return NULL;
712 if (PyDict_SetItemString(modules, name, m) != 0) {
713 Py_DECREF(m);
714 return NULL;
715 }
716 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000719}
720
Tim Peters1cd70172004-08-02 03:52:12 +0000721/* Remove name from sys.modules, if it's there. */
722static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000723remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyObject *modules = PyImport_GetModuleDict();
726 if (PyDict_GetItemString(modules, name) == NULL)
727 return;
728 if (PyDict_DelItemString(modules, name) < 0)
729 Py_FatalError("import: deleting existing key in"
730 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000731}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000732
Barry Warsaw28a691b2010-04-17 00:19:56 +0000733static PyObject * get_sourcefile(char *file);
734static char *make_source_pathname(char *pathname, char *buf);
735static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000737
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000738/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000739 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
740 * removed from sys.modules, to avoid leaving damaged module objects
741 * in sys.modules. The caller may wish to restore the original
742 * module object (if any) in this case; PyImport_ReloadModule is an
743 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000744 *
745 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
746 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000747 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000748PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000749PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 return PyImport_ExecCodeModuleWithPathnames(
752 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000753}
754
755PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 return PyImport_ExecCodeModuleWithPathnames(
759 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000760}
761
762PyObject *
763PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyObject *modules = PyImport_GetModuleDict();
767 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 m = PyImport_AddModule(name);
770 if (m == NULL)
771 return NULL;
772 /* If the module is being reloaded, we get the old module back
773 and re-use its dict to exec the new code. */
774 d = PyModule_GetDict(m);
775 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
776 if (PyDict_SetItemString(d, "__builtins__",
777 PyEval_GetBuiltins()) != 0)
778 goto error;
779 }
780 /* Remember the filename as the __file__ attribute */
781 v = NULL;
782 if (pathname != NULL) {
783 v = get_sourcefile(pathname);
784 if (v == NULL)
785 PyErr_Clear();
786 }
787 if (v == NULL) {
788 v = ((PyCodeObject *)co)->co_filename;
789 Py_INCREF(v);
790 }
791 if (PyDict_SetItemString(d, "__file__", v) != 0)
792 PyErr_Clear(); /* Not important enough to report */
793 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 /* Remember the pyc path name as the __cached__ attribute. */
796 if (cpathname == NULL) {
797 v = Py_None;
798 Py_INCREF(v);
799 }
800 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
801 PyErr_Clear(); /* Not important enough to report */
802 v = Py_None;
803 Py_INCREF(v);
804 }
805 if (PyDict_SetItemString(d, "__cached__", v) != 0)
806 PyErr_Clear(); /* Not important enough to report */
807 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000808
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000809 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (v == NULL)
811 goto error;
812 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
815 PyErr_Format(PyExc_ImportError,
816 "Loaded module %.200s not found in sys.modules",
817 name);
818 return NULL;
819 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000824
825 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 remove_module(name);
827 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000828}
829
830
Barry Warsaw28a691b2010-04-17 00:19:56 +0000831/* Like strrchr(string, '/') but searches for the rightmost of either SEP
832 or ALTSEP, if the latter is defined.
833*/
834static char *
835rightmost_sep(char *s)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 char *found, c;
838 for (found = NULL; (c = *s); s++) {
839 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000840#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000842#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 )
844 {
845 found = s;
846 }
847 }
848 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000849}
850
851
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000852/* Given a pathname for a Python source file, fill a buffer with the
853 pathname for the corresponding compiled file. Return the pathname
854 for the compiled file, or NULL if there's no space in the buffer.
855 Doesn't set an exception. */
856
857static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000858make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* foo.py -> __pycache__/foo.<tag>.pyc */
861 size_t len = strlen(pathname);
862 size_t i, save;
863 char *pos;
864 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 /* Sanity check that the buffer has roughly enough space to hold what
867 will eventually be the full path to the compiled file. The 5 extra
868 bytes include the slash afer __pycache__, the two extra dots, the
869 extra trailing character ('c' or 'o') and null. This isn't exact
870 because the contents of the buffer can affect how many actual
871 characters of the string get into the buffer. We'll do a final
872 sanity check before writing the extension to ensure we do not
873 overflow the buffer.
874 */
875 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
876 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 /* Find the last path separator and copy everything from the start of
879 the source string up to and including the separator.
880 */
881 if ((pos = rightmost_sep(pathname)) == NULL) {
882 i = 0;
883 }
884 else {
885 sep = *pos;
886 i = pos - pathname + 1;
887 strncpy(buf, pathname, i);
888 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 save = i;
891 buf[i++] = '\0';
892 /* Add __pycache__/ */
893 strcat(buf, CACHEDIR);
894 i += strlen(CACHEDIR) - 1;
895 buf[i++] = sep;
896 buf[i++] = '\0';
897 /* Add the base filename, but remove the .py or .pyw extension, since
898 the tag name must go before the extension.
899 */
900 strcat(buf, pathname + save);
901 if ((pos = strrchr(buf, '.')) != NULL)
902 *++pos = '\0';
903 strcat(buf, pyc_tag);
904 /* The length test above assumes that we're only adding one character
905 to the end of what would normally be the extension. What if there
906 is no extension, or the string ends in '.' or '.p', and otherwise
907 fills the buffer? By appending 4 more characters onto the string
908 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 As a simple example, let's say buflen=32 and the input string is
911 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 which is false and so the name mangling would continue. This would
916 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
921 We can even handle an input string of say 'xxxxx' above because
922 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
923 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 which is 32 characters including the nul, and thus fits in the
928 buffer. However, an input string of 'xxxxxx' would yield a result
929 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 which is 33 characters long (including the nul), thus overflowing
934 the buffer, even though the first test would fail, i.e.: the input
935 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 The reason the first test fails but we still overflow the buffer is
938 that the test above only expects to add one extra character to be
939 added to the extension, and here we're adding three (pyc). We
940 don't add the first dot, so that reclaims one of expected
941 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
942 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 The best we can do is ensure that we still have enough room in the
945 target buffer before we write the extension. Because it's always
946 only the extension that can cause the overflow, and never the other
947 path bytes we've written, it's sufficient to just do one more test
948 here. Still, the assertion that follows can't hurt.
949 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000950#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000952#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (strlen(buf) + 5 > buflen)
954 return NULL;
955 strcat(buf, debug ? ".pyc" : ".pyo");
956 assert(strlen(buf) < buflen);
957 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000958}
959
960
Barry Warsaw28a691b2010-04-17 00:19:56 +0000961/* Given a pathname to a Python byte compiled file, return the path to the
962 source file, if the path matches the PEP 3147 format. This does not check
963 for any file existence, however, if the pyc file name does not match PEP
964 3147 style, NULL is returned. buf must be at least as big as pathname;
965 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966
Barry Warsaw28a691b2010-04-17 00:19:56 +0000967static char *
968make_source_pathname(char *pathname, char *buf)
969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* __pycache__/foo.<tag>.pyc -> foo.py */
971 size_t i, j;
972 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* Look back two slashes from the end. In between these two slashes
975 must be the string __pycache__ or this is not a PEP 3147 style
976 path. It's possible for there to be only one slash.
977 */
978 if ((right = rightmost_sep(pathname)) == NULL)
979 return NULL;
980 sep = *right;
981 *right = '\0';
982 left = rightmost_sep(pathname);
983 *right = sep;
984 if (left == NULL)
985 left = pathname;
986 else
987 left++;
988 if (right-left != strlen(CACHEDIR) ||
989 strncmp(left, CACHEDIR, right-left) != 0)
990 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 /* Now verify that the path component to the right of the last slash
993 has two dots in it.
994 */
995 if ((dot0 = strchr(right + 1, '.')) == NULL)
996 return NULL;
997 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
998 return NULL;
999 /* Too many dots? */
1000 if (strchr(dot1 + 1, '.') != NULL)
1001 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 /* This is a PEP 3147 path. Start by copying everything from the
1004 start of pathname up to and including the leftmost slash. Then
1005 copy the file's basename, removing the magic tag and adding a .py
1006 suffix.
1007 */
1008 strncpy(buf, pathname, (i=left-pathname));
1009 strncpy(buf+i, right+1, (j=dot0-right));
1010 strcpy(buf+i+j, "py");
1011 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001012}
1013
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001014/* Given a pathname for a Python source file, its time of last
1015 modification, and a pathname for a compiled file, check whether the
1016 compiled file represents the same version of the source. If so,
1017 return a FILE pointer for the compiled file, positioned just after
1018 the header; if not, return NULL.
1019 Doesn't set an exception. */
1020
1021static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001022check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 FILE *fp;
1025 long magic;
1026 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 fp = fopen(cpathname, "rb");
1029 if (fp == NULL)
1030 return NULL;
1031 magic = PyMarshal_ReadLongFromFile(fp);
1032 if (magic != pyc_magic) {
1033 if (Py_VerboseFlag)
1034 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1035 fclose(fp);
1036 return NULL;
1037 }
1038 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1039 if (pyc_mtime != mtime) {
1040 if (Py_VerboseFlag)
1041 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1042 fclose(fp);
1043 return NULL;
1044 }
1045 if (Py_VerboseFlag)
1046 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1047 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048}
1049
1050
1051/* Read a code object from a file and check it for validity */
1052
Guido van Rossum79f25d91997-04-29 20:08:16 +00001053static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001054read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 co = PyMarshal_ReadLastObjectFromFile(fp);
1059 if (co == NULL)
1060 return NULL;
1061 if (!PyCode_Check(co)) {
1062 PyErr_Format(PyExc_ImportError,
1063 "Non-code object in %.200s", cpathname);
1064 Py_DECREF(co);
1065 return NULL;
1066 }
1067 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068}
1069
1070
1071/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001072 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001073
Guido van Rossum79f25d91997-04-29 20:08:16 +00001074static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001075load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 long magic;
1078 PyCodeObject *co;
1079 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 magic = PyMarshal_ReadLongFromFile(fp);
1082 if (magic != pyc_magic) {
1083 PyErr_Format(PyExc_ImportError,
1084 "Bad magic number in %.200s", cpathname);
1085 return NULL;
1086 }
1087 (void) PyMarshal_ReadLongFromFile(fp);
1088 co = read_compiled_module(cpathname, fp);
1089 if (co == NULL)
1090 return NULL;
1091 if (Py_VerboseFlag)
1092 PySys_WriteStderr("import %s # precompiled from %s\n",
1093 name, cpathname);
1094 m = PyImport_ExecCodeModuleWithPathnames(
1095 name, (PyObject *)co, cpathname, cpathname);
1096 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001099}
1100
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001101/* Parse a source file and return the corresponding code object */
1102
Guido van Rossum79f25d91997-04-29 20:08:16 +00001103static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001104parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 PyCodeObject *co = NULL;
1107 mod_ty mod;
1108 PyCompilerFlags flags;
1109 PyArena *arena = PyArena_New();
1110 if (arena == NULL)
1111 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 flags.cf_flags = 0;
1114 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1115 Py_file_input, 0, 0, &flags,
1116 NULL, arena);
1117 if (mod) {
1118 co = PyAST_Compile(mod, pathname, NULL, arena);
1119 }
1120 PyArena_Free(arena);
1121 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122}
1123
1124
Guido van Rossum55a83382000-09-20 20:31:38 +00001125/* Helper to open a bytecode file for writing in exclusive mode */
1126
1127static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001128open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001129{
1130#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* Use O_EXCL to avoid a race condition when another process tries to
1132 write the same file. When that happens, our open() call fails,
1133 which is just fine (since it's only a cache).
1134 XXX If the file exists and is writable but the directory is not
1135 writable, the file will never be written. Oh well.
1136 */
1137 int fd;
1138 (void) unlink(filename);
1139 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001140#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001142#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001143#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001145#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001147#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 );
1149 if (fd < 0)
1150 return NULL;
1151 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001152#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Best we can do -- on Windows this can't happen anyway */
1154 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001155#endif
1156}
1157
1158
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001159/* Write a compiled module to a file, placing the time of last
1160 modification of its source into the header.
1161 Errors are ignored, if a write error occurs an attempt is made to
1162 remove the file. */
1163
1164static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001165write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 FILE *fp;
1168 char *dirpath;
1169 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001170#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001172#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1174 mode_t dirmode = (srcstat->st_mode |
1175 S_IXUSR | S_IXGRP | S_IXOTH |
1176 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 /* Ensure that the __pycache__ directory exists. */
1181 dirpath = rightmost_sep(cpathname);
1182 if (dirpath == NULL) {
1183 if (Py_VerboseFlag)
1184 PySys_WriteStderr(
1185 "# no %s path found %s\n",
1186 CACHEDIR, cpathname);
1187 return;
1188 }
1189 saved = *dirpath;
1190 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001191
1192#ifdef MS_WINDOWS
1193 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1194#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001196#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 *dirpath = saved;
1198 if (Py_VerboseFlag)
1199 PySys_WriteStderr(
1200 "# cannot create cache dir %s\n", cpathname);
1201 return;
1202 }
1203 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 fp = open_exclusive(cpathname, mode);
1206 if (fp == NULL) {
1207 if (Py_VerboseFlag)
1208 PySys_WriteStderr(
1209 "# can't create %s\n", cpathname);
1210 return;
1211 }
1212 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1213 /* First write a 0 for mtime */
1214 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1215 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1216 if (fflush(fp) != 0 || ferror(fp)) {
1217 if (Py_VerboseFlag)
1218 PySys_WriteStderr("# can't write %s\n", cpathname);
1219 /* Don't keep partial file */
1220 fclose(fp);
1221 (void) unlink(cpathname);
1222 return;
1223 }
1224 /* Now write the true mtime */
1225 fseek(fp, 4L, 0);
1226 assert(mtime < LONG_MAX);
1227 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1228 fflush(fp);
1229 fclose(fp);
1230 if (Py_VerboseFlag)
1231 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001232}
1233
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001234static void
1235update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyObject *constants, *tmp;
1238 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (PyUnicode_Compare(co->co_filename, oldname))
1241 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 tmp = co->co_filename;
1244 co->co_filename = newname;
1245 Py_INCREF(co->co_filename);
1246 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 constants = co->co_consts;
1249 n = PyTuple_GET_SIZE(constants);
1250 for (i = 0; i < n; i++) {
1251 tmp = PyTuple_GET_ITEM(constants, i);
1252 if (PyCode_Check(tmp))
1253 update_code_filenames((PyCodeObject *)tmp,
1254 oldname, newname);
1255 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001256}
1257
1258static int
1259update_compiled_module(PyCodeObject *co, char *pathname)
1260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 newname = PyUnicode_DecodeFSDefault(pathname);
1264 if (newname == NULL)
1265 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (!PyUnicode_Compare(co->co_filename, newname)) {
1268 Py_DECREF(newname);
1269 return 0;
1270 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 oldname = co->co_filename;
1273 Py_INCREF(oldname);
1274 update_code_filenames(co, oldname, newname);
1275 Py_DECREF(oldname);
1276 Py_DECREF(newname);
1277 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001278}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001279
1280/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001281 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1282 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001283
Guido van Rossum79f25d91997-04-29 20:08:16 +00001284static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001285load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 struct stat st;
1288 FILE *fpc;
1289 char buf[MAXPATHLEN+1];
1290 char *cpathname;
1291 PyCodeObject *co;
1292 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (fstat(fileno(fp), &st) != 0) {
1295 PyErr_Format(PyExc_RuntimeError,
1296 "unable to get file status from '%s'",
1297 pathname);
1298 return NULL;
1299 }
Fred Drake4c82b232000-06-30 16:18:57 +00001300#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* Python's .pyc timestamp handling presumes that the timestamp fits
1302 in 4 bytes. This will be fine until sometime in the year 2038,
1303 when a 4-byte signed time_t will overflow.
1304 */
1305 if (st.st_mtime >> 32) {
1306 PyErr_SetString(PyExc_OverflowError,
1307 "modification time overflows a 4 byte field");
1308 return NULL;
1309 }
Fred Drake4c82b232000-06-30 16:18:57 +00001310#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 cpathname = make_compiled_pathname(
1312 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1313 if (cpathname != NULL &&
1314 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1315 co = read_compiled_module(cpathname, fpc);
1316 fclose(fpc);
1317 if (co == NULL)
1318 return NULL;
1319 if (update_compiled_module(co, pathname) < 0)
1320 return NULL;
1321 if (Py_VerboseFlag)
1322 PySys_WriteStderr("import %s # precompiled from %s\n",
1323 name, cpathname);
1324 pathname = cpathname;
1325 }
1326 else {
1327 co = parse_source_module(pathname, fp);
1328 if (co == NULL)
1329 return NULL;
1330 if (Py_VerboseFlag)
1331 PySys_WriteStderr("import %s # from %s\n",
1332 name, pathname);
1333 if (cpathname) {
1334 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1335 if (ro == NULL || !PyObject_IsTrue(ro))
1336 write_compiled_module(co, cpathname, &st);
1337 }
1338 }
1339 m = PyImport_ExecCodeModuleWithPathnames(
1340 name, (PyObject *)co, pathname, cpathname);
1341 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001344}
1345
Christian Heimes3b06e532008-01-07 20:12:44 +00001346/* Get source file -> unicode or None
1347 * Returns the path to the py file if available, else the given path
1348 */
1349static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001350get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 char py[MAXPATHLEN + 1];
1353 Py_ssize_t len;
1354 PyObject *u;
1355 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 if (!file || !*file) {
1358 Py_RETURN_NONE;
1359 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 len = strlen(file);
1362 /* match '*.py?' */
1363 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1364 return PyUnicode_DecodeFSDefault(file);
1365 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* Start by trying to turn PEP 3147 path into source path. If that
1368 * fails, just chop off the trailing character, i.e. legacy pyc path
1369 * to py.
1370 */
1371 if (make_source_pathname(file, py) == NULL) {
1372 strncpy(py, file, len-1);
1373 py[len-1] = '\0';
1374 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (stat(py, &statbuf) == 0 &&
1377 S_ISREG(statbuf.st_mode)) {
1378 u = PyUnicode_DecodeFSDefault(py);
1379 }
1380 else {
1381 u = PyUnicode_DecodeFSDefault(file);
1382 }
1383 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001384}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001385
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001386/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001387static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1388static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001390static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001391
1392/* Load a package and return its module object WITH INCREMENTED
1393 REFERENCE COUNT */
1394
1395static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001396load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyObject *m, *d;
1399 PyObject *file = NULL;
1400 PyObject *path = NULL;
1401 int err;
1402 char buf[MAXPATHLEN+1];
1403 FILE *fp = NULL;
1404 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 m = PyImport_AddModule(name);
1407 if (m == NULL)
1408 return NULL;
1409 if (Py_VerboseFlag)
1410 PySys_WriteStderr("import %s # directory %s\n",
1411 name, pathname);
1412 d = PyModule_GetDict(m);
1413 file = get_sourcefile(pathname);
1414 if (file == NULL)
1415 goto error;
1416 path = Py_BuildValue("[O]", file);
1417 if (path == NULL)
1418 goto error;
1419 err = PyDict_SetItemString(d, "__file__", file);
1420 if (err == 0)
1421 err = PyDict_SetItemString(d, "__path__", path);
1422 if (err != 0)
1423 goto error;
1424 buf[0] = '\0';
1425 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1426 if (fdp == NULL) {
1427 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1428 PyErr_Clear();
1429 Py_INCREF(m);
1430 }
1431 else
1432 m = NULL;
1433 goto cleanup;
1434 }
1435 m = load_module(name, fp, buf, fdp->type, NULL);
1436 if (fp != NULL)
1437 fclose(fp);
1438 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001439
1440 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001442 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_XDECREF(path);
1444 Py_XDECREF(file);
1445 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001446}
1447
1448
1449/* Helper to test for built-in module */
1450
1451static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001452is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 int i;
1455 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1456 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1457 if (PyImport_Inittab[i].initfunc == NULL)
1458 return -1;
1459 else
1460 return 1;
1461 }
1462 }
1463 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001464}
1465
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001466
Just van Rossum52e14d62002-12-30 22:08:05 +00001467/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1468 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001469 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001470 that can handle the path item. Return None if no hook could;
1471 this tells our caller it should fall back to the builtin
1472 import mechanism. Cache the result in path_importer_cache.
1473 Returns a borrowed reference. */
1474
1475static PyObject *
1476get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 PyObject *importer;
1480 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 /* These conditions are the caller's responsibility: */
1483 assert(PyList_Check(path_hooks));
1484 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 nhooks = PyList_Size(path_hooks);
1487 if (nhooks < 0)
1488 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 importer = PyDict_GetItem(path_importer_cache, p);
1491 if (importer != NULL)
1492 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 /* set path_importer_cache[p] to None to avoid recursion */
1495 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1496 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 for (j = 0; j < nhooks; j++) {
1499 PyObject *hook = PyList_GetItem(path_hooks, j);
1500 if (hook == NULL)
1501 return NULL;
1502 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1503 if (importer != NULL)
1504 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1507 return NULL;
1508 }
1509 PyErr_Clear();
1510 }
1511 if (importer == NULL) {
1512 importer = PyObject_CallFunctionObjArgs(
1513 (PyObject *)&PyNullImporter_Type, p, NULL
1514 );
1515 if (importer == NULL) {
1516 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1517 PyErr_Clear();
1518 return Py_None;
1519 }
1520 }
1521 }
1522 if (importer != NULL) {
1523 int err = PyDict_SetItem(path_importer_cache, p, importer);
1524 Py_DECREF(importer);
1525 if (err != 0)
1526 return NULL;
1527 }
1528 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001529}
1530
Christian Heimes9cd17752007-11-18 19:35:23 +00001531PyAPI_FUNC(PyObject *)
1532PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1536 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1537 importer = get_path_importer(path_importer_cache,
1538 path_hooks, path);
1539 }
1540 }
1541 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1542 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001543}
1544
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001545/* Search the path (default sys.path) for a module. Return the
1546 corresponding filedescr struct, and (via return arguments) the
1547 pathname and an open file. Return NULL if the module is not found. */
1548
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001549#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001550extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001552#endif
1553
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001555static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001556static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001557
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001558static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001559find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 Py_ssize_t i, npath;
1563 size_t len, namelen;
1564 struct filedescr *fdp = NULL;
1565 char *filemode;
1566 FILE *fp = NULL;
1567 PyObject *path_hooks, *path_importer_cache;
1568 struct stat statbuf;
1569 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1570 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1571 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1572 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001573#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 size_t saved_len;
1575 size_t saved_namelen;
1576 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001577#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (p_loader != NULL)
1579 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (strlen(subname) > MAXPATHLEN) {
1582 PyErr_SetString(PyExc_OverflowError,
1583 "module name is too long");
1584 return NULL;
1585 }
1586 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* sys.meta_path import hook */
1589 if (p_loader != NULL) {
1590 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 meta_path = PySys_GetObject("meta_path");
1593 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02001594 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 "sys.meta_path must be a list of "
1596 "import hooks");
1597 return NULL;
1598 }
1599 Py_INCREF(meta_path); /* zap guard */
1600 npath = PyList_Size(meta_path);
1601 for (i = 0; i < npath; i++) {
1602 PyObject *loader;
1603 PyObject *hook = PyList_GetItem(meta_path, i);
1604 loader = PyObject_CallMethod(hook, "find_module",
1605 "sO", fullname,
1606 path != NULL ?
1607 path : Py_None);
1608 if (loader == NULL) {
1609 Py_DECREF(meta_path);
1610 return NULL; /* true error */
1611 }
1612 if (loader != Py_None) {
1613 /* a loader was found */
1614 *p_loader = loader;
1615 Py_DECREF(meta_path);
1616 return &importhookdescr;
1617 }
1618 Py_DECREF(loader);
1619 }
1620 Py_DECREF(meta_path);
1621 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (find_frozen(fullname) != NULL) {
1624 strcpy(buf, fullname);
1625 return &fd_frozen;
1626 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (path == NULL) {
1629 if (is_builtin(name)) {
1630 strcpy(buf, name);
1631 return &fd_builtin;
1632 }
Guido van Rossumac279101996-08-22 23:10:58 +00001633#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1635 if (fp != NULL) {
1636 *p_fp = fp;
1637 return fdp;
1638 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001639#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 path = PySys_GetObject("path");
1641 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (path == NULL || !PyList_Check(path)) {
Victor Stinner16191322011-09-15 19:28:05 +02001644 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 "sys.path must be a list of directory names");
1646 return NULL;
1647 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 path_hooks = PySys_GetObject("path_hooks");
1650 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02001651 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 "sys.path_hooks must be a list of "
1653 "import hooks");
1654 return NULL;
1655 }
1656 path_importer_cache = PySys_GetObject("path_importer_cache");
1657 if (path_importer_cache == NULL ||
1658 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02001659 PyErr_SetString(PyExc_RuntimeError,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 "sys.path_importer_cache must be a dict");
1661 return NULL;
1662 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 npath = PyList_Size(path);
1665 namelen = strlen(name);
1666 for (i = 0; i < npath; i++) {
1667 PyObject *v = PyList_GetItem(path, i);
1668 PyObject *origv = v;
1669 const char *base;
1670 Py_ssize_t size;
1671 if (!v)
1672 return NULL;
1673 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001674 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (v == NULL)
1676 return NULL;
1677 }
1678 else if (!PyBytes_Check(v))
1679 continue;
1680 else
1681 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 base = PyBytes_AS_STRING(v);
1684 size = PyBytes_GET_SIZE(v);
1685 len = size;
1686 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1687 Py_DECREF(v);
1688 continue; /* Too long */
1689 }
1690 strcpy(buf, base);
1691 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (strlen(buf) != len) {
1694 continue; /* v contains '\0' */
1695 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 /* sys.path_hooks import hook */
1698 if (p_loader != NULL) {
1699 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 importer = get_path_importer(path_importer_cache,
1702 path_hooks, origv);
1703 if (importer == NULL) {
1704 return NULL;
1705 }
1706 /* Note: importer is a borrowed reference */
1707 if (importer != Py_None) {
1708 PyObject *loader;
1709 loader = PyObject_CallMethod(importer,
1710 "find_module",
1711 "s", fullname);
1712 if (loader == NULL)
1713 return NULL; /* error */
1714 if (loader != Py_None) {
1715 /* a loader was found */
1716 *p_loader = loader;
1717 return &importhookdescr;
1718 }
1719 Py_DECREF(loader);
1720 continue;
1721 }
1722 }
1723 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001726#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001728#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 )
1730 buf[len++] = SEP;
1731 strcpy(buf+len, name);
1732 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 /* Check for package import (buf holds a directory name,
1735 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001736#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (stat(buf, &statbuf) == 0 && /* it exists */
1738 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1739 case_ok(buf, len, namelen, name)) { /* case matches */
1740 if (find_init_module(buf)) { /* and has __init__.py */
1741 return &fd_package;
1742 }
1743 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001744 int err;
1745 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1746 if (unicode == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 return NULL;
Victor Stinnered7916d2010-10-17 02:07:09 +00001748 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1749 "Not importing directory '%U': missing __init__.py",
1750 unicode);
1751 Py_DECREF(unicode);
1752 if (err)
1753 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 }
1755 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001756#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001757#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 /* take a snapshot of the module spec for restoration
1759 * after the 8 character DLL hackery
1760 */
1761 saved_buf = strdup(buf);
1762 saved_len = len;
1763 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001764#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinner53ffdc52011-09-23 18:54:40 +02001766 struct stat statbuf;
Guido van Rossum04110fb2007-08-24 16:32:05 +00001767#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* OS/2 limits DLLs to 8 character names (w/o
1769 extension)
1770 * so if the name is longer than that and its a
1771 * dynamically loaded module we're going to try,
1772 * truncate the name before trying
1773 */
1774 if (strlen(subname) > 8) {
1775 /* is this an attempt to load a C extension? */
1776 const struct filedescr *scan;
1777 scan = _PyImport_DynLoadFiletab;
1778 while (scan->suffix != NULL) {
1779 if (!strcmp(scan->suffix, fdp->suffix))
1780 break;
1781 else
1782 scan++;
1783 }
1784 if (scan->suffix != NULL) {
1785 /* yes, so truncate the name */
1786 namelen = 8;
1787 len -= strlen(subname) - namelen;
1788 buf[len] = '\0';
1789 }
1790 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001791#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 strcpy(buf+len, fdp->suffix);
1793 if (Py_VerboseFlag > 1)
1794 PySys_WriteStderr("# trying %s\n", buf);
Victor Stinner53ffdc52011-09-23 18:54:40 +02001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 filemode = fdp->mode;
1797 if (filemode[0] == 'U')
1798 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinner53ffdc52011-09-23 18:54:40 +02001799
1800 if (stat(buf, &statbuf) == 0 && S_ISDIR(statbuf.st_mode))
1801 /* it's a directory */
1802 fp = NULL;
1803 else
1804 fp = fopen(buf, filemode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (fp != NULL) {
1806 if (case_ok(buf, len, namelen, name))
1807 break;
1808 else { /* continue search */
1809 fclose(fp);
1810 fp = NULL;
1811 }
1812 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001813#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 /* restore the saved snapshot */
1815 strcpy(buf, saved_buf);
1816 len = saved_len;
1817 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001818#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001820#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 /* don't need/want the module name snapshot anymore */
1822 if (saved_buf)
1823 {
1824 free(saved_buf);
1825 saved_buf = NULL;
1826 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001827#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (fp != NULL)
1829 break;
1830 }
1831 if (fp == NULL) {
1832 PyErr_Format(PyExc_ImportError,
1833 "No module named %.200s", name);
1834 return NULL;
1835 }
1836 *p_fp = fp;
1837 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001838}
1839
Martin v. Löwis18e16552006-02-15 17:27:45 +00001840/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001841 * The arguments here are tricky, best shown by example:
1842 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1843 * ^ ^ ^ ^
1844 * |--------------------- buf ---------------------|
1845 * |------------------- len ------------------|
1846 * |------ name -------|
1847 * |----- namelen -----|
1848 * buf is the full path, but len only counts up to (& exclusive of) the
1849 * extension. name is the module name, also exclusive of extension.
1850 *
1851 * We've already done a successful stat() or fopen() on buf, so know that
1852 * there's some match, possibly case-insensitive.
1853 *
Tim Peters50d8d372001-02-28 05:34:27 +00001854 * case_ok() is to return 1 if there's a case-sensitive match for
1855 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1856 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001857 *
Tim Peters50d8d372001-02-28 05:34:27 +00001858 * case_ok() is used to implement case-sensitive import semantics even
1859 * on platforms with case-insensitive filesystems. It's trivial to implement
1860 * for case-sensitive filesystems. It's pretty much a cross-platform
1861 * nightmare for systems with case-insensitive filesystems.
1862 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001863
Tim Peters50d8d372001-02-28 05:34:27 +00001864/* First we may need a pile of platform-specific header files; the sequence
1865 * of #if's here should match the sequence in the body of case_ok().
1866 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001867#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001868#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001869
Tim Peters50d8d372001-02-28 05:34:27 +00001870#elif defined(DJGPP)
1871#include <dir.h>
1872
Jason Tishler7961aa62005-05-20 00:56:54 +00001873#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001874#include <sys/types.h>
1875#include <dirent.h>
1876
Andrew MacIntyred9400542002-02-26 11:41:34 +00001877#elif defined(PYOS_OS2)
1878#define INCL_DOS
1879#define INCL_DOSERRORS
1880#define INCL_NOPMAPI
1881#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001882#endif
1883
Guido van Rossum0980bd91998-02-13 17:18:36 +00001884static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001886{
Tim Peters50d8d372001-02-28 05:34:27 +00001887/* Pick a platform-specific implementation; the sequence of #if's here should
1888 * match the sequence just above.
1889 */
1890
Jason Tishler7961aa62005-05-20 00:56:54 +00001891/* MS_WINDOWS */
1892#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 WIN32_FIND_DATA data;
1894 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (Py_GETENV("PYTHONCASEOK") != NULL)
1897 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 h = FindFirstFile(buf, &data);
1900 if (h == INVALID_HANDLE_VALUE) {
1901 PyErr_Format(PyExc_NameError,
1902 "Can't find file for module %.100s\n(filename %.300s)",
1903 name, buf);
1904 return 0;
1905 }
1906 FindClose(h);
1907 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001908
1909/* DJGPP */
1910#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 struct ffblk ffblk;
1912 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 if (Py_GETENV("PYTHONCASEOK") != NULL)
1915 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1918 if (done) {
1919 PyErr_Format(PyExc_NameError,
1920 "Can't find file for module %.100s\n(filename %.300s)",
1921 name, buf);
1922 return 0;
1923 }
1924 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001925
Jason Tishler7961aa62005-05-20 00:56:54 +00001926/* new-fangled macintosh (macosx) or Cygwin */
1927#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 DIR *dirp;
1929 struct dirent *dp;
1930 char dirname[MAXPATHLEN + 1];
1931 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (Py_GETENV("PYTHONCASEOK") != NULL)
1934 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* Copy the dir component into dirname; substitute "." if empty */
1937 if (dirlen <= 0) {
1938 dirname[0] = '.';
1939 dirname[1] = '\0';
1940 }
1941 else {
1942 assert(dirlen <= MAXPATHLEN);
1943 memcpy(dirname, buf, dirlen);
1944 dirname[dirlen] = '\0';
1945 }
1946 /* Open the directory and search the entries for an exact match. */
1947 dirp = opendir(dirname);
1948 if (dirp) {
1949 char *nameWithExt = buf + len - namelen;
1950 while ((dp = readdir(dirp)) != NULL) {
1951 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001952#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001954#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001956#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (thislen >= namelen &&
1958 strcmp(dp->d_name, nameWithExt) == 0) {
1959 (void)closedir(dirp);
1960 return 1; /* Found */
1961 }
1962 }
1963 (void)closedir(dirp);
1964 }
1965 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001966
Andrew MacIntyred9400542002-02-26 11:41:34 +00001967/* OS/2 */
1968#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 HDIR hdir = 1;
1970 ULONG srchcnt = 1;
1971 FILEFINDBUF3 ffbuf;
1972 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (Py_GETENV("PYTHONCASEOK") != NULL)
1975 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 rc = DosFindFirst(buf,
1978 &hdir,
1979 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1980 &ffbuf, sizeof(ffbuf),
1981 &srchcnt,
1982 FIL_STANDARD);
1983 if (rc != NO_ERROR)
1984 return 0;
1985 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001986
Tim Peters50d8d372001-02-28 05:34:27 +00001987/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1988#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001990
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001991#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001992}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001993
Guido van Rossum197346f1997-10-31 18:38:52 +00001994#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001995
Guido van Rossum197346f1997-10-31 18:38:52 +00001996/* Helper to look for __init__.py or __init__.py[co] in potential package */
1997static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001998find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 const size_t save_len = strlen(buf);
2001 size_t i = save_len;
2002 char *pname; /* pointer to start of __init__ */
2003 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005/* For calling case_ok(buf, len, namelen, name):
2006 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2007 * ^ ^ ^ ^
2008 * |--------------------- buf ---------------------|
2009 * |------------------- len ------------------|
2010 * |------ name -------|
2011 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002012 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (save_len + 13 >= MAXPATHLEN)
2014 return 0;
2015 buf[i++] = SEP;
2016 pname = buf + i;
2017 strcpy(pname, "__init__.py");
2018 if (stat(buf, &statbuf) == 0) {
2019 if (case_ok(buf,
2020 save_len + 9, /* len("/__init__") */
2021 8, /* len("__init__") */
2022 pname)) {
2023 buf[save_len] = '\0';
2024 return 1;
2025 }
2026 }
2027 i += strlen(pname);
2028 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2029 if (stat(buf, &statbuf) == 0) {
2030 if (case_ok(buf,
2031 save_len + 9, /* len("/__init__") */
2032 8, /* len("__init__") */
2033 pname)) {
2034 buf[save_len] = '\0';
2035 return 1;
2036 }
2037 }
2038 buf[save_len] = '\0';
2039 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002040}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002041
Guido van Rossum197346f1997-10-31 18:38:52 +00002042#endif /* HAVE_STAT */
2043
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002044
Tim Petersdbd9ba62000-07-09 03:09:57 +00002045static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002046
Victor Stinner44c6c152010-08-09 00:59:10 +00002047static PyObject*
2048load_builtin(char *name, char *pathname, int type)
2049{
2050 PyObject *m, *modules;
2051 int err;
2052
2053 if (pathname != NULL && pathname[0] != '\0')
2054 name = pathname;
2055
2056 if (type == C_BUILTIN)
2057 err = init_builtin(name);
2058 else
2059 err = PyImport_ImportFrozenModule(name);
2060 if (err < 0)
2061 return NULL;
2062 if (err == 0) {
2063 PyErr_Format(PyExc_ImportError,
2064 "Purported %s module %.200s not found",
2065 type == C_BUILTIN ?
2066 "builtin" : "frozen",
2067 name);
2068 return NULL;
2069 }
2070
2071 modules = PyImport_GetModuleDict();
2072 m = PyDict_GetItemString(modules, name);
2073 if (m == NULL) {
2074 PyErr_Format(
2075 PyExc_ImportError,
2076 "%s module %.200s not properly initialized",
2077 type == C_BUILTIN ?
2078 "builtin" : "frozen",
2079 name);
2080 return NULL;
2081 }
2082 Py_INCREF(m);
2083 return m;
2084}
2085
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002086/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002087 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002088
Guido van Rossum79f25d91997-04-29 20:08:16 +00002089static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002090load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* First check that there's an open file (if we need one) */
2095 switch (type) {
2096 case PY_SOURCE:
2097 case PY_COMPILED:
2098 if (fp == NULL) {
2099 PyErr_Format(PyExc_ValueError,
2100 "file object required for import (type code %d)",
2101 type);
2102 return NULL;
2103 }
2104 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 case PY_SOURCE:
2109 m = load_source_module(name, pathname, fp);
2110 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 case PY_COMPILED:
2113 m = load_compiled_module(name, pathname, fp);
2114 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002115
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002116#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 case C_EXTENSION:
2118 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2119 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002120#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 case PKG_DIRECTORY:
2123 m = load_package(name, pathname);
2124 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 case C_BUILTIN:
2127 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002128 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 case IMP_HOOK: {
2132 if (loader == NULL) {
2133 PyErr_SetString(PyExc_ImportError,
2134 "import hook without loader");
2135 return NULL;
2136 }
2137 m = PyObject_CallMethod(loader, "load_module", "s", name);
2138 break;
2139 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 default:
2142 PyErr_Format(PyExc_ImportError,
2143 "Don't know how to import %.200s (type code %d)",
2144 name, type);
2145 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002150}
2151
2152
2153/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002154 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002155 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002156
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002157static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002158init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002161
Victor Stinner49d3f252010-10-17 01:24:53 +00002162 if (_PyImport_FindBuiltin(name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 for (p = PyImport_Inittab; p->name != NULL; p++) {
2166 PyObject *mod;
2167 if (strcmp(name, p->name) == 0) {
2168 if (p->initfunc == NULL) {
2169 PyErr_Format(PyExc_ImportError,
2170 "Cannot re-init internal module %.200s",
2171 name);
2172 return -1;
2173 }
2174 if (Py_VerboseFlag)
2175 PySys_WriteStderr("import %s # builtin\n", name);
2176 mod = (*p->initfunc)();
2177 if (mod == 0)
2178 return -1;
Victor Stinner49d3f252010-10-17 01:24:53 +00002179 if (_PyImport_FixupBuiltin(mod, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 return -1;
2181 /* FixupExtension has put the module into sys.modules,
2182 so we can release our own reference. */
2183 Py_DECREF(mod);
2184 return 1;
2185 }
2186 }
2187 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002188}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002189
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002190
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002191/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002192
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002193static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002194find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (!name)
2199 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 for (p = PyImport_FrozenModules; ; p++) {
2202 if (p->name == NULL)
2203 return NULL;
2204 if (strcmp(p->name, name) == 0)
2205 break;
2206 }
2207 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002208}
2209
Guido van Rossum79f25d91997-04-29 20:08:16 +00002210static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002211get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 struct _frozen *p = find_frozen(name);
2214 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (p == NULL) {
2217 PyErr_Format(PyExc_ImportError,
2218 "No such frozen object named %.200s",
2219 name);
2220 return NULL;
2221 }
2222 if (p->code == NULL) {
2223 PyErr_Format(PyExc_ImportError,
2224 "Excluded frozen object named %.200s",
2225 name);
2226 return NULL;
2227 }
2228 size = p->size;
2229 if (size < 0)
2230 size = -size;
2231 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002232}
2233
Brett Cannon8d110132009-03-15 02:20:16 +00002234static PyObject *
2235is_frozen_package(char *name)
2236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 struct _frozen *p = find_frozen(name);
2238 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 if (p == NULL) {
2241 PyErr_Format(PyExc_ImportError,
2242 "No such frozen object named %.200s",
2243 name);
2244 return NULL;
2245 }
Brett Cannon8d110132009-03-15 02:20:16 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (size < 0)
2250 Py_RETURN_TRUE;
2251 else
2252 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002253}
2254
2255
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002256/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002257 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002258 an exception set if the initialization failed.
2259 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002260
2261int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002262PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 struct _frozen *p = find_frozen(name);
2265 PyObject *co;
2266 PyObject *m;
2267 int ispackage;
2268 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 if (p == NULL)
2271 return 0;
2272 if (p->code == NULL) {
2273 PyErr_Format(PyExc_ImportError,
2274 "Excluded frozen object named %.200s",
2275 name);
2276 return -1;
2277 }
2278 size = p->size;
2279 ispackage = (size < 0);
2280 if (ispackage)
2281 size = -size;
2282 if (Py_VerboseFlag)
2283 PySys_WriteStderr("import %s # frozen%s\n",
2284 name, ispackage ? " package" : "");
2285 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2286 if (co == NULL)
2287 return -1;
2288 if (!PyCode_Check(co)) {
2289 PyErr_Format(PyExc_TypeError,
2290 "frozen object %.200s is not a code object",
2291 name);
2292 goto err_return;
2293 }
2294 if (ispackage) {
2295 /* Set __path__ to the package name */
2296 PyObject *d, *s, *l;
2297 int err;
2298 m = PyImport_AddModule(name);
2299 if (m == NULL)
2300 goto err_return;
2301 d = PyModule_GetDict(m);
2302 s = PyUnicode_InternFromString(name);
2303 if (s == NULL)
2304 goto err_return;
2305 l = PyList_New(1);
2306 if (l == NULL) {
2307 Py_DECREF(s);
2308 goto err_return;
2309 }
2310 PyList_SET_ITEM(l, 0, s);
2311 err = PyDict_SetItemString(d, "__path__", l);
2312 Py_DECREF(l);
2313 if (err != 0)
2314 goto err_return;
2315 }
2316 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2317 if (m == NULL)
2318 goto err_return;
2319 Py_DECREF(co);
2320 Py_DECREF(m);
2321 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002322err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 Py_DECREF(co);
2324 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002325}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002326
2327
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002328/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002329 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002330
Guido van Rossum79f25d91997-04-29 20:08:16 +00002331PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002332PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 PyObject *pname;
2335 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 pname = PyUnicode_FromString(name);
2338 if (pname == NULL)
2339 return NULL;
2340 result = PyImport_Import(pname);
2341 Py_DECREF(pname);
2342 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002343}
2344
Christian Heimes072c0f12008-01-03 23:01:04 +00002345/* Import a module without blocking
2346 *
2347 * At first it tries to fetch the module from sys.modules. If the module was
2348 * never loaded before it loads it with PyImport_ImportModule() unless another
2349 * thread holds the import lock. In the latter case the function raises an
2350 * ImportError instead of blocking.
2351 *
2352 * Returns the module object with incremented ref count.
2353 */
2354PyObject *
2355PyImport_ImportModuleNoBlock(const char *name)
2356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 PyObject *result;
2358 PyObject *modules;
Victor Stinner0af03062011-09-02 00:11:43 +02002359#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002361#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Try to get the module from sys.modules[name] */
2364 modules = PyImport_GetModuleDict();
2365 if (modules == NULL)
2366 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 result = PyDict_GetItemString(modules, name);
2369 if (result != NULL) {
2370 Py_INCREF(result);
2371 return result;
2372 }
2373 else {
2374 PyErr_Clear();
2375 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002376#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* check the import lock
2378 * me might be -1 but I ignore the error here, the lock function
2379 * takes care of the problem */
2380 me = PyThread_get_thread_ident();
2381 if (import_lock_thread == -1 || import_lock_thread == me) {
2382 /* no thread or me is holding the lock */
2383 return PyImport_ImportModule(name);
2384 }
2385 else {
2386 PyErr_Format(PyExc_ImportError,
2387 "Failed to import %.200s because the import lock"
2388 "is held by another thread.",
2389 name);
2390 return NULL;
2391 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002392#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002394#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002395}
2396
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002397/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002398static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002400static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002402static int mark_miss(char *name);
2403static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002405static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002406
2407/* The Magnum Opus of dotted-name import :-) */
2408
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002409static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002410import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 char buf[MAXPATHLEN+1];
2414 Py_ssize_t buflen = 0;
2415 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002418#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002420#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 ) {
2422 PyErr_SetString(PyExc_ImportError,
2423 "Import by filename is not supported.");
2424 return NULL;
2425 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 parent = get_parent(globals, buf, &buflen, level);
2428 if (parent == NULL)
2429 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002430
Benjamin Peterson556d8002010-06-27 22:37:28 +00002431 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2432 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 if (head == NULL)
2434 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 tail = head;
2437 Py_INCREF(tail);
2438 while (name) {
2439 next = load_next(tail, tail, &name, buf, &buflen);
2440 Py_DECREF(tail);
2441 if (next == NULL) {
2442 Py_DECREF(head);
2443 return NULL;
2444 }
2445 tail = next;
2446 }
2447 if (tail == Py_None) {
2448 /* If tail is Py_None, both get_parent and load_next found
2449 an empty module name: someone called __import__("") or
2450 doctored faulty bytecode */
2451 Py_DECREF(tail);
2452 Py_DECREF(head);
2453 PyErr_SetString(PyExc_ValueError,
2454 "Empty module name");
2455 return NULL;
2456 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 if (fromlist != NULL) {
2459 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2460 fromlist = NULL;
2461 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (fromlist == NULL) {
2464 Py_DECREF(tail);
2465 return head;
2466 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 Py_DECREF(head);
2469 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2470 Py_DECREF(tail);
2471 return NULL;
2472 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002475}
2476
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002477PyObject *
2478PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 PyObject *result;
2482 _PyImport_AcquireLock();
2483 result = import_module_level(name, globals, locals, fromlist, level);
2484 if (_PyImport_ReleaseLock() < 0) {
2485 Py_XDECREF(result);
2486 PyErr_SetString(PyExc_RuntimeError,
2487 "not holding the import lock");
2488 return NULL;
2489 }
2490 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002491}
2492
Fred Drake87590902004-05-28 20:21:36 +00002493/* Return the package that an import is being performed in. If globals comes
2494 from the module foo.bar.bat (not itself a package), this returns the
2495 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002496 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002497
2498 The *name* of the returned package is returned in buf, with the length of
2499 the name in *p_buflen.
2500
2501 If globals doesn't come from a package or a module in a package, or a
2502 corresponding entry is not found in sys.modules, Py_None is returned.
2503*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002504static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002505get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 static PyObject *namestr = NULL;
2508 static PyObject *pathstr = NULL;
2509 static PyObject *pkgstr = NULL;
2510 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2511 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (globals == NULL || !PyDict_Check(globals) || !level)
2514 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 if (namestr == NULL) {
2517 namestr = PyUnicode_InternFromString("__name__");
2518 if (namestr == NULL)
2519 return NULL;
2520 }
2521 if (pathstr == NULL) {
2522 pathstr = PyUnicode_InternFromString("__path__");
2523 if (pathstr == NULL)
2524 return NULL;
2525 }
2526 if (pkgstr == NULL) {
2527 pkgstr = PyUnicode_InternFromString("__package__");
2528 if (pkgstr == NULL)
2529 return NULL;
2530 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 *buf = '\0';
2533 *p_buflen = 0;
2534 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if ((pkgname != NULL) && (pkgname != Py_None)) {
2537 /* __package__ is set, so use it */
2538 char *pkgname_str;
2539 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (!PyUnicode_Check(pkgname)) {
2542 PyErr_SetString(PyExc_ValueError,
2543 "__package__ set to non-string");
2544 return NULL;
2545 }
2546 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2547 if (len == 0) {
2548 if (level > 0) {
2549 PyErr_SetString(PyExc_ValueError,
2550 "Attempted relative import in non-package");
2551 return NULL;
2552 }
2553 return Py_None;
2554 }
2555 if (len > MAXPATHLEN) {
2556 PyErr_SetString(PyExc_ValueError,
2557 "Package name too long");
2558 return NULL;
2559 }
2560 strcpy(buf, pkgname_str);
2561 } else {
2562 /* __package__ not set, so figure it out and set it */
2563 modname = PyDict_GetItem(globals, namestr);
2564 if (modname == NULL || !PyUnicode_Check(modname))
2565 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 modpath = PyDict_GetItem(globals, pathstr);
2568 if (modpath != NULL) {
2569 /* __path__ is set, so modname is already the package name */
2570 char *modname_str;
2571 Py_ssize_t len;
2572 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2575 if (len > MAXPATHLEN) {
2576 PyErr_SetString(PyExc_ValueError,
2577 "Module name too long");
2578 return NULL;
2579 }
2580 strcpy(buf, modname_str);
2581 error = PyDict_SetItem(globals, pkgstr, modname);
2582 if (error) {
2583 PyErr_SetString(PyExc_ValueError,
2584 "Could not set __package__");
2585 return NULL;
2586 }
2587 } else {
2588 /* Normal module, so work out the package name if any */
2589 char *start = _PyUnicode_AsString(modname);
2590 char *lastdot = strrchr(start, '.');
2591 size_t len;
2592 int error;
2593 if (lastdot == NULL && level > 0) {
2594 PyErr_SetString(PyExc_ValueError,
2595 "Attempted relative import in non-package");
2596 return NULL;
2597 }
2598 if (lastdot == NULL) {
2599 error = PyDict_SetItem(globals, pkgstr, Py_None);
2600 if (error) {
2601 PyErr_SetString(PyExc_ValueError,
2602 "Could not set __package__");
2603 return NULL;
2604 }
2605 return Py_None;
2606 }
2607 len = lastdot - start;
2608 if (len >= MAXPATHLEN) {
2609 PyErr_SetString(PyExc_ValueError,
2610 "Module name too long");
2611 return NULL;
2612 }
2613 strncpy(buf, start, len);
2614 buf[len] = '\0';
2615 pkgname = PyUnicode_FromString(buf);
2616 if (pkgname == NULL) {
2617 return NULL;
2618 }
2619 error = PyDict_SetItem(globals, pkgstr, pkgname);
2620 Py_DECREF(pkgname);
2621 if (error) {
2622 PyErr_SetString(PyExc_ValueError,
2623 "Could not set __package__");
2624 return NULL;
2625 }
2626 }
2627 }
2628 while (--level > 0) {
2629 char *dot = strrchr(buf, '.');
2630 if (dot == NULL) {
2631 PyErr_SetString(PyExc_ValueError,
2632 "Attempted relative import beyond "
2633 "toplevel package");
2634 return NULL;
2635 }
2636 *dot = '\0';
2637 }
2638 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 modules = PyImport_GetModuleDict();
2641 parent = PyDict_GetItemString(modules, buf);
2642 if (parent == NULL) {
2643 if (orig_level < 1) {
2644 PyObject *err_msg = PyBytes_FromFormat(
2645 "Parent module '%.200s' not found "
2646 "while handling absolute import", buf);
2647 if (err_msg == NULL) {
2648 return NULL;
2649 }
2650 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2651 PyBytes_AsString(err_msg), 1)) {
2652 *buf = '\0';
2653 *p_buflen = 0;
2654 parent = Py_None;
2655 }
2656 Py_DECREF(err_msg);
2657 } else {
2658 PyErr_Format(PyExc_SystemError,
2659 "Parent module '%.200s' not loaded, "
2660 "cannot perform relative import", buf);
2661 }
2662 }
2663 return parent;
2664 /* We expect, but can't guarantee, if parent != None, that:
2665 - parent.__name__ == buf
2666 - parent.__dict__ is globals
2667 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002668}
2669
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002670/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002671static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002672load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 char *name = *p_name;
2676 char *dot = strchr(name, '.');
2677 size_t len;
2678 char *p;
2679 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 if (strlen(name) == 0) {
2682 /* completely empty module name should only happen in
2683 'from . import' (or '__import__("")')*/
2684 Py_INCREF(mod);
2685 *p_name = NULL;
2686 return mod;
2687 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (dot == NULL) {
2690 *p_name = NULL;
2691 len = strlen(name);
2692 }
2693 else {
2694 *p_name = dot+1;
2695 len = dot-name;
2696 }
2697 if (len == 0) {
2698 PyErr_SetString(PyExc_ValueError,
2699 "Empty module name");
2700 return NULL;
2701 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 p = buf + *p_buflen;
2704 if (p != buf)
2705 *p++ = '.';
2706 if (p+len-buf >= MAXPATHLEN) {
2707 PyErr_SetString(PyExc_ValueError,
2708 "Module name too long");
2709 return NULL;
2710 }
2711 strncpy(p, name, len);
2712 p[len] = '\0';
2713 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 result = import_submodule(mod, p, buf);
2716 if (result == Py_None && altmod != mod) {
2717 Py_DECREF(result);
2718 /* Here, altmod must be None and mod must not be None */
2719 result = import_submodule(altmod, p, p);
2720 if (result != NULL && result != Py_None) {
2721 if (mark_miss(buf) != 0) {
2722 Py_DECREF(result);
2723 return NULL;
2724 }
2725 strncpy(buf, name, len);
2726 buf[len] = '\0';
2727 *p_buflen = len;
2728 }
2729 }
2730 if (result == NULL)
2731 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 if (result == Py_None) {
2734 Py_DECREF(result);
2735 PyErr_Format(PyExc_ImportError,
2736 "No module named %.200s", name);
2737 return NULL;
2738 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002741}
2742
2743static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002744mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 PyObject *modules = PyImport_GetModuleDict();
2747 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002748}
2749
2750static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002751ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 if (!PyObject_HasAttrString(mod, "__path__"))
2757 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 for (i = 0; ; i++) {
2760 PyObject *item = PySequence_GetItem(fromlist, i);
2761 int hasit;
2762 if (item == NULL) {
2763 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2764 PyErr_Clear();
2765 return 1;
2766 }
2767 return 0;
2768 }
2769 if (!PyUnicode_Check(item)) {
2770 PyErr_SetString(PyExc_TypeError,
2771 "Item in ``from list'' not a string");
2772 Py_DECREF(item);
2773 return 0;
2774 }
2775 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2776 PyObject *all;
2777 Py_DECREF(item);
2778 /* See if the package defines __all__ */
2779 if (recursive)
2780 continue; /* Avoid endless recursion */
2781 all = PyObject_GetAttrString(mod, "__all__");
2782 if (all == NULL)
2783 PyErr_Clear();
2784 else {
2785 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2786 Py_DECREF(all);
2787 if (!ret)
2788 return 0;
2789 }
2790 continue;
2791 }
2792 hasit = PyObject_HasAttr(mod, item);
2793 if (!hasit) {
2794 PyObject *item8;
2795 char *subname;
2796 PyObject *submod;
2797 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002798 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 if (!item8) {
2800 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2801 return 0;
2802 }
2803 subname = PyBytes_AS_STRING(item8);
2804 if (buflen + strlen(subname) >= MAXPATHLEN) {
2805 PyErr_SetString(PyExc_ValueError,
2806 "Module name too long");
2807 Py_DECREF(item);
2808 return 0;
2809 }
2810 p = buf + buflen;
2811 *p++ = '.';
2812 strcpy(p, subname);
2813 submod = import_submodule(mod, subname, buf);
2814 Py_DECREF(item8);
2815 Py_XDECREF(submod);
2816 if (submod == NULL) {
2817 Py_DECREF(item);
2818 return 0;
2819 }
2820 }
2821 Py_DECREF(item);
2822 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002825}
2826
Neil Schemenauer00b09662003-06-16 21:03:07 +00002827static int
2828add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 if (mod == Py_None)
2832 return 1;
2833 /* Irrespective of the success of this load, make a
2834 reference to it in the parent package module. A copy gets
2835 saved in the modules dictionary under the full name, so get a
2836 reference from there, if need be. (The exception is when the
2837 load failed with a SyntaxError -- then there's no trace in
2838 sys.modules. In that case, of course, do nothing extra.) */
2839 if (submod == NULL) {
2840 submod = PyDict_GetItemString(modules, fullname);
2841 if (submod == NULL)
2842 return 1;
2843 }
2844 if (PyModule_Check(mod)) {
2845 /* We can't use setattr here since it can give a
2846 * spurious warning if the submodule name shadows a
2847 * builtin name */
2848 PyObject *dict = PyModule_GetDict(mod);
2849 if (!dict)
2850 return 0;
2851 if (PyDict_SetItemString(dict, subname, submod) < 0)
2852 return 0;
2853 }
2854 else {
2855 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2856 return 0;
2857 }
2858 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002859}
2860
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002861static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002862import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 PyObject *modules = PyImport_GetModuleDict();
2865 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 /* Require:
2868 if mod == None: subname == fullname
2869 else: mod.__name__ + "." + subname == fullname
2870 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2873 Py_INCREF(m);
2874 }
2875 else {
2876 PyObject *path, *loader = NULL;
2877 char buf[MAXPATHLEN+1];
2878 struct filedescr *fdp;
2879 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 if (mod == Py_None)
2882 path = NULL;
2883 else {
2884 path = PyObject_GetAttrString(mod, "__path__");
2885 if (path == NULL) {
2886 PyErr_Clear();
2887 Py_INCREF(Py_None);
2888 return Py_None;
2889 }
2890 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 buf[0] = '\0';
2893 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2894 &fp, &loader);
2895 Py_XDECREF(path);
2896 if (fdp == NULL) {
2897 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2898 return NULL;
2899 PyErr_Clear();
2900 Py_INCREF(Py_None);
2901 return Py_None;
2902 }
2903 m = load_module(fullname, fp, buf, fdp->type, loader);
2904 Py_XDECREF(loader);
2905 if (fp)
2906 fclose(fp);
2907 if (!add_submodule(mod, m, fullname, subname, modules)) {
2908 Py_XDECREF(m);
2909 m = NULL;
2910 }
2911 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002914}
2915
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002916
2917/* Re-import a module of any kind and return its module object, WITH
2918 INCREMENTED REFERENCE COUNT */
2919
Guido van Rossum79f25d91997-04-29 20:08:16 +00002920PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002921PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 PyInterpreterState *interp = PyThreadState_Get()->interp;
2924 PyObject *modules_reloading = interp->modules_reloading;
2925 PyObject *modules = PyImport_GetModuleDict();
2926 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2927 char *name, *subname;
2928 char buf[MAXPATHLEN+1];
2929 struct filedescr *fdp;
2930 FILE *fp = NULL;
2931 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 if (modules_reloading == NULL) {
2934 Py_FatalError("PyImport_ReloadModule: "
2935 "no modules_reloading dictionary!");
2936 return NULL;
2937 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (m == NULL || !PyModule_Check(m)) {
2940 PyErr_SetString(PyExc_TypeError,
2941 "reload() argument must be module");
2942 return NULL;
2943 }
2944 name = (char*)PyModule_GetName(m);
2945 if (name == NULL)
2946 return NULL;
2947 if (m != PyDict_GetItemString(modules, name)) {
2948 PyErr_Format(PyExc_ImportError,
2949 "reload(): module %.200s not in sys.modules",
2950 name);
2951 return NULL;
2952 }
2953 existing_m = PyDict_GetItemString(modules_reloading, name);
2954 if (existing_m != NULL) {
2955 /* Due to a recursive reload, this module is already
2956 being reloaded. */
2957 Py_INCREF(existing_m);
2958 return existing_m;
2959 }
2960 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2961 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 subname = strrchr(name, '.');
2964 if (subname == NULL)
2965 subname = name;
2966 else {
2967 PyObject *parentname, *parent;
2968 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2969 if (parentname == NULL) {
2970 imp_modules_reloading_clear();
2971 return NULL;
2972 }
2973 parent = PyDict_GetItem(modules, parentname);
2974 if (parent == NULL) {
2975 PyErr_Format(PyExc_ImportError,
2976 "reload(): parent %U not in sys.modules",
2977 parentname);
2978 Py_DECREF(parentname);
2979 imp_modules_reloading_clear();
2980 return NULL;
2981 }
2982 Py_DECREF(parentname);
2983 subname++;
2984 path = PyObject_GetAttrString(parent, "__path__");
2985 if (path == NULL)
2986 PyErr_Clear();
2987 }
2988 buf[0] = '\0';
2989 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2990 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 if (fdp == NULL) {
2993 Py_XDECREF(loader);
2994 imp_modules_reloading_clear();
2995 return NULL;
2996 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 newm = load_module(name, fp, buf, fdp->type, loader);
2999 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 if (fp)
3002 fclose(fp);
3003 if (newm == NULL) {
3004 /* load_module probably removed name from modules because of
3005 * the error. Put back the original module object. We're
3006 * going to return NULL in this case regardless of whether
3007 * replacing name succeeds, so the return value is ignored.
3008 */
3009 PyDict_SetItemString(modules, name, m);
3010 }
3011 imp_modules_reloading_clear();
3012 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003013}
3014
3015
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003016/* Higher-level import emulator which emulates the "import" statement
3017 more accurately -- it invokes the __import__() function from the
3018 builtins of the current globals. This means that the import is
3019 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003020 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003021 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003022 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003023 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003024
3025PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003026PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 static PyObject *silly_list = NULL;
3029 static PyObject *builtins_str = NULL;
3030 static PyObject *import_str = NULL;
3031 PyObject *globals = NULL;
3032 PyObject *import = NULL;
3033 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003034 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* Initialize constant string objects */
3038 if (silly_list == NULL) {
3039 import_str = PyUnicode_InternFromString("__import__");
3040 if (import_str == NULL)
3041 return NULL;
3042 builtins_str = PyUnicode_InternFromString("__builtins__");
3043 if (builtins_str == NULL)
3044 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003045 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 if (silly_list == NULL)
3047 return NULL;
3048 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 /* Get the builtins from current globals */
3051 globals = PyEval_GetGlobals();
3052 if (globals != NULL) {
3053 Py_INCREF(globals);
3054 builtins = PyObject_GetItem(globals, builtins_str);
3055 if (builtins == NULL)
3056 goto err;
3057 }
3058 else {
3059 /* No globals -- use standard builtins, and fake globals */
3060 builtins = PyImport_ImportModuleLevel("builtins",
3061 NULL, NULL, NULL, 0);
3062 if (builtins == NULL)
3063 return NULL;
3064 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3065 if (globals == NULL)
3066 goto err;
3067 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 /* Get the __import__ function from the builtins */
3070 if (PyDict_Check(builtins)) {
3071 import = PyObject_GetItem(builtins, import_str);
3072 if (import == NULL)
3073 PyErr_SetObject(PyExc_KeyError, import_str);
3074 }
3075 else
3076 import = PyObject_GetAttr(builtins, import_str);
3077 if (import == NULL)
3078 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003081 Always use absolute import here.
3082 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3084 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003085 if (r == NULL)
3086 goto err;
3087 Py_DECREF(r);
3088
3089 modules = PyImport_GetModuleDict();
3090 r = PyDict_GetItem(modules, module_name);
3091 if (r != NULL)
3092 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003093
3094 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 Py_XDECREF(globals);
3096 Py_XDECREF(builtins);
3097 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003100}
3101
3102
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003103/* Module 'imp' provides Python access to the primitives used for
3104 importing modules.
3105*/
3106
Guido van Rossum79f25d91997-04-29 20:08:16 +00003107static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003108imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 buf[0] = (char) ((magic >> 0) & 0xff);
3113 buf[1] = (char) ((magic >> 8) & 0xff);
3114 buf[2] = (char) ((magic >> 16) & 0xff);
3115 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003118}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003119
3120static PyObject *
3121imp_get_magic(PyObject *self, PyObject *noargs)
3122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003124}
3125
3126static PyObject *
3127imp_get_tag(PyObject *self, PyObject *noargs)
3128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003130}
3131
Guido van Rossum79f25d91997-04-29 20:08:16 +00003132static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003133imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 PyObject *list;
3136 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 list = PyList_New(0);
3139 if (list == NULL)
3140 return NULL;
3141 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3142 PyObject *item = Py_BuildValue("ssi",
3143 fdp->suffix, fdp->mode, fdp->type);
3144 if (item == NULL) {
3145 Py_DECREF(list);
3146 return NULL;
3147 }
3148 if (PyList_Append(list, item) < 0) {
3149 Py_DECREF(list);
3150 Py_DECREF(item);
3151 return NULL;
3152 }
3153 Py_DECREF(item);
3154 }
3155 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003156}
3157
Guido van Rossum79f25d91997-04-29 20:08:16 +00003158static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003159call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 extern int fclose(FILE *);
3162 PyObject *fob, *ret;
3163 PyObject *pathobj;
3164 struct filedescr *fdp;
3165 char pathname[MAXPATHLEN+1];
3166 FILE *fp = NULL;
3167 int fd = -1;
3168 char *found_encoding = NULL;
3169 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 pathname[0] = '\0';
3172 if (path == Py_None)
3173 path = NULL;
3174 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3175 if (fdp == NULL)
3176 return NULL;
3177 if (fp != NULL) {
3178 fd = fileno(fp);
3179 if (fd != -1)
3180 fd = dup(fd);
3181 fclose(fp);
3182 fp = NULL;
3183 }
3184 if (fd != -1) {
3185 if (strchr(fdp->mode, 'b') == NULL) {
3186 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3187 memory. */
3188 found_encoding = PyTokenizer_FindEncoding(fd);
3189 lseek(fd, 0, 0); /* Reset position */
3190 if (found_encoding == NULL && PyErr_Occurred())
3191 return NULL;
3192 encoding = (found_encoding != NULL) ? found_encoding :
3193 (char*)PyUnicode_GetDefaultEncoding();
3194 }
3195 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3196 (char*)encoding, NULL, NULL, 1);
3197 if (fob == NULL) {
3198 close(fd);
3199 PyMem_FREE(found_encoding);
3200 return NULL;
3201 }
3202 }
3203 else {
3204 fob = Py_None;
3205 Py_INCREF(fob);
3206 }
3207 pathobj = PyUnicode_DecodeFSDefault(pathname);
3208 ret = Py_BuildValue("NN(ssi)",
3209 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3210 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003213}
3214
Guido van Rossum79f25d91997-04-29 20:08:16 +00003215static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003216imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003217{
Victor Stinnerebc00522010-12-03 17:06:43 +00003218 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 PyObject *ret, *path = NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003220 if (!PyArg_ParseTuple(args, "O&|O:find_module",
3221 PyUnicode_FSConverter, &name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 &path))
3223 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003224 ret = call_find_module(PyBytes_AS_STRING(name), path);
3225 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003227}
3228
3229static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003230imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 char *name;
3233 int ret;
3234 PyObject *m;
3235 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3236 return NULL;
3237 ret = init_builtin(name);
3238 if (ret < 0)
3239 return NULL;
3240 if (ret == 0) {
3241 Py_INCREF(Py_None);
3242 return Py_None;
3243 }
3244 m = PyImport_AddModule(name);
3245 Py_XINCREF(m);
3246 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003247}
3248
Guido van Rossum79f25d91997-04-29 20:08:16 +00003249static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003250imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 char *name;
3253 int ret;
3254 PyObject *m;
3255 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3256 return NULL;
3257 ret = PyImport_ImportFrozenModule(name);
3258 if (ret < 0)
3259 return NULL;
3260 if (ret == 0) {
3261 Py_INCREF(Py_None);
3262 return Py_None;
3263 }
3264 m = PyImport_AddModule(name);
3265 Py_XINCREF(m);
3266 return m;
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 +00003270imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3275 return NULL;
3276 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003277}
3278
Guido van Rossum79f25d91997-04-29 20:08:16 +00003279static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003280imp_is_frozen_package(PyObject *self, PyObject *args)
3281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3285 return NULL;
3286 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003287}
3288
3289static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003290imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 char *name;
3293 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3294 return NULL;
3295 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003296}
3297
Guido van Rossum79f25d91997-04-29 20:08:16 +00003298static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003299imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 char *name;
3302 struct _frozen *p;
3303 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3304 return NULL;
3305 p = find_frozen(name);
3306 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003307}
3308
3309static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003310get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 FILE *fp;
3313 if (mode[0] == 'U')
3314 mode = "r" PY_STDIOTEXTMODE;
3315 if (fob == NULL) {
3316 fp = fopen(pathname, mode);
3317 }
3318 else {
3319 int fd = PyObject_AsFileDescriptor(fob);
3320 if (fd == -1)
3321 return NULL;
3322 if (!_PyVerify_fd(fd))
3323 goto error;
3324 /* the FILE struct gets a new fd, so that it can be closed
3325 * independently of the file descriptor given
3326 */
3327 fd = dup(fd);
3328 if (fd == -1)
3329 goto error;
3330 fp = fdopen(fd, mode);
3331 }
3332 if (fp)
3333 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003334error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 PyErr_SetFromErrno(PyExc_IOError);
3336 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003337}
3338
Guido van Rossum79f25d91997-04-29 20:08:16 +00003339static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003340imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003343 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 PyObject *fob = NULL;
3345 PyObject *m;
3346 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003347 if (!PyArg_ParseTuple(args, "sO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003349 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 &fob))
3351 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003352 fp = get_file(PyBytes_AS_STRING(pathname), fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003354 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 return NULL;
3356 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003357 m = load_compiled_module(name, PyBytes_AS_STRING(pathname), fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003359 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003361}
3362
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003363#ifdef HAVE_DYNAMIC_LOADING
3364
Guido van Rossum79f25d91997-04-29 20:08:16 +00003365static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003366imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003369 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 char *pathname;
3371 PyObject *fob = NULL;
3372 PyObject *m;
3373 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003374 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3375 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003377 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 if (fob) {
3379 fp = get_file(pathname, fob, "r");
3380 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003381 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 return NULL;
3383 }
3384 }
3385 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003386 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 if (fp)
3388 fclose(fp);
3389 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003390}
3391
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003392#endif /* HAVE_DYNAMIC_LOADING */
3393
Guido van Rossum79f25d91997-04-29 20:08:16 +00003394static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003395imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003398 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 PyObject *fob = NULL;
3400 PyObject *m;
3401 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003402 if (!PyArg_ParseTuple(args, "sO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003404 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 &fob))
3406 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003407 fp = get_file(PyBytes_AS_STRING(pathname), fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003409 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 return NULL;
3411 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003412 m = load_source_module(name, PyBytes_AS_STRING(pathname), fp);
3413 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 fclose(fp);
3415 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003416}
3417
Guido van Rossum79f25d91997-04-29 20:08:16 +00003418static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003419imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 char *name;
3422 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003423 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 PyObject * ret;
3425 char *suffix; /* Unused */
3426 char *mode;
3427 int type;
3428 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003429
Victor Stinner1a563032010-10-15 22:43:10 +00003430 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003432 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 &suffix, &mode, &type))
3434 return NULL;
3435 if (*mode) {
3436 /* Mode must start with 'r' or 'U' and must not contain '+'.
3437 Implicit in this test is the assumption that the mode
3438 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3441 PyErr_Format(PyExc_ValueError,
3442 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003443 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 return NULL;
3445 }
3446 }
3447 if (fob == Py_None)
3448 fp = NULL;
3449 else {
3450 fp = get_file(NULL, fob, mode);
3451 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003452 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 return NULL;
3454 }
3455 }
Victor Stinner1a563032010-10-15 22:43:10 +00003456 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3457 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 if (fp)
3459 fclose(fp);
3460 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003461}
3462
3463static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003464imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003467 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 PyObject * ret;
Victor Stinnerebc00522010-12-03 17:06:43 +00003469 if (!PyArg_ParseTuple(args, "sO&:load_package",
3470 &name, PyUnicode_FSConverter, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003472 ret = load_package(name, PyBytes_AS_STRING(pathname));
3473 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003475}
3476
3477static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003478imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 char *name;
3481 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3482 return NULL;
3483 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003484}
3485
Christian Heimes13a7a212008-01-07 17:13:09 +00003486static PyObject *
3487imp_reload(PyObject *self, PyObject *v)
3488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003490}
3491
3492PyDoc_STRVAR(doc_reload,
3493"reload(module) -> module\n\
3494\n\
3495Reload the module. The module must have been successfully imported before.");
3496
Barry Warsaw28a691b2010-04-17 00:19:56 +00003497static PyObject *
3498imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003503 PyObject *pathbytes;
3504 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003505 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003509 args, kws, "O&|O", kwlist,
3510 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003512
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003513 if (debug_override != NULL &&
3514 (debug = PyObject_IsTrue(debug_override)) < 0) {
3515 Py_DECREF(pathbytes);
3516 return NULL;
3517 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003518
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003519 cpathname = make_compiled_pathname(
3520 PyBytes_AS_STRING(pathbytes),
3521 buf, MAXPATHLEN+1, debug);
3522 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 if (cpathname == NULL) {
3525 PyErr_Format(PyExc_SystemError, "path buffer too short");
3526 return NULL;
3527 }
Victor Stinner88bd8912010-10-15 22:46:07 +00003528 return PyUnicode_DecodeFSDefault(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003529}
3530
3531PyDoc_STRVAR(doc_cache_from_source,
3532"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3533\n\
3534The .py file does not need to exist; this simply returns the path to the\n\
3535.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3536will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3537\n\
3538If debug_override is not None, then it must be a boolean and is taken as\n\
3539the value of __debug__ instead.");
3540
3541static PyObject *
3542imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003545
Victor Stinnerebc00522010-12-03 17:06:43 +00003546 PyObject *pathname_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 char *pathname;
3548 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003551 args, kws, "O&", kwlist,
3552 PyUnicode_FSConverter, &pathname_obj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003554
Victor Stinnerebc00522010-12-03 17:06:43 +00003555 pathname = PyBytes_AS_STRING(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 if (make_source_pathname(pathname, buf) == NULL) {
3557 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3558 pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003559 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 return NULL;
3561 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003562 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003564}
3565
3566PyDoc_STRVAR(doc_source_from_cache,
3567"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3568\n\
3569The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3570the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3571does not conform to PEP 3147 format, ValueError will be raised.");
3572
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003573/* Doc strings */
3574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003575PyDoc_STRVAR(doc_imp,
3576"This module provides the components needed to build your own\n\
3577__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003579PyDoc_STRVAR(doc_find_module,
3580"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003581Search for a module. If path is omitted or None, search for a\n\
3582built-in, frozen or special module and continue search in sys.path.\n\
3583The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003584package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003586PyDoc_STRVAR(doc_load_module,
3587"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003588Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003589The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003591PyDoc_STRVAR(doc_get_magic,
3592"get_magic() -> string\n\
3593Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003594
Barry Warsaw28a691b2010-04-17 00:19:56 +00003595PyDoc_STRVAR(doc_get_tag,
3596"get_tag() -> string\n\
3597Return the magic tag for .pyc or .pyo files.");
3598
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003599PyDoc_STRVAR(doc_get_suffixes,
3600"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003601Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003602that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003604PyDoc_STRVAR(doc_new_module,
3605"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003606Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003607The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003609PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003610"lock_held() -> boolean\n\
3611Return True if the import lock is currently held, else False.\n\
3612On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003613
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003614PyDoc_STRVAR(doc_acquire_lock,
3615"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003616Acquires the interpreter's import lock for the current thread.\n\
3617This lock should be used by import hooks to ensure thread-safety\n\
3618when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003619On platforms without threads, this function does nothing.");
3620
3621PyDoc_STRVAR(doc_release_lock,
3622"release_lock() -> None\n\
3623Release the interpreter's import lock.\n\
3624On platforms without threads, this function does nothing.");
3625
Guido van Rossum79f25d91997-04-29 20:08:16 +00003626static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3628 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3629 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3630 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3631 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3632 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3633 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3634 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3635 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3636 {"reload", imp_reload, METH_O, doc_reload},
3637 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3638 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3639 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3640 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3641 /* The rest are obsolete */
3642 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3643 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3644 {"init_builtin", imp_init_builtin, METH_VARARGS},
3645 {"init_frozen", imp_init_frozen, METH_VARARGS},
3646 {"is_builtin", imp_is_builtin, METH_VARARGS},
3647 {"is_frozen", imp_is_frozen, METH_VARARGS},
3648 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003649#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003651#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 {"load_package", imp_load_package, METH_VARARGS},
3653 {"load_source", imp_load_source, METH_VARARGS},
3654 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003655};
3656
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003657static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003658setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 PyObject *v;
3661 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 v = PyLong_FromLong((long)value);
3664 err = PyDict_SetItemString(d, name, v);
3665 Py_XDECREF(v);
3666 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003667}
3668
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003669typedef struct {
3670 PyObject_HEAD
3671} NullImporter;
3672
3673static int
3674NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3675{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003676#ifndef MS_WINDOWS
3677 PyObject *path;
3678 struct stat statbuf;
3679 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3682 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003683
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003684 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3685 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003687
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003688 if (PyBytes_GET_SIZE(path) == 0) {
3689 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 PyErr_SetString(PyExc_ImportError, "empty pathname");
3691 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003693
3694 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3695 Py_DECREF(path);
3696 if (rv == 0) {
3697 /* it exists */
3698 if (S_ISDIR(statbuf.st_mode)) {
3699 /* it's a directory */
3700 PyErr_SetString(PyExc_ImportError, "existing directory");
3701 return -1;
3702 }
3703 }
3704#else /* MS_WINDOWS */
3705 PyObject *pathobj;
3706 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003707 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003708
3709 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3710 return -1;
3711
3712 if (!PyArg_ParseTuple(args, "U:NullImporter",
3713 &pathobj))
3714 return -1;
3715
3716 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3717 PyErr_SetString(PyExc_ImportError, "empty pathname");
3718 return -1;
3719 }
3720
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003721 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003722 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003723 return -1;
3724 /* see issue1293 and issue3677:
3725 * stat() on Windows doesn't recognise paths like
3726 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3727 */
3728 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003729 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003730 if (rv != INVALID_FILE_ATTRIBUTES) {
3731 /* it exists */
3732 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3733 /* it's a directory */
3734 PyErr_SetString(PyExc_ImportError, "existing directory");
3735 return -1;
3736 }
3737 }
3738#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003740}
3741
3742static PyObject *
3743NullImporter_find_module(NullImporter *self, PyObject *args)
3744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003746}
3747
3748static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3750 "Always return None"
3751 },
3752 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003753};
3754
3755
Christian Heimes9cd17752007-11-18 19:35:23 +00003756PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 PyVarObject_HEAD_INIT(NULL, 0)
3758 "imp.NullImporter", /*tp_name*/
3759 sizeof(NullImporter), /*tp_basicsize*/
3760 0, /*tp_itemsize*/
3761 0, /*tp_dealloc*/
3762 0, /*tp_print*/
3763 0, /*tp_getattr*/
3764 0, /*tp_setattr*/
3765 0, /*tp_reserved*/
3766 0, /*tp_repr*/
3767 0, /*tp_as_number*/
3768 0, /*tp_as_sequence*/
3769 0, /*tp_as_mapping*/
3770 0, /*tp_hash */
3771 0, /*tp_call*/
3772 0, /*tp_str*/
3773 0, /*tp_getattro*/
3774 0, /*tp_setattro*/
3775 0, /*tp_as_buffer*/
3776 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3777 "Null importer object", /* tp_doc */
3778 0, /* tp_traverse */
3779 0, /* tp_clear */
3780 0, /* tp_richcompare */
3781 0, /* tp_weaklistoffset */
3782 0, /* tp_iter */
3783 0, /* tp_iternext */
3784 NullImporter_methods, /* tp_methods */
3785 0, /* tp_members */
3786 0, /* tp_getset */
3787 0, /* tp_base */
3788 0, /* tp_dict */
3789 0, /* tp_descr_get */
3790 0, /* tp_descr_set */
3791 0, /* tp_dictoffset */
3792 (initproc)NullImporter_init, /* tp_init */
3793 0, /* tp_alloc */
3794 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003795};
3796
Martin v. Löwis1a214512008-06-11 05:26:20 +00003797static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 PyModuleDef_HEAD_INIT,
3799 "imp",
3800 doc_imp,
3801 0,
3802 imp_methods,
3803 NULL,
3804 NULL,
3805 NULL,
3806 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003807};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003808
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003809PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003810PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 if (PyType_Ready(&PyNullImporter_Type) < 0)
3815 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 m = PyModule_Create(&impmodule);
3818 if (m == NULL)
3819 goto failure;
3820 d = PyModule_GetDict(m);
3821 if (d == NULL)
3822 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3825 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3826 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3827 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3828 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3829 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3830 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3831 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3832 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3833 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 Py_INCREF(&PyNullImporter_Type);
3836 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3837 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003838 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 Py_XDECREF(m);
3840 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003841}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003842
3843
Guido van Rossumb18618d2000-05-03 23:44:39 +00003844/* API for embedding applications that want to add their own entries
3845 to the table of built-in modules. This should normally be called
3846 *before* Py_Initialize(). When the table resize fails, -1 is
3847 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003848
3849 After a similar function by Just van Rossum. */
3850
3851int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003852PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 static struct _inittab *our_copy = NULL;
3855 struct _inittab *p;
3856 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 /* Count the number of entries in both tables */
3859 for (n = 0; newtab[n].name != NULL; n++)
3860 ;
3861 if (n == 0)
3862 return 0; /* Nothing to do */
3863 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3864 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 /* Allocate new memory for the combined table */
3867 p = our_copy;
3868 PyMem_RESIZE(p, struct _inittab, i+n+1);
3869 if (p == NULL)
3870 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 /* Copy the tables into the new memory */
3873 if (our_copy != PyImport_Inittab)
3874 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3875 PyImport_Inittab = our_copy = p;
3876 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003879}
3880
3881/* Shorthand to add a single entry given a name and a function */
3882
3883int
Brett Cannona826f322009-04-02 03:41:46 +00003884PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 newtab[0].name = (char *)name;
3891 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003894}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003895
3896#ifdef __cplusplus
3897}
3898#endif