blob: d6b19e8f97562a0a82095bffdc665860b6836352 [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 */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000022extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimesd3eb5a152008-02-24 00:38:49 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
28#endif
29
Guido van Rossum21d335e1993-10-15 13:01:11 +000030
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000031/* Magic word to reject .pyc files generated by other Python versions.
32 It should change for each incompatible change to the bytecode.
33
34 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000035 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000036 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000037
Guido van Rossum45aecf42006-03-15 04:58:47 +000038 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000039 -U interpeter flag will cause MAGIC+1 being used. They have been
40 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000041
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000042 There were a variety of old schemes for setting the magic number.
43 The current working scheme is to increment the previous value by
44 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000045
Barry Warsaw28a691b2010-04-17 00:19:56 +000046 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
47 number also includes a new "magic tag", i.e. a human readable string used
48 to represent the magic number in __pycache__ directories. When you change
49 the magic number, you must also set a new unique magic tag. Generally this
50 can be named after the Python major version of the magic number bump, but
51 it can really be anything, as long as it's different than anything else
52 that's come before. The tags are included in the following table, starting
53 with Python 3.2a0.
54
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000055 Known values:
56 Python 1.5: 20121
57 Python 1.5.1: 20121
58 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000060 Python 2.0: 50823
61 Python 2.0.1: 50823
62 Python 2.1: 60202
63 Python 2.1.1: 60202
64 Python 2.1.2: 60202
65 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000066 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000067 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000068 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000069 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000070 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000071 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000072 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000073 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000074 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000075 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
77 Python 2.5b3: 62111 (fix wrong code: x += yield)
78 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000080 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000081 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000082 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000083 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 3010 (removed UNARY_CONVERT)
85 3020 (added BUILD_SET)
86 3030 (added keyword-only parameters)
87 3040 (added signature annotations)
88 3050 (print becomes a function)
89 3060 (PEP 3115 metaclass syntax)
90 3061 (string literals become unicode)
91 3071 (PEP 3109 raise changes)
92 3081 (PEP 3137 make __file__ and __name__ unicode)
93 3091 (kill str8 interning)
94 3101 (merge from 2.6a0, see 62151)
95 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000096 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
97 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
98 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +0000100 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000102 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000104 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
105 tag: cpython-32
Tim Peters36515e22001-11-18 04:06:29 +0000106*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000107
Barry Warsaw28a691b2010-04-17 00:19:56 +0000108/* If you change MAGIC, you must change TAG and you must insert the old value
109 into _PyMagicNumberTags below.
110*/
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000111#define MAGIC (3170 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112#define TAG "cpython-32"
113#define CACHEDIR "__pycache__"
114/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000115static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118/* See _PyImport_FixupExtension() below */
119static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000120
Guido van Rossum771c6c81997-10-31 18:37:24 +0000121/* This table is defined in config.c: */
122extern struct _inittab _PyImport_Inittab[];
123
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000124/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000125extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000126
Guido van Rossum771c6c81997-10-31 18:37:24 +0000127struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000128
Guido van Rossumed1170e1999-12-20 21:23:41 +0000129/* these tables define the module suffixes that Python recognizes */
130struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000131
Guido van Rossumed1170e1999-12-20 21:23:41 +0000132static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000134#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000136#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 {".pyc", "rb", PY_COMPILED},
138 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000139};
140
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000142/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143
144void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000145_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 const struct filedescr *scan;
148 struct filedescr *filetab;
149 int countD = 0;
150 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 /* prepare _PyImport_Filetab: copy entries from
153 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
154 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000155#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
157 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000158#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
160 ++countS;
161 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
162 if (filetab == NULL)
163 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000164#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 memcpy(filetab, _PyImport_DynLoadFiletab,
166 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000167#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 memcpy(filetab + countD, _PyImport_StandardFiletab,
169 countS * sizeof(struct filedescr));
170 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (Py_OptimizeFlag) {
175 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
176 for (; filetab->suffix != NULL; filetab++) {
177 if (strcmp(filetab->suffix, ".pyc") == 0)
178 filetab->suffix = ".pyo";
179 }
180 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
Guido van Rossum25ce5661997-08-02 03:10:38 +0000183void
Just van Rossum52e14d62002-12-30 22:08:05 +0000184_PyImportHooks_Init(void)
185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 PyObject *v, *path_hooks = NULL, *zimpimport;
187 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 /* adding sys.path_hooks and sys.path_importer_cache, setting up
190 zipimport */
191 if (PyType_Ready(&PyNullImporter_Type) < 0)
192 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 if (Py_VerboseFlag)
195 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 v = PyList_New(0);
198 if (v == NULL)
199 goto error;
200 err = PySys_SetObject("meta_path", v);
201 Py_DECREF(v);
202 if (err)
203 goto error;
204 v = PyDict_New();
205 if (v == NULL)
206 goto error;
207 err = PySys_SetObject("path_importer_cache", v);
208 Py_DECREF(v);
209 if (err)
210 goto error;
211 path_hooks = PyList_New(0);
212 if (path_hooks == NULL)
213 goto error;
214 err = PySys_SetObject("path_hooks", path_hooks);
215 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000216 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyErr_Print();
218 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
219 "path_importer_cache, or NullImporter failed"
220 );
221 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 zimpimport = PyImport_ImportModule("zipimport");
224 if (zimpimport == NULL) {
225 PyErr_Clear(); /* No zip import module -- okay */
226 if (Py_VerboseFlag)
227 PySys_WriteStderr("# can't import zipimport\n");
228 }
229 else {
230 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
231 "zipimporter");
232 Py_DECREF(zimpimport);
233 if (zipimporter == NULL) {
234 PyErr_Clear(); /* No zipimporter object -- okay */
235 if (Py_VerboseFlag)
236 PySys_WriteStderr(
237 "# can't import zipimport.zipimporter\n");
238 }
239 else {
240 /* sys.path_hooks.append(zipimporter) */
241 err = PyList_Append(path_hooks, zipimporter);
242 Py_DECREF(zipimporter);
243 if (err)
244 goto error;
245 if (Py_VerboseFlag)
246 PySys_WriteStderr(
247 "# installed zipimport hook\n");
248 }
249 }
250 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000251}
252
253void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000254_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_XDECREF(extensions);
257 extensions = NULL;
258 PyMem_DEL(_PyImport_Filetab);
259 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260}
261
262
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000263/* Locking primitives to prevent parallel imports of the same module
264 in different threads to return with a partially loaded module.
265 These calls are serialized by the global interpreter lock. */
266
267#ifdef WITH_THREAD
268
Guido van Rossum49b56061998-10-01 20:42:43 +0000269#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000270
Guido van Rossum65d5b571998-12-21 19:32:43 +0000271static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272static long import_lock_thread = -1;
273static int import_lock_level = 0;
274
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000275void
276_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 long me = PyThread_get_thread_ident();
279 if (me == -1)
280 return; /* Too bad */
281 if (import_lock == NULL) {
282 import_lock = PyThread_allocate_lock();
283 if (import_lock == NULL)
284 return; /* Nothing much we can do. */
285 }
286 if (import_lock_thread == me) {
287 import_lock_level++;
288 return;
289 }
290 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
291 {
292 PyThreadState *tstate = PyEval_SaveThread();
293 PyThread_acquire_lock(import_lock, 1);
294 PyEval_RestoreThread(tstate);
295 }
296 import_lock_thread = me;
297 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000298}
299
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000300int
301_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 long me = PyThread_get_thread_ident();
304 if (me == -1 || import_lock == NULL)
305 return 0; /* Too bad */
306 if (import_lock_thread != me)
307 return -1;
308 import_lock_level--;
309 if (import_lock_level == 0) {
310 import_lock_thread = -1;
311 PyThread_release_lock(import_lock);
312 }
313 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000314}
315
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000316/* This function is called from PyOS_AfterFork to ensure that newly
317 created child processes do not share locks with the parent.
318 We now acquire the import lock around fork() calls but on some platforms
319 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000320
321void
322_PyImport_ReInitLock(void)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (import_lock != NULL)
325 import_lock = PyThread_allocate_lock();
326 import_lock_thread = -1;
327 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000328}
329
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000330#endif
331
Tim Peters69232342001-08-30 05:16:13 +0000332static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000333imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000334{
Tim Peters69232342001-08-30 05:16:13 +0000335#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000337#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000339#endif
340}
341
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000343imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000344{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000347#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_INCREF(Py_None);
349 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000350}
351
352static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000353imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000354{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000355#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (_PyImport_ReleaseLock() < 0) {
357 PyErr_SetString(PyExc_RuntimeError,
358 "not holding the import lock");
359 return NULL;
360 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 Py_INCREF(Py_None);
363 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000364}
365
Guido van Rossumd8faa362007-04-27 19:54:29 +0000366static void
367imp_modules_reloading_clear(void)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 PyInterpreterState *interp = PyThreadState_Get()->interp;
370 if (interp->modules_reloading != NULL)
371 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000372}
373
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374/* Helper for sys */
375
376PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000377PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyInterpreterState *interp = PyThreadState_GET()->interp;
380 if (interp->modules == NULL)
381 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
382 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383}
384
Guido van Rossum3f5da241990-12-20 15:06:42 +0000385
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000386/* List of names to clear in sys */
387static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 "path", "argv", "ps1", "ps2",
389 "last_type", "last_value", "last_traceback",
390 "path_hooks", "path_importer_cache", "meta_path",
391 /* misc stuff */
392 "flags", "float_info",
393 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000394};
395
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000396static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 "stdin", "__stdin__",
398 "stdout", "__stdout__",
399 "stderr", "__stderr__",
400 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000401};
402
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000403
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000404/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000405
Guido van Rossum3f5da241990-12-20 15:06:42 +0000406void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000407PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 Py_ssize_t pos, ndone;
410 char *name;
411 PyObject *key, *value, *dict;
412 PyInterpreterState *interp = PyThreadState_GET()->interp;
413 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (modules == NULL)
416 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 /* Delete some special variables first. These are common
419 places where user values hide and people complain when their
420 destructors fail. Since the modules containing them are
421 deleted *last* of all, they would come too late in the normal
422 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 value = PyDict_GetItemString(modules, "builtins");
425 if (value != NULL && PyModule_Check(value)) {
426 dict = PyModule_GetDict(value);
427 if (Py_VerboseFlag)
428 PySys_WriteStderr("# clear builtins._\n");
429 PyDict_SetItemString(dict, "_", Py_None);
430 }
431 value = PyDict_GetItemString(modules, "sys");
432 if (value != NULL && PyModule_Check(value)) {
433 char **p;
434 PyObject *v;
435 dict = PyModule_GetDict(value);
436 for (p = sys_deletes; *p != NULL; p++) {
437 if (Py_VerboseFlag)
438 PySys_WriteStderr("# clear sys.%s\n", *p);
439 PyDict_SetItemString(dict, *p, Py_None);
440 }
441 for (p = sys_files; *p != NULL; p+=2) {
442 if (Py_VerboseFlag)
443 PySys_WriteStderr("# restore sys.%s\n", *p);
444 v = PyDict_GetItemString(dict, *(p+1));
445 if (v == NULL)
446 v = Py_None;
447 PyDict_SetItemString(dict, *p, v);
448 }
449 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* First, delete __main__ */
452 value = PyDict_GetItemString(modules, "__main__");
453 if (value != NULL && PyModule_Check(value)) {
454 if (Py_VerboseFlag)
455 PySys_WriteStderr("# cleanup __main__\n");
456 _PyModule_Clear(value);
457 PyDict_SetItemString(modules, "__main__", Py_None);
458 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* The special treatment of "builtins" here is because even
461 when it's not referenced as a module, its dictionary is
462 referenced by almost every module's __builtins__. Since
463 deleting a module clears its dictionary (even if there are
464 references left to it), we need to delete the "builtins"
465 module last. Likewise, we don't delete sys until the very
466 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 Also note that we 'delete' modules by replacing their entry
469 in the modules dict with None, rather than really deleting
470 them; this avoids a rehash of the modules dictionary and
471 also marks them as "non existent" so they won't be
472 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Next, repeatedly delete modules with a reference count of
475 one (skipping builtins and sys) and delete them */
476 do {
477 ndone = 0;
478 pos = 0;
479 while (PyDict_Next(modules, &pos, &key, &value)) {
480 if (value->ob_refcnt != 1)
481 continue;
482 if (PyUnicode_Check(key) && PyModule_Check(value)) {
483 name = _PyUnicode_AsString(key);
484 if (strcmp(name, "builtins") == 0)
485 continue;
486 if (strcmp(name, "sys") == 0)
487 continue;
488 if (Py_VerboseFlag)
489 PySys_WriteStderr(
490 "# cleanup[1] %s\n", name);
491 _PyModule_Clear(value);
492 PyDict_SetItem(modules, key, Py_None);
493 ndone++;
494 }
495 }
496 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* Next, delete all modules (still skipping builtins and sys) */
499 pos = 0;
500 while (PyDict_Next(modules, &pos, &key, &value)) {
501 if (PyUnicode_Check(key) && PyModule_Check(value)) {
502 name = _PyUnicode_AsString(key);
503 if (strcmp(name, "builtins") == 0)
504 continue;
505 if (strcmp(name, "sys") == 0)
506 continue;
507 if (Py_VerboseFlag)
508 PySys_WriteStderr("# cleanup[2] %s\n", name);
509 _PyModule_Clear(value);
510 PyDict_SetItem(modules, key, Py_None);
511 }
512 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 /* Next, delete sys and builtins (in that order) */
515 value = PyDict_GetItemString(modules, "sys");
516 if (value != NULL && PyModule_Check(value)) {
517 if (Py_VerboseFlag)
518 PySys_WriteStderr("# cleanup sys\n");
519 _PyModule_Clear(value);
520 PyDict_SetItemString(modules, "sys", Py_None);
521 }
522 value = PyDict_GetItemString(modules, "builtins");
523 if (value != NULL && PyModule_Check(value)) {
524 if (Py_VerboseFlag)
525 PySys_WriteStderr("# cleanup builtins\n");
526 _PyModule_Clear(value);
527 PyDict_SetItemString(modules, "builtins", Py_None);
528 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* Finally, clear and delete the modules directory */
531 PyDict_Clear(modules);
532 interp->modules = NULL;
533 Py_DECREF(modules);
534 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000535}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000536
537
Barry Warsaw28a691b2010-04-17 00:19:56 +0000538/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000539
540long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000541PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000544}
545
546
Barry Warsaw28a691b2010-04-17 00:19:56 +0000547const char *
548PyImport_GetMagicTag(void)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000551}
552
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553/* Magic for extension modules (built-in as well as dynamically
554 loaded). To prevent initializing an extension module more than
555 once, we keep a static dictionary 'extensions' keyed by module name
556 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000557 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558 dictionary is stored by calling _PyImport_FixupExtension()
559 immediately after the module initialization function succeeds. A
560 copy can be retrieved from there by calling
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000561 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000562
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000563 Modules which do support multiple initialization set their m_size
564 field to a non-negative number (indicating the size of the
565 module-specific state). They are still recorded in the extensions
566 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000567*/
568
569int
570_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 PyObject *modules, *dict;
573 struct PyModuleDef *def;
574 if (extensions == NULL) {
575 extensions = PyDict_New();
576 if (extensions == NULL)
577 return -1;
578 }
579 if (mod == NULL || !PyModule_Check(mod)) {
580 PyErr_BadInternalCall();
581 return -1;
582 }
583 def = PyModule_GetDef(mod);
584 if (!def) {
585 PyErr_BadInternalCall();
586 return -1;
587 }
588 modules = PyImport_GetModuleDict();
589 if (PyDict_SetItemString(modules, name, mod) < 0)
590 return -1;
591 if (_PyState_AddModule(mod, def) < 0) {
592 PyDict_DelItemString(modules, name);
593 return -1;
594 }
595 if (def->m_size == -1) {
596 if (def->m_base.m_copy) {
597 /* Somebody already imported the module,
598 likely under a different name.
599 XXX this should really not happen. */
600 Py_DECREF(def->m_base.m_copy);
601 def->m_base.m_copy = NULL;
602 }
603 dict = PyModule_GetDict(mod);
604 if (dict == NULL)
605 return -1;
606 def->m_base.m_copy = PyDict_Copy(dict);
607 if (def->m_base.m_copy == NULL)
608 return -1;
609 }
610 PyDict_SetItemString(extensions, filename, (PyObject*)def);
611 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000612}
613
614PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000615_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyObject *mod, *mdict;
618 PyModuleDef* def;
619 if (extensions == NULL)
620 return NULL;
621 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
622 if (def == NULL)
623 return NULL;
624 if (def->m_size == -1) {
625 /* Module does not support repeated initialization */
626 if (def->m_base.m_copy == NULL)
627 return NULL;
628 mod = PyImport_AddModule(name);
629 if (mod == NULL)
630 return NULL;
631 mdict = PyModule_GetDict(mod);
632 if (mdict == NULL)
633 return NULL;
634 if (PyDict_Update(mdict, def->m_base.m_copy))
635 return NULL;
636 }
637 else {
638 if (def->m_base.m_init == NULL)
639 return NULL;
640 mod = def->m_base.m_init();
641 if (mod == NULL)
642 return NULL;
643 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
644 Py_DECREF(mod);
645 }
646 if (_PyState_AddModule(mod, def) < 0) {
647 PyDict_DelItemString(PyImport_GetModuleDict(), name);
648 Py_DECREF(mod);
649 return NULL;
650 }
651 if (Py_VerboseFlag)
652 PySys_WriteStderr("import %s # previously loaded (%s)\n",
653 name, filename);
654 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000655
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656}
657
658
659/* Get the module object corresponding to a module name.
660 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000661 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000662 Because the former action is most common, THIS DOES NOT RETURN A
663 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000664
Guido van Rossum79f25d91997-04-29 20:08:16 +0000665PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000666PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyObject *modules = PyImport_GetModuleDict();
669 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
672 PyModule_Check(m))
673 return m;
674 m = PyModule_New(name);
675 if (m == NULL)
676 return NULL;
677 if (PyDict_SetItemString(modules, name, m) != 0) {
678 Py_DECREF(m);
679 return NULL;
680 }
681 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684}
685
Tim Peters1cd70172004-08-02 03:52:12 +0000686/* Remove name from sys.modules, if it's there. */
687static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000688remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyObject *modules = PyImport_GetModuleDict();
691 if (PyDict_GetItemString(modules, name) == NULL)
692 return;
693 if (PyDict_DelItemString(modules, name) < 0)
694 Py_FatalError("import: deleting existing key in"
695 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000696}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697
Barry Warsaw28a691b2010-04-17 00:19:56 +0000698static PyObject * get_sourcefile(char *file);
699static char *make_source_pathname(char *pathname, char *buf);
700static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000702
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000703/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000704 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
705 * removed from sys.modules, to avoid leaving damaged module objects
706 * in sys.modules. The caller may wish to restore the original
707 * module object (if any) in this case; PyImport_ReloadModule is an
708 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000709 *
710 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
711 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000712 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000713PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000714PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return PyImport_ExecCodeModuleWithPathnames(
717 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000718}
719
720PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000721PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return PyImport_ExecCodeModuleWithPathnames(
724 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000725}
726
727PyObject *
728PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyObject *modules = PyImport_GetModuleDict();
732 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 m = PyImport_AddModule(name);
735 if (m == NULL)
736 return NULL;
737 /* If the module is being reloaded, we get the old module back
738 and re-use its dict to exec the new code. */
739 d = PyModule_GetDict(m);
740 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
741 if (PyDict_SetItemString(d, "__builtins__",
742 PyEval_GetBuiltins()) != 0)
743 goto error;
744 }
745 /* Remember the filename as the __file__ attribute */
746 v = NULL;
747 if (pathname != NULL) {
748 v = get_sourcefile(pathname);
749 if (v == NULL)
750 PyErr_Clear();
751 }
752 if (v == NULL) {
753 v = ((PyCodeObject *)co)->co_filename;
754 Py_INCREF(v);
755 }
756 if (PyDict_SetItemString(d, "__file__", v) != 0)
757 PyErr_Clear(); /* Not important enough to report */
758 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* Remember the pyc path name as the __cached__ attribute. */
761 if (cpathname == NULL) {
762 v = Py_None;
763 Py_INCREF(v);
764 }
765 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
766 PyErr_Clear(); /* Not important enough to report */
767 v = Py_None;
768 Py_INCREF(v);
769 }
770 if (PyDict_SetItemString(d, "__cached__", v) != 0)
771 PyErr_Clear(); /* Not important enough to report */
772 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
775 if (v == NULL)
776 goto error;
777 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
780 PyErr_Format(PyExc_ImportError,
781 "Loaded module %.200s not found in sys.modules",
782 name);
783 return NULL;
784 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000789
790 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 remove_module(name);
792 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793}
794
795
Barry Warsaw28a691b2010-04-17 00:19:56 +0000796/* Like strrchr(string, '/') but searches for the rightmost of either SEP
797 or ALTSEP, if the latter is defined.
798*/
799static char *
800rightmost_sep(char *s)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 char *found, c;
803 for (found = NULL; (c = *s); s++) {
804 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000805#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000807#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 )
809 {
810 found = s;
811 }
812 }
813 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000814}
815
816
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817/* Given a pathname for a Python source file, fill a buffer with the
818 pathname for the corresponding compiled file. Return the pathname
819 for the compiled file, or NULL if there's no space in the buffer.
820 Doesn't set an exception. */
821
822static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000823make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 /* foo.py -> __pycache__/foo.<tag>.pyc */
826 size_t len = strlen(pathname);
827 size_t i, save;
828 char *pos;
829 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Sanity check that the buffer has roughly enough space to hold what
832 will eventually be the full path to the compiled file. The 5 extra
833 bytes include the slash afer __pycache__, the two extra dots, the
834 extra trailing character ('c' or 'o') and null. This isn't exact
835 because the contents of the buffer can affect how many actual
836 characters of the string get into the buffer. We'll do a final
837 sanity check before writing the extension to ensure we do not
838 overflow the buffer.
839 */
840 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
841 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Find the last path separator and copy everything from the start of
844 the source string up to and including the separator.
845 */
846 if ((pos = rightmost_sep(pathname)) == NULL) {
847 i = 0;
848 }
849 else {
850 sep = *pos;
851 i = pos - pathname + 1;
852 strncpy(buf, pathname, i);
853 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 save = i;
856 buf[i++] = '\0';
857 /* Add __pycache__/ */
858 strcat(buf, CACHEDIR);
859 i += strlen(CACHEDIR) - 1;
860 buf[i++] = sep;
861 buf[i++] = '\0';
862 /* Add the base filename, but remove the .py or .pyw extension, since
863 the tag name must go before the extension.
864 */
865 strcat(buf, pathname + save);
866 if ((pos = strrchr(buf, '.')) != NULL)
867 *++pos = '\0';
868 strcat(buf, pyc_tag);
869 /* The length test above assumes that we're only adding one character
870 to the end of what would normally be the extension. What if there
871 is no extension, or the string ends in '.' or '.p', and otherwise
872 fills the buffer? By appending 4 more characters onto the string
873 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 As a simple example, let's say buflen=32 and the input string is
876 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 which is false and so the name mangling would continue. This would
881 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
886 We can even handle an input string of say 'xxxxx' above because
887 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
888 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 which is 32 characters including the nul, and thus fits in the
893 buffer. However, an input string of 'xxxxxx' would yield a result
894 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 which is 33 characters long (including the nul), thus overflowing
899 the buffer, even though the first test would fail, i.e.: the input
900 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 The reason the first test fails but we still overflow the buffer is
903 that the test above only expects to add one extra character to be
904 added to the extension, and here we're adding three (pyc). We
905 don't add the first dot, so that reclaims one of expected
906 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
907 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 The best we can do is ensure that we still have enough room in the
910 target buffer before we write the extension. Because it's always
911 only the extension that can cause the overflow, and never the other
912 path bytes we've written, it's sufficient to just do one more test
913 here. Still, the assertion that follows can't hurt.
914 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000915#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000917#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (strlen(buf) + 5 > buflen)
919 return NULL;
920 strcat(buf, debug ? ".pyc" : ".pyo");
921 assert(strlen(buf) < buflen);
922 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000923}
924
925
Barry Warsaw28a691b2010-04-17 00:19:56 +0000926/* Given a pathname to a Python byte compiled file, return the path to the
927 source file, if the path matches the PEP 3147 format. This does not check
928 for any file existence, however, if the pyc file name does not match PEP
929 3147 style, NULL is returned. buf must be at least as big as pathname;
930 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931
Barry Warsaw28a691b2010-04-17 00:19:56 +0000932static char *
933make_source_pathname(char *pathname, char *buf)
934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* __pycache__/foo.<tag>.pyc -> foo.py */
936 size_t i, j;
937 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* Look back two slashes from the end. In between these two slashes
940 must be the string __pycache__ or this is not a PEP 3147 style
941 path. It's possible for there to be only one slash.
942 */
943 if ((right = rightmost_sep(pathname)) == NULL)
944 return NULL;
945 sep = *right;
946 *right = '\0';
947 left = rightmost_sep(pathname);
948 *right = sep;
949 if (left == NULL)
950 left = pathname;
951 else
952 left++;
953 if (right-left != strlen(CACHEDIR) ||
954 strncmp(left, CACHEDIR, right-left) != 0)
955 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* Now verify that the path component to the right of the last slash
958 has two dots in it.
959 */
960 if ((dot0 = strchr(right + 1, '.')) == NULL)
961 return NULL;
962 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
963 return NULL;
964 /* Too many dots? */
965 if (strchr(dot1 + 1, '.') != NULL)
966 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* This is a PEP 3147 path. Start by copying everything from the
969 start of pathname up to and including the leftmost slash. Then
970 copy the file's basename, removing the magic tag and adding a .py
971 suffix.
972 */
973 strncpy(buf, pathname, (i=left-pathname));
974 strncpy(buf+i, right+1, (j=dot0-right));
975 strcpy(buf+i+j, "py");
976 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000977}
978
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000979/* Given a pathname for a Python source file, its time of last
980 modification, and a pathname for a compiled file, check whether the
981 compiled file represents the same version of the source. If so,
982 return a FILE pointer for the compiled file, positioned just after
983 the header; if not, return NULL.
984 Doesn't set an exception. */
985
986static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000987check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 FILE *fp;
990 long magic;
991 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 fp = fopen(cpathname, "rb");
994 if (fp == NULL)
995 return NULL;
996 magic = PyMarshal_ReadLongFromFile(fp);
997 if (magic != pyc_magic) {
998 if (Py_VerboseFlag)
999 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1000 fclose(fp);
1001 return NULL;
1002 }
1003 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1004 if (pyc_mtime != mtime) {
1005 if (Py_VerboseFlag)
1006 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1007 fclose(fp);
1008 return NULL;
1009 }
1010 if (Py_VerboseFlag)
1011 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1012 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001013}
1014
1015
1016/* Read a code object from a file and check it for validity */
1017
Guido van Rossum79f25d91997-04-29 20:08:16 +00001018static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001019read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 co = PyMarshal_ReadLastObjectFromFile(fp);
1024 if (co == NULL)
1025 return NULL;
1026 if (!PyCode_Check(co)) {
1027 PyErr_Format(PyExc_ImportError,
1028 "Non-code object in %.200s", cpathname);
1029 Py_DECREF(co);
1030 return NULL;
1031 }
1032 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001033}
1034
1035
1036/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001037 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001038
Guido van Rossum79f25d91997-04-29 20:08:16 +00001039static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001040load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 long magic;
1043 PyCodeObject *co;
1044 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 magic = PyMarshal_ReadLongFromFile(fp);
1047 if (magic != pyc_magic) {
1048 PyErr_Format(PyExc_ImportError,
1049 "Bad magic number in %.200s", cpathname);
1050 return NULL;
1051 }
1052 (void) PyMarshal_ReadLongFromFile(fp);
1053 co = read_compiled_module(cpathname, fp);
1054 if (co == NULL)
1055 return NULL;
1056 if (Py_VerboseFlag)
1057 PySys_WriteStderr("import %s # precompiled from %s\n",
1058 name, cpathname);
1059 m = PyImport_ExecCodeModuleWithPathnames(
1060 name, (PyObject *)co, cpathname, cpathname);
1061 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064}
1065
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001066/* Parse a source file and return the corresponding code object */
1067
Guido van Rossum79f25d91997-04-29 20:08:16 +00001068static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyCodeObject *co = NULL;
1072 mod_ty mod;
1073 PyCompilerFlags flags;
1074 PyArena *arena = PyArena_New();
1075 if (arena == NULL)
1076 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 flags.cf_flags = 0;
1079 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1080 Py_file_input, 0, 0, &flags,
1081 NULL, arena);
1082 if (mod) {
1083 co = PyAST_Compile(mod, pathname, NULL, arena);
1084 }
1085 PyArena_Free(arena);
1086 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001087}
1088
1089
Guido van Rossum55a83382000-09-20 20:31:38 +00001090/* Helper to open a bytecode file for writing in exclusive mode */
1091
1092static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001093open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001094{
1095#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Use O_EXCL to avoid a race condition when another process tries to
1097 write the same file. When that happens, our open() call fails,
1098 which is just fine (since it's only a cache).
1099 XXX If the file exists and is writable but the directory is not
1100 writable, the file will never be written. Oh well.
1101 */
1102 int fd;
1103 (void) unlink(filename);
1104 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001105#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001107#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001108#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001110#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001112#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 );
1114 if (fd < 0)
1115 return NULL;
1116 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001117#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* Best we can do -- on Windows this can't happen anyway */
1119 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001120#endif
1121}
1122
1123
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001124/* Write a compiled module to a file, placing the time of last
1125 modification of its source into the header.
1126 Errors are ignored, if a write error occurs an attempt is made to
1127 remove the file. */
1128
1129static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001130write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 FILE *fp;
1133 char *dirpath;
1134 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001135#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 mode_t mode = srcstat->st_mode & ~S_IEXEC;
1137 mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct
1138 for Windows?
1139 2010-04-07 BAW */
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001140#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1142 mode_t dirmode = (srcstat->st_mode |
1143 S_IXUSR | S_IXGRP | S_IXOTH |
1144 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001145#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 /* Ensure that the __pycache__ directory exists. */
1149 dirpath = rightmost_sep(cpathname);
1150 if (dirpath == NULL) {
1151 if (Py_VerboseFlag)
1152 PySys_WriteStderr(
1153 "# no %s path found %s\n",
1154 CACHEDIR, cpathname);
1155 return;
1156 }
1157 saved = *dirpath;
1158 *dirpath = '\0';
1159 /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */
1160 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
1161 *dirpath = saved;
1162 if (Py_VerboseFlag)
1163 PySys_WriteStderr(
1164 "# cannot create cache dir %s\n", cpathname);
1165 return;
1166 }
1167 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 fp = open_exclusive(cpathname, mode);
1170 if (fp == NULL) {
1171 if (Py_VerboseFlag)
1172 PySys_WriteStderr(
1173 "# can't create %s\n", cpathname);
1174 return;
1175 }
1176 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1177 /* First write a 0 for mtime */
1178 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1179 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1180 if (fflush(fp) != 0 || ferror(fp)) {
1181 if (Py_VerboseFlag)
1182 PySys_WriteStderr("# can't write %s\n", cpathname);
1183 /* Don't keep partial file */
1184 fclose(fp);
1185 (void) unlink(cpathname);
1186 return;
1187 }
1188 /* Now write the true mtime */
1189 fseek(fp, 4L, 0);
1190 assert(mtime < LONG_MAX);
1191 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1192 fflush(fp);
1193 fclose(fp);
1194 if (Py_VerboseFlag)
1195 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001196}
1197
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001198static void
1199update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyObject *constants, *tmp;
1202 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (PyUnicode_Compare(co->co_filename, oldname))
1205 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 tmp = co->co_filename;
1208 co->co_filename = newname;
1209 Py_INCREF(co->co_filename);
1210 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 constants = co->co_consts;
1213 n = PyTuple_GET_SIZE(constants);
1214 for (i = 0; i < n; i++) {
1215 tmp = PyTuple_GET_ITEM(constants, i);
1216 if (PyCode_Check(tmp))
1217 update_code_filenames((PyCodeObject *)tmp,
1218 oldname, newname);
1219 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001220}
1221
1222static int
1223update_compiled_module(PyCodeObject *co, char *pathname)
1224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 newname = PyUnicode_DecodeFSDefault(pathname);
1228 if (newname == NULL)
1229 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (!PyUnicode_Compare(co->co_filename, newname)) {
1232 Py_DECREF(newname);
1233 return 0;
1234 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 oldname = co->co_filename;
1237 Py_INCREF(oldname);
1238 update_code_filenames(co, oldname, newname);
1239 Py_DECREF(oldname);
1240 Py_DECREF(newname);
1241 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001242}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243
1244/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001245 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1246 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247
Guido van Rossum79f25d91997-04-29 20:08:16 +00001248static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001249load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 struct stat st;
1252 FILE *fpc;
1253 char buf[MAXPATHLEN+1];
1254 char *cpathname;
1255 PyCodeObject *co;
1256 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (fstat(fileno(fp), &st) != 0) {
1259 PyErr_Format(PyExc_RuntimeError,
1260 "unable to get file status from '%s'",
1261 pathname);
1262 return NULL;
1263 }
Fred Drake4c82b232000-06-30 16:18:57 +00001264#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 /* Python's .pyc timestamp handling presumes that the timestamp fits
1266 in 4 bytes. This will be fine until sometime in the year 2038,
1267 when a 4-byte signed time_t will overflow.
1268 */
1269 if (st.st_mtime >> 32) {
1270 PyErr_SetString(PyExc_OverflowError,
1271 "modification time overflows a 4 byte field");
1272 return NULL;
1273 }
Fred Drake4c82b232000-06-30 16:18:57 +00001274#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 cpathname = make_compiled_pathname(
1276 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1277 if (cpathname != NULL &&
1278 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1279 co = read_compiled_module(cpathname, fpc);
1280 fclose(fpc);
1281 if (co == NULL)
1282 return NULL;
1283 if (update_compiled_module(co, pathname) < 0)
1284 return NULL;
1285 if (Py_VerboseFlag)
1286 PySys_WriteStderr("import %s # precompiled from %s\n",
1287 name, cpathname);
1288 pathname = cpathname;
1289 }
1290 else {
1291 co = parse_source_module(pathname, fp);
1292 if (co == NULL)
1293 return NULL;
1294 if (Py_VerboseFlag)
1295 PySys_WriteStderr("import %s # from %s\n",
1296 name, pathname);
1297 if (cpathname) {
1298 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1299 if (ro == NULL || !PyObject_IsTrue(ro))
1300 write_compiled_module(co, cpathname, &st);
1301 }
1302 }
1303 m = PyImport_ExecCodeModuleWithPathnames(
1304 name, (PyObject *)co, pathname, cpathname);
1305 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001308}
1309
Christian Heimes3b06e532008-01-07 20:12:44 +00001310/* Get source file -> unicode or None
1311 * Returns the path to the py file if available, else the given path
1312 */
1313static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001314get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 char py[MAXPATHLEN + 1];
1317 Py_ssize_t len;
1318 PyObject *u;
1319 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!file || !*file) {
1322 Py_RETURN_NONE;
1323 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 len = strlen(file);
1326 /* match '*.py?' */
1327 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1328 return PyUnicode_DecodeFSDefault(file);
1329 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* Start by trying to turn PEP 3147 path into source path. If that
1332 * fails, just chop off the trailing character, i.e. legacy pyc path
1333 * to py.
1334 */
1335 if (make_source_pathname(file, py) == NULL) {
1336 strncpy(py, file, len-1);
1337 py[len-1] = '\0';
1338 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (stat(py, &statbuf) == 0 &&
1341 S_ISREG(statbuf.st_mode)) {
1342 u = PyUnicode_DecodeFSDefault(py);
1343 }
1344 else {
1345 u = PyUnicode_DecodeFSDefault(file);
1346 }
1347 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001348}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001349
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001350/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001351static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1352static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001354static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001355
1356/* Load a package and return its module object WITH INCREMENTED
1357 REFERENCE COUNT */
1358
1359static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001360load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *m, *d;
1363 PyObject *file = NULL;
1364 PyObject *path = NULL;
1365 int err;
1366 char buf[MAXPATHLEN+1];
1367 FILE *fp = NULL;
1368 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 m = PyImport_AddModule(name);
1371 if (m == NULL)
1372 return NULL;
1373 if (Py_VerboseFlag)
1374 PySys_WriteStderr("import %s # directory %s\n",
1375 name, pathname);
1376 d = PyModule_GetDict(m);
1377 file = get_sourcefile(pathname);
1378 if (file == NULL)
1379 goto error;
1380 path = Py_BuildValue("[O]", file);
1381 if (path == NULL)
1382 goto error;
1383 err = PyDict_SetItemString(d, "__file__", file);
1384 if (err == 0)
1385 err = PyDict_SetItemString(d, "__path__", path);
1386 if (err != 0)
1387 goto error;
1388 buf[0] = '\0';
1389 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1390 if (fdp == NULL) {
1391 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1392 PyErr_Clear();
1393 Py_INCREF(m);
1394 }
1395 else
1396 m = NULL;
1397 goto cleanup;
1398 }
1399 m = load_module(name, fp, buf, fdp->type, NULL);
1400 if (fp != NULL)
1401 fclose(fp);
1402 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001403
1404 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001406 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 Py_XDECREF(path);
1408 Py_XDECREF(file);
1409 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001410}
1411
1412
1413/* Helper to test for built-in module */
1414
1415static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001416is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 int i;
1419 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1420 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1421 if (PyImport_Inittab[i].initfunc == NULL)
1422 return -1;
1423 else
1424 return 1;
1425 }
1426 }
1427 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001428}
1429
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001430
Just van Rossum52e14d62002-12-30 22:08:05 +00001431/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1432 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001433 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001434 that can handle the path item. Return None if no hook could;
1435 this tells our caller it should fall back to the builtin
1436 import mechanism. Cache the result in path_importer_cache.
1437 Returns a borrowed reference. */
1438
1439static PyObject *
1440get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyObject *importer;
1444 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 /* These conditions are the caller's responsibility: */
1447 assert(PyList_Check(path_hooks));
1448 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 nhooks = PyList_Size(path_hooks);
1451 if (nhooks < 0)
1452 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 importer = PyDict_GetItem(path_importer_cache, p);
1455 if (importer != NULL)
1456 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 /* set path_importer_cache[p] to None to avoid recursion */
1459 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1460 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 for (j = 0; j < nhooks; j++) {
1463 PyObject *hook = PyList_GetItem(path_hooks, j);
1464 if (hook == NULL)
1465 return NULL;
1466 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1467 if (importer != NULL)
1468 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1471 return NULL;
1472 }
1473 PyErr_Clear();
1474 }
1475 if (importer == NULL) {
1476 importer = PyObject_CallFunctionObjArgs(
1477 (PyObject *)&PyNullImporter_Type, p, NULL
1478 );
1479 if (importer == NULL) {
1480 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1481 PyErr_Clear();
1482 return Py_None;
1483 }
1484 }
1485 }
1486 if (importer != NULL) {
1487 int err = PyDict_SetItem(path_importer_cache, p, importer);
1488 Py_DECREF(importer);
1489 if (err != 0)
1490 return NULL;
1491 }
1492 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001493}
1494
Christian Heimes9cd17752007-11-18 19:35:23 +00001495PyAPI_FUNC(PyObject *)
1496PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1500 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1501 importer = get_path_importer(path_importer_cache,
1502 path_hooks, path);
1503 }
1504 }
1505 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1506 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001507}
1508
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001509/* Search the path (default sys.path) for a module. Return the
1510 corresponding filedescr struct, and (via return arguments) the
1511 pathname and an open file. Return NULL if the module is not found. */
1512
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001513#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001514extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001516#endif
1517
Martin v. Löwis18e16552006-02-15 17:27:45 +00001518static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001519static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001520static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001521
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001522static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001523find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 Py_ssize_t i, npath;
1527 size_t len, namelen;
1528 struct filedescr *fdp = NULL;
1529 char *filemode;
1530 FILE *fp = NULL;
1531 PyObject *path_hooks, *path_importer_cache;
1532 struct stat statbuf;
1533 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1534 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1535 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1536 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001537#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 size_t saved_len;
1539 size_t saved_namelen;
1540 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001541#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (p_loader != NULL)
1543 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (strlen(subname) > MAXPATHLEN) {
1546 PyErr_SetString(PyExc_OverflowError,
1547 "module name is too long");
1548 return NULL;
1549 }
1550 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* sys.meta_path import hook */
1553 if (p_loader != NULL) {
1554 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 meta_path = PySys_GetObject("meta_path");
1557 if (meta_path == NULL || !PyList_Check(meta_path)) {
1558 PyErr_SetString(PyExc_ImportError,
1559 "sys.meta_path must be a list of "
1560 "import hooks");
1561 return NULL;
1562 }
1563 Py_INCREF(meta_path); /* zap guard */
1564 npath = PyList_Size(meta_path);
1565 for (i = 0; i < npath; i++) {
1566 PyObject *loader;
1567 PyObject *hook = PyList_GetItem(meta_path, i);
1568 loader = PyObject_CallMethod(hook, "find_module",
1569 "sO", fullname,
1570 path != NULL ?
1571 path : Py_None);
1572 if (loader == NULL) {
1573 Py_DECREF(meta_path);
1574 return NULL; /* true error */
1575 }
1576 if (loader != Py_None) {
1577 /* a loader was found */
1578 *p_loader = loader;
1579 Py_DECREF(meta_path);
1580 return &importhookdescr;
1581 }
1582 Py_DECREF(loader);
1583 }
1584 Py_DECREF(meta_path);
1585 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if (find_frozen(fullname) != NULL) {
1588 strcpy(buf, fullname);
1589 return &fd_frozen;
1590 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (path == NULL) {
1593 if (is_builtin(name)) {
1594 strcpy(buf, name);
1595 return &fd_builtin;
1596 }
Guido van Rossumac279101996-08-22 23:10:58 +00001597#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1599 if (fp != NULL) {
1600 *p_fp = fp;
1601 return fdp;
1602 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001603#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 path = PySys_GetObject("path");
1605 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (path == NULL || !PyList_Check(path)) {
1608 PyErr_SetString(PyExc_ImportError,
1609 "sys.path must be a list of directory names");
1610 return NULL;
1611 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 path_hooks = PySys_GetObject("path_hooks");
1614 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1615 PyErr_SetString(PyExc_ImportError,
1616 "sys.path_hooks must be a list of "
1617 "import hooks");
1618 return NULL;
1619 }
1620 path_importer_cache = PySys_GetObject("path_importer_cache");
1621 if (path_importer_cache == NULL ||
1622 !PyDict_Check(path_importer_cache)) {
1623 PyErr_SetString(PyExc_ImportError,
1624 "sys.path_importer_cache must be a dict");
1625 return NULL;
1626 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 npath = PyList_Size(path);
1629 namelen = strlen(name);
1630 for (i = 0; i < npath; i++) {
1631 PyObject *v = PyList_GetItem(path, i);
1632 PyObject *origv = v;
1633 const char *base;
1634 Py_ssize_t size;
1635 if (!v)
1636 return NULL;
1637 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001638 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (v == NULL)
1640 return NULL;
1641 }
1642 else if (!PyBytes_Check(v))
1643 continue;
1644 else
1645 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 base = PyBytes_AS_STRING(v);
1648 size = PyBytes_GET_SIZE(v);
1649 len = size;
1650 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1651 Py_DECREF(v);
1652 continue; /* Too long */
1653 }
1654 strcpy(buf, base);
1655 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (strlen(buf) != len) {
1658 continue; /* v contains '\0' */
1659 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* sys.path_hooks import hook */
1662 if (p_loader != NULL) {
1663 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 importer = get_path_importer(path_importer_cache,
1666 path_hooks, origv);
1667 if (importer == NULL) {
1668 return NULL;
1669 }
1670 /* Note: importer is a borrowed reference */
1671 if (importer != Py_None) {
1672 PyObject *loader;
1673 loader = PyObject_CallMethod(importer,
1674 "find_module",
1675 "s", fullname);
1676 if (loader == NULL)
1677 return NULL; /* error */
1678 if (loader != Py_None) {
1679 /* a loader was found */
1680 *p_loader = loader;
1681 return &importhookdescr;
1682 }
1683 Py_DECREF(loader);
1684 continue;
1685 }
1686 }
1687 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001690#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001692#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 )
1694 buf[len++] = SEP;
1695 strcpy(buf+len, name);
1696 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 /* Check for package import (buf holds a directory name,
1699 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001700#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (stat(buf, &statbuf) == 0 && /* it exists */
1702 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1703 case_ok(buf, len, namelen, name)) { /* case matches */
1704 if (find_init_module(buf)) { /* and has __init__.py */
1705 return &fd_package;
1706 }
1707 else {
1708 char warnstr[MAXPATHLEN+80];
1709 sprintf(warnstr, "Not importing directory "
1710 "'%.*s': missing __init__.py",
1711 MAXPATHLEN, buf);
1712 if (PyErr_WarnEx(PyExc_ImportWarning,
1713 warnstr, 1)) {
1714 return NULL;
1715 }
1716 }
1717 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001718#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001719#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 /* take a snapshot of the module spec for restoration
1721 * after the 8 character DLL hackery
1722 */
1723 saved_buf = strdup(buf);
1724 saved_len = len;
1725 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001726#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001728#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* OS/2 limits DLLs to 8 character names (w/o
1730 extension)
1731 * so if the name is longer than that and its a
1732 * dynamically loaded module we're going to try,
1733 * truncate the name before trying
1734 */
1735 if (strlen(subname) > 8) {
1736 /* is this an attempt to load a C extension? */
1737 const struct filedescr *scan;
1738 scan = _PyImport_DynLoadFiletab;
1739 while (scan->suffix != NULL) {
1740 if (!strcmp(scan->suffix, fdp->suffix))
1741 break;
1742 else
1743 scan++;
1744 }
1745 if (scan->suffix != NULL) {
1746 /* yes, so truncate the name */
1747 namelen = 8;
1748 len -= strlen(subname) - namelen;
1749 buf[len] = '\0';
1750 }
1751 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001752#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 strcpy(buf+len, fdp->suffix);
1754 if (Py_VerboseFlag > 1)
1755 PySys_WriteStderr("# trying %s\n", buf);
1756 filemode = fdp->mode;
1757 if (filemode[0] == 'U')
1758 filemode = "r" PY_STDIOTEXTMODE;
1759 fp = fopen(buf, filemode);
1760 if (fp != NULL) {
1761 if (case_ok(buf, len, namelen, name))
1762 break;
1763 else { /* continue search */
1764 fclose(fp);
1765 fp = NULL;
1766 }
1767 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001768#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* restore the saved snapshot */
1770 strcpy(buf, saved_buf);
1771 len = saved_len;
1772 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001773#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001775#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* don't need/want the module name snapshot anymore */
1777 if (saved_buf)
1778 {
1779 free(saved_buf);
1780 saved_buf = NULL;
1781 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001782#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 if (fp != NULL)
1784 break;
1785 }
1786 if (fp == NULL) {
1787 PyErr_Format(PyExc_ImportError,
1788 "No module named %.200s", name);
1789 return NULL;
1790 }
1791 *p_fp = fp;
1792 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001793}
1794
Martin v. Löwis18e16552006-02-15 17:27:45 +00001795/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001796 * The arguments here are tricky, best shown by example:
1797 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1798 * ^ ^ ^ ^
1799 * |--------------------- buf ---------------------|
1800 * |------------------- len ------------------|
1801 * |------ name -------|
1802 * |----- namelen -----|
1803 * buf is the full path, but len only counts up to (& exclusive of) the
1804 * extension. name is the module name, also exclusive of extension.
1805 *
1806 * We've already done a successful stat() or fopen() on buf, so know that
1807 * there's some match, possibly case-insensitive.
1808 *
Tim Peters50d8d372001-02-28 05:34:27 +00001809 * case_ok() is to return 1 if there's a case-sensitive match for
1810 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1811 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001812 *
Tim Peters50d8d372001-02-28 05:34:27 +00001813 * case_ok() is used to implement case-sensitive import semantics even
1814 * on platforms with case-insensitive filesystems. It's trivial to implement
1815 * for case-sensitive filesystems. It's pretty much a cross-platform
1816 * nightmare for systems with case-insensitive filesystems.
1817 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001818
Tim Peters50d8d372001-02-28 05:34:27 +00001819/* First we may need a pile of platform-specific header files; the sequence
1820 * of #if's here should match the sequence in the body of case_ok().
1821 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001822#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001823#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001824
Tim Peters50d8d372001-02-28 05:34:27 +00001825#elif defined(DJGPP)
1826#include <dir.h>
1827
Jason Tishler7961aa62005-05-20 00:56:54 +00001828#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001829#include <sys/types.h>
1830#include <dirent.h>
1831
Andrew MacIntyred9400542002-02-26 11:41:34 +00001832#elif defined(PYOS_OS2)
1833#define INCL_DOS
1834#define INCL_DOSERRORS
1835#define INCL_NOPMAPI
1836#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001837#endif
1838
Guido van Rossum0980bd91998-02-13 17:18:36 +00001839static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001840case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001841{
Tim Peters50d8d372001-02-28 05:34:27 +00001842/* Pick a platform-specific implementation; the sequence of #if's here should
1843 * match the sequence just above.
1844 */
1845
Jason Tishler7961aa62005-05-20 00:56:54 +00001846/* MS_WINDOWS */
1847#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 WIN32_FIND_DATA data;
1849 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (Py_GETENV("PYTHONCASEOK") != NULL)
1852 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 h = FindFirstFile(buf, &data);
1855 if (h == INVALID_HANDLE_VALUE) {
1856 PyErr_Format(PyExc_NameError,
1857 "Can't find file for module %.100s\n(filename %.300s)",
1858 name, buf);
1859 return 0;
1860 }
1861 FindClose(h);
1862 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001863
1864/* DJGPP */
1865#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 struct ffblk ffblk;
1867 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (Py_GETENV("PYTHONCASEOK") != NULL)
1870 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1873 if (done) {
1874 PyErr_Format(PyExc_NameError,
1875 "Can't find file for module %.100s\n(filename %.300s)",
1876 name, buf);
1877 return 0;
1878 }
1879 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001880
Jason Tishler7961aa62005-05-20 00:56:54 +00001881/* new-fangled macintosh (macosx) or Cygwin */
1882#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 DIR *dirp;
1884 struct dirent *dp;
1885 char dirname[MAXPATHLEN + 1];
1886 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (Py_GETENV("PYTHONCASEOK") != NULL)
1889 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* Copy the dir component into dirname; substitute "." if empty */
1892 if (dirlen <= 0) {
1893 dirname[0] = '.';
1894 dirname[1] = '\0';
1895 }
1896 else {
1897 assert(dirlen <= MAXPATHLEN);
1898 memcpy(dirname, buf, dirlen);
1899 dirname[dirlen] = '\0';
1900 }
1901 /* Open the directory and search the entries for an exact match. */
1902 dirp = opendir(dirname);
1903 if (dirp) {
1904 char *nameWithExt = buf + len - namelen;
1905 while ((dp = readdir(dirp)) != NULL) {
1906 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001907#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001909#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001911#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (thislen >= namelen &&
1913 strcmp(dp->d_name, nameWithExt) == 0) {
1914 (void)closedir(dirp);
1915 return 1; /* Found */
1916 }
1917 }
1918 (void)closedir(dirp);
1919 }
1920 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001921
Andrew MacIntyred9400542002-02-26 11:41:34 +00001922/* OS/2 */
1923#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 HDIR hdir = 1;
1925 ULONG srchcnt = 1;
1926 FILEFINDBUF3 ffbuf;
1927 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 if (Py_GETENV("PYTHONCASEOK") != NULL)
1930 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 rc = DosFindFirst(buf,
1933 &hdir,
1934 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1935 &ffbuf, sizeof(ffbuf),
1936 &srchcnt,
1937 FIL_STANDARD);
1938 if (rc != NO_ERROR)
1939 return 0;
1940 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001941
Tim Peters50d8d372001-02-28 05:34:27 +00001942/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1943#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001945
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001946#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001947}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001948
Victor Stinnerf52b7052010-08-14 17:06:04 +00001949/* Call _wfopen() on Windows, or fopen() otherwise. Return the new file
1950 object on success, or NULL if the file cannot be open or (if
1951 PyErr_Occurred()) on unicode error */
1952
1953FILE*
1954_Py_fopen(PyObject *unicode, const char *mode)
1955{
1956#ifdef MS_WINDOWS
1957 wchar_t path[MAXPATHLEN+1];
1958 wchar_t wmode[10];
1959 Py_ssize_t len;
1960 int usize;
1961
1962 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
1963 if (len == -1)
1964 return NULL;
1965 path[len] = L'\0';
1966
1967 usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
1968 if (usize == 0)
1969 return NULL;
1970
1971 return _wfopen(path, wmode);
1972#else
1973 FILE *f;
1974 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
1975 if (bytes == NULL)
1976 return NULL;
1977 f = fopen(PyBytes_AS_STRING(bytes), mode);
1978 Py_DECREF(bytes);
1979 return f;
1980#endif
1981}
Guido van Rossum0980bd91998-02-13 17:18:36 +00001982
Guido van Rossum197346f1997-10-31 18:38:52 +00001983#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001984
1985/* Call _wstat() on Windows, or stat() otherwise. Only fill st_mode
1986 attribute on Windows. Return 0 on success, -1 on stat error or (if
1987 PyErr_Occurred()) unicode error. */
1988
1989int
1990_Py_stat(PyObject *unicode, struct stat *statbuf)
1991{
1992#ifdef MS_WINDOWS
1993 wchar_t path[MAXPATHLEN+1];
1994 Py_ssize_t len;
1995 int err;
1996 struct _stat wstatbuf;
1997
Victor Stinner8a79dcc2010-08-14 16:59:08 +00001998 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
Victor Stinner4f4402c2010-08-14 14:50:26 +00001999 if (len == -1)
2000 return -1;
Victor Stinner8a79dcc2010-08-14 16:59:08 +00002001 path[len] = L'\0';
2002
Victor Stinner4f4402c2010-08-14 14:50:26 +00002003 err = _wstat(path, &wstatbuf);
2004 if (!err)
2005 statbuf->st_mode = wstatbuf.st_mode;
2006 return err;
2007#else
2008 int ret;
2009 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
2010 if (bytes == NULL)
2011 return -1;
2012 ret = stat(PyBytes_AS_STRING(bytes), statbuf);
2013 Py_DECREF(bytes);
2014 return ret;
2015#endif
2016}
2017
Guido van Rossum197346f1997-10-31 18:38:52 +00002018/* Helper to look for __init__.py or __init__.py[co] in potential package */
2019static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002020find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 const size_t save_len = strlen(buf);
2023 size_t i = save_len;
2024 char *pname; /* pointer to start of __init__ */
2025 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027/* For calling case_ok(buf, len, namelen, name):
2028 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2029 * ^ ^ ^ ^
2030 * |--------------------- buf ---------------------|
2031 * |------------------- len ------------------|
2032 * |------ name -------|
2033 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002034 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 if (save_len + 13 >= MAXPATHLEN)
2036 return 0;
2037 buf[i++] = SEP;
2038 pname = buf + i;
2039 strcpy(pname, "__init__.py");
2040 if (stat(buf, &statbuf) == 0) {
2041 if (case_ok(buf,
2042 save_len + 9, /* len("/__init__") */
2043 8, /* len("__init__") */
2044 pname)) {
2045 buf[save_len] = '\0';
2046 return 1;
2047 }
2048 }
2049 i += strlen(pname);
2050 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2051 if (stat(buf, &statbuf) == 0) {
2052 if (case_ok(buf,
2053 save_len + 9, /* len("/__init__") */
2054 8, /* len("__init__") */
2055 pname)) {
2056 buf[save_len] = '\0';
2057 return 1;
2058 }
2059 }
2060 buf[save_len] = '\0';
2061 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002062}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002063
Guido van Rossum197346f1997-10-31 18:38:52 +00002064#endif /* HAVE_STAT */
2065
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002066
Tim Petersdbd9ba62000-07-09 03:09:57 +00002067static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002068
Victor Stinner44c6c152010-08-09 00:59:10 +00002069static PyObject*
2070load_builtin(char *name, char *pathname, int type)
2071{
2072 PyObject *m, *modules;
2073 int err;
2074
2075 if (pathname != NULL && pathname[0] != '\0')
2076 name = pathname;
2077
2078 if (type == C_BUILTIN)
2079 err = init_builtin(name);
2080 else
2081 err = PyImport_ImportFrozenModule(name);
2082 if (err < 0)
2083 return NULL;
2084 if (err == 0) {
2085 PyErr_Format(PyExc_ImportError,
2086 "Purported %s module %.200s not found",
2087 type == C_BUILTIN ?
2088 "builtin" : "frozen",
2089 name);
2090 return NULL;
2091 }
2092
2093 modules = PyImport_GetModuleDict();
2094 m = PyDict_GetItemString(modules, name);
2095 if (m == NULL) {
2096 PyErr_Format(
2097 PyExc_ImportError,
2098 "%s module %.200s not properly initialized",
2099 type == C_BUILTIN ?
2100 "builtin" : "frozen",
2101 name);
2102 return NULL;
2103 }
2104 Py_INCREF(m);
2105 return m;
2106}
2107
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002108/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002109 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002110
Guido van Rossum79f25d91997-04-29 20:08:16 +00002111static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002112load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 /* First check that there's an open file (if we need one) */
2117 switch (type) {
2118 case PY_SOURCE:
2119 case PY_COMPILED:
2120 if (fp == NULL) {
2121 PyErr_Format(PyExc_ValueError,
2122 "file object required for import (type code %d)",
2123 type);
2124 return NULL;
2125 }
2126 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 case PY_SOURCE:
2131 m = load_source_module(name, pathname, fp);
2132 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 case PY_COMPILED:
2135 m = load_compiled_module(name, pathname, fp);
2136 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002137
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002138#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 case C_EXTENSION:
2140 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2141 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002142#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 case PKG_DIRECTORY:
2145 m = load_package(name, pathname);
2146 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 case C_BUILTIN:
2149 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002150 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 case IMP_HOOK: {
2154 if (loader == NULL) {
2155 PyErr_SetString(PyExc_ImportError,
2156 "import hook without loader");
2157 return NULL;
2158 }
2159 m = PyObject_CallMethod(loader, "load_module", "s", name);
2160 break;
2161 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 default:
2164 PyErr_Format(PyExc_ImportError,
2165 "Don't know how to import %.200s (type code %d)",
2166 name, type);
2167 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002172}
2173
2174
2175/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002176 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002177 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002178
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002179static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002180init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (_PyImport_FindExtension(name, name) != NULL)
2185 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 for (p = PyImport_Inittab; p->name != NULL; p++) {
2188 PyObject *mod;
2189 if (strcmp(name, p->name) == 0) {
2190 if (p->initfunc == NULL) {
2191 PyErr_Format(PyExc_ImportError,
2192 "Cannot re-init internal module %.200s",
2193 name);
2194 return -1;
2195 }
2196 if (Py_VerboseFlag)
2197 PySys_WriteStderr("import %s # builtin\n", name);
2198 mod = (*p->initfunc)();
2199 if (mod == 0)
2200 return -1;
2201 if (_PyImport_FixupExtension(mod, name, name) < 0)
2202 return -1;
2203 /* FixupExtension has put the module into sys.modules,
2204 so we can release our own reference. */
2205 Py_DECREF(mod);
2206 return 1;
2207 }
2208 }
2209 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002210}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002211
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002212
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002213/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002214
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002215static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002216find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (!name)
2221 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 for (p = PyImport_FrozenModules; ; p++) {
2224 if (p->name == NULL)
2225 return NULL;
2226 if (strcmp(p->name, name) == 0)
2227 break;
2228 }
2229 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002230}
2231
Guido van Rossum79f25d91997-04-29 20:08:16 +00002232static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002233get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 struct _frozen *p = find_frozen(name);
2236 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (p == NULL) {
2239 PyErr_Format(PyExc_ImportError,
2240 "No such frozen object named %.200s",
2241 name);
2242 return NULL;
2243 }
2244 if (p->code == NULL) {
2245 PyErr_Format(PyExc_ImportError,
2246 "Excluded frozen object named %.200s",
2247 name);
2248 return NULL;
2249 }
2250 size = p->size;
2251 if (size < 0)
2252 size = -size;
2253 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002254}
2255
Brett Cannon8d110132009-03-15 02:20:16 +00002256static PyObject *
2257is_frozen_package(char *name)
2258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 struct _frozen *p = find_frozen(name);
2260 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 if (p == NULL) {
2263 PyErr_Format(PyExc_ImportError,
2264 "No such frozen object named %.200s",
2265 name);
2266 return NULL;
2267 }
Brett Cannon8d110132009-03-15 02:20:16 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (size < 0)
2272 Py_RETURN_TRUE;
2273 else
2274 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002275}
2276
2277
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002278/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002279 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002280 an exception set if the initialization failed.
2281 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002282
2283int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002284PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 struct _frozen *p = find_frozen(name);
2287 PyObject *co;
2288 PyObject *m;
2289 int ispackage;
2290 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (p == NULL)
2293 return 0;
2294 if (p->code == NULL) {
2295 PyErr_Format(PyExc_ImportError,
2296 "Excluded frozen object named %.200s",
2297 name);
2298 return -1;
2299 }
2300 size = p->size;
2301 ispackage = (size < 0);
2302 if (ispackage)
2303 size = -size;
2304 if (Py_VerboseFlag)
2305 PySys_WriteStderr("import %s # frozen%s\n",
2306 name, ispackage ? " package" : "");
2307 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2308 if (co == NULL)
2309 return -1;
2310 if (!PyCode_Check(co)) {
2311 PyErr_Format(PyExc_TypeError,
2312 "frozen object %.200s is not a code object",
2313 name);
2314 goto err_return;
2315 }
2316 if (ispackage) {
2317 /* Set __path__ to the package name */
2318 PyObject *d, *s, *l;
2319 int err;
2320 m = PyImport_AddModule(name);
2321 if (m == NULL)
2322 goto err_return;
2323 d = PyModule_GetDict(m);
2324 s = PyUnicode_InternFromString(name);
2325 if (s == NULL)
2326 goto err_return;
2327 l = PyList_New(1);
2328 if (l == NULL) {
2329 Py_DECREF(s);
2330 goto err_return;
2331 }
2332 PyList_SET_ITEM(l, 0, s);
2333 err = PyDict_SetItemString(d, "__path__", l);
2334 Py_DECREF(l);
2335 if (err != 0)
2336 goto err_return;
2337 }
2338 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2339 if (m == NULL)
2340 goto err_return;
2341 Py_DECREF(co);
2342 Py_DECREF(m);
2343 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002344err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 Py_DECREF(co);
2346 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002347}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002348
2349
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002350/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002351 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002352
Guido van Rossum79f25d91997-04-29 20:08:16 +00002353PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002354PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 PyObject *pname;
2357 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 pname = PyUnicode_FromString(name);
2360 if (pname == NULL)
2361 return NULL;
2362 result = PyImport_Import(pname);
2363 Py_DECREF(pname);
2364 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002365}
2366
Christian Heimes072c0f12008-01-03 23:01:04 +00002367/* Import a module without blocking
2368 *
2369 * At first it tries to fetch the module from sys.modules. If the module was
2370 * never loaded before it loads it with PyImport_ImportModule() unless another
2371 * thread holds the import lock. In the latter case the function raises an
2372 * ImportError instead of blocking.
2373 *
2374 * Returns the module object with incremented ref count.
2375 */
2376PyObject *
2377PyImport_ImportModuleNoBlock(const char *name)
2378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyObject *result;
2380 PyObject *modules;
2381 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* Try to get the module from sys.modules[name] */
2384 modules = PyImport_GetModuleDict();
2385 if (modules == NULL)
2386 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 result = PyDict_GetItemString(modules, name);
2389 if (result != NULL) {
2390 Py_INCREF(result);
2391 return result;
2392 }
2393 else {
2394 PyErr_Clear();
2395 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002396#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* check the import lock
2398 * me might be -1 but I ignore the error here, the lock function
2399 * takes care of the problem */
2400 me = PyThread_get_thread_ident();
2401 if (import_lock_thread == -1 || import_lock_thread == me) {
2402 /* no thread or me is holding the lock */
2403 return PyImport_ImportModule(name);
2404 }
2405 else {
2406 PyErr_Format(PyExc_ImportError,
2407 "Failed to import %.200s because the import lock"
2408 "is held by another thread.",
2409 name);
2410 return NULL;
2411 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002412#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002414#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002415}
2416
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002417/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002418static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002420static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002422static int mark_miss(char *name);
2423static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002425static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002426
2427/* The Magnum Opus of dotted-name import :-) */
2428
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002429static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002430import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 char buf[MAXPATHLEN+1];
2434 Py_ssize_t buflen = 0;
2435 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002438#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002440#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 ) {
2442 PyErr_SetString(PyExc_ImportError,
2443 "Import by filename is not supported.");
2444 return NULL;
2445 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 parent = get_parent(globals, buf, &buflen, level);
2448 if (parent == NULL)
2449 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002450
Benjamin Peterson556d8002010-06-27 22:37:28 +00002451 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2452 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 if (head == NULL)
2454 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 tail = head;
2457 Py_INCREF(tail);
2458 while (name) {
2459 next = load_next(tail, tail, &name, buf, &buflen);
2460 Py_DECREF(tail);
2461 if (next == NULL) {
2462 Py_DECREF(head);
2463 return NULL;
2464 }
2465 tail = next;
2466 }
2467 if (tail == Py_None) {
2468 /* If tail is Py_None, both get_parent and load_next found
2469 an empty module name: someone called __import__("") or
2470 doctored faulty bytecode */
2471 Py_DECREF(tail);
2472 Py_DECREF(head);
2473 PyErr_SetString(PyExc_ValueError,
2474 "Empty module name");
2475 return NULL;
2476 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (fromlist != NULL) {
2479 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2480 fromlist = NULL;
2481 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 if (fromlist == NULL) {
2484 Py_DECREF(tail);
2485 return head;
2486 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 Py_DECREF(head);
2489 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2490 Py_DECREF(tail);
2491 return NULL;
2492 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002495}
2496
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002497PyObject *
2498PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 PyObject *result;
2502 _PyImport_AcquireLock();
2503 result = import_module_level(name, globals, locals, fromlist, level);
2504 if (_PyImport_ReleaseLock() < 0) {
2505 Py_XDECREF(result);
2506 PyErr_SetString(PyExc_RuntimeError,
2507 "not holding the import lock");
2508 return NULL;
2509 }
2510 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002511}
2512
Fred Drake87590902004-05-28 20:21:36 +00002513/* Return the package that an import is being performed in. If globals comes
2514 from the module foo.bar.bat (not itself a package), this returns the
2515 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002516 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002517
2518 The *name* of the returned package is returned in buf, with the length of
2519 the name in *p_buflen.
2520
2521 If globals doesn't come from a package or a module in a package, or a
2522 corresponding entry is not found in sys.modules, Py_None is returned.
2523*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002524static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002525get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 static PyObject *namestr = NULL;
2528 static PyObject *pathstr = NULL;
2529 static PyObject *pkgstr = NULL;
2530 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2531 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (globals == NULL || !PyDict_Check(globals) || !level)
2534 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (namestr == NULL) {
2537 namestr = PyUnicode_InternFromString("__name__");
2538 if (namestr == NULL)
2539 return NULL;
2540 }
2541 if (pathstr == NULL) {
2542 pathstr = PyUnicode_InternFromString("__path__");
2543 if (pathstr == NULL)
2544 return NULL;
2545 }
2546 if (pkgstr == NULL) {
2547 pkgstr = PyUnicode_InternFromString("__package__");
2548 if (pkgstr == NULL)
2549 return NULL;
2550 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 *buf = '\0';
2553 *p_buflen = 0;
2554 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 if ((pkgname != NULL) && (pkgname != Py_None)) {
2557 /* __package__ is set, so use it */
2558 char *pkgname_str;
2559 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 if (!PyUnicode_Check(pkgname)) {
2562 PyErr_SetString(PyExc_ValueError,
2563 "__package__ set to non-string");
2564 return NULL;
2565 }
2566 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2567 if (len == 0) {
2568 if (level > 0) {
2569 PyErr_SetString(PyExc_ValueError,
2570 "Attempted relative import in non-package");
2571 return NULL;
2572 }
2573 return Py_None;
2574 }
2575 if (len > MAXPATHLEN) {
2576 PyErr_SetString(PyExc_ValueError,
2577 "Package name too long");
2578 return NULL;
2579 }
2580 strcpy(buf, pkgname_str);
2581 } else {
2582 /* __package__ not set, so figure it out and set it */
2583 modname = PyDict_GetItem(globals, namestr);
2584 if (modname == NULL || !PyUnicode_Check(modname))
2585 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 modpath = PyDict_GetItem(globals, pathstr);
2588 if (modpath != NULL) {
2589 /* __path__ is set, so modname is already the package name */
2590 char *modname_str;
2591 Py_ssize_t len;
2592 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2595 if (len > MAXPATHLEN) {
2596 PyErr_SetString(PyExc_ValueError,
2597 "Module name too long");
2598 return NULL;
2599 }
2600 strcpy(buf, modname_str);
2601 error = PyDict_SetItem(globals, pkgstr, modname);
2602 if (error) {
2603 PyErr_SetString(PyExc_ValueError,
2604 "Could not set __package__");
2605 return NULL;
2606 }
2607 } else {
2608 /* Normal module, so work out the package name if any */
2609 char *start = _PyUnicode_AsString(modname);
2610 char *lastdot = strrchr(start, '.');
2611 size_t len;
2612 int error;
2613 if (lastdot == NULL && level > 0) {
2614 PyErr_SetString(PyExc_ValueError,
2615 "Attempted relative import in non-package");
2616 return NULL;
2617 }
2618 if (lastdot == NULL) {
2619 error = PyDict_SetItem(globals, pkgstr, Py_None);
2620 if (error) {
2621 PyErr_SetString(PyExc_ValueError,
2622 "Could not set __package__");
2623 return NULL;
2624 }
2625 return Py_None;
2626 }
2627 len = lastdot - start;
2628 if (len >= MAXPATHLEN) {
2629 PyErr_SetString(PyExc_ValueError,
2630 "Module name too long");
2631 return NULL;
2632 }
2633 strncpy(buf, start, len);
2634 buf[len] = '\0';
2635 pkgname = PyUnicode_FromString(buf);
2636 if (pkgname == NULL) {
2637 return NULL;
2638 }
2639 error = PyDict_SetItem(globals, pkgstr, pkgname);
2640 Py_DECREF(pkgname);
2641 if (error) {
2642 PyErr_SetString(PyExc_ValueError,
2643 "Could not set __package__");
2644 return NULL;
2645 }
2646 }
2647 }
2648 while (--level > 0) {
2649 char *dot = strrchr(buf, '.');
2650 if (dot == NULL) {
2651 PyErr_SetString(PyExc_ValueError,
2652 "Attempted relative import beyond "
2653 "toplevel package");
2654 return NULL;
2655 }
2656 *dot = '\0';
2657 }
2658 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 modules = PyImport_GetModuleDict();
2661 parent = PyDict_GetItemString(modules, buf);
2662 if (parent == NULL) {
2663 if (orig_level < 1) {
2664 PyObject *err_msg = PyBytes_FromFormat(
2665 "Parent module '%.200s' not found "
2666 "while handling absolute import", buf);
2667 if (err_msg == NULL) {
2668 return NULL;
2669 }
2670 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2671 PyBytes_AsString(err_msg), 1)) {
2672 *buf = '\0';
2673 *p_buflen = 0;
2674 parent = Py_None;
2675 }
2676 Py_DECREF(err_msg);
2677 } else {
2678 PyErr_Format(PyExc_SystemError,
2679 "Parent module '%.200s' not loaded, "
2680 "cannot perform relative import", buf);
2681 }
2682 }
2683 return parent;
2684 /* We expect, but can't guarantee, if parent != None, that:
2685 - parent.__name__ == buf
2686 - parent.__dict__ is globals
2687 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002688}
2689
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002690/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002691static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002692load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 char *name = *p_name;
2696 char *dot = strchr(name, '.');
2697 size_t len;
2698 char *p;
2699 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 if (strlen(name) == 0) {
2702 /* completely empty module name should only happen in
2703 'from . import' (or '__import__("")')*/
2704 Py_INCREF(mod);
2705 *p_name = NULL;
2706 return mod;
2707 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 if (dot == NULL) {
2710 *p_name = NULL;
2711 len = strlen(name);
2712 }
2713 else {
2714 *p_name = dot+1;
2715 len = dot-name;
2716 }
2717 if (len == 0) {
2718 PyErr_SetString(PyExc_ValueError,
2719 "Empty module name");
2720 return NULL;
2721 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 p = buf + *p_buflen;
2724 if (p != buf)
2725 *p++ = '.';
2726 if (p+len-buf >= MAXPATHLEN) {
2727 PyErr_SetString(PyExc_ValueError,
2728 "Module name too long");
2729 return NULL;
2730 }
2731 strncpy(p, name, len);
2732 p[len] = '\0';
2733 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 result = import_submodule(mod, p, buf);
2736 if (result == Py_None && altmod != mod) {
2737 Py_DECREF(result);
2738 /* Here, altmod must be None and mod must not be None */
2739 result = import_submodule(altmod, p, p);
2740 if (result != NULL && result != Py_None) {
2741 if (mark_miss(buf) != 0) {
2742 Py_DECREF(result);
2743 return NULL;
2744 }
2745 strncpy(buf, name, len);
2746 buf[len] = '\0';
2747 *p_buflen = len;
2748 }
2749 }
2750 if (result == NULL)
2751 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 if (result == Py_None) {
2754 Py_DECREF(result);
2755 PyErr_Format(PyExc_ImportError,
2756 "No module named %.200s", name);
2757 return NULL;
2758 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002761}
2762
2763static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002764mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyObject *modules = PyImport_GetModuleDict();
2767 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002768}
2769
2770static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002771ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 if (!PyObject_HasAttrString(mod, "__path__"))
2777 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 for (i = 0; ; i++) {
2780 PyObject *item = PySequence_GetItem(fromlist, i);
2781 int hasit;
2782 if (item == NULL) {
2783 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2784 PyErr_Clear();
2785 return 1;
2786 }
2787 return 0;
2788 }
2789 if (!PyUnicode_Check(item)) {
2790 PyErr_SetString(PyExc_TypeError,
2791 "Item in ``from list'' not a string");
2792 Py_DECREF(item);
2793 return 0;
2794 }
2795 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2796 PyObject *all;
2797 Py_DECREF(item);
2798 /* See if the package defines __all__ */
2799 if (recursive)
2800 continue; /* Avoid endless recursion */
2801 all = PyObject_GetAttrString(mod, "__all__");
2802 if (all == NULL)
2803 PyErr_Clear();
2804 else {
2805 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2806 Py_DECREF(all);
2807 if (!ret)
2808 return 0;
2809 }
2810 continue;
2811 }
2812 hasit = PyObject_HasAttr(mod, item);
2813 if (!hasit) {
2814 PyObject *item8;
2815 char *subname;
2816 PyObject *submod;
2817 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002818 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 if (!item8) {
2820 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2821 return 0;
2822 }
2823 subname = PyBytes_AS_STRING(item8);
2824 if (buflen + strlen(subname) >= MAXPATHLEN) {
2825 PyErr_SetString(PyExc_ValueError,
2826 "Module name too long");
2827 Py_DECREF(item);
2828 return 0;
2829 }
2830 p = buf + buflen;
2831 *p++ = '.';
2832 strcpy(p, subname);
2833 submod = import_submodule(mod, subname, buf);
2834 Py_DECREF(item8);
2835 Py_XDECREF(submod);
2836 if (submod == NULL) {
2837 Py_DECREF(item);
2838 return 0;
2839 }
2840 }
2841 Py_DECREF(item);
2842 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002845}
2846
Neil Schemenauer00b09662003-06-16 21:03:07 +00002847static int
2848add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 if (mod == Py_None)
2852 return 1;
2853 /* Irrespective of the success of this load, make a
2854 reference to it in the parent package module. A copy gets
2855 saved in the modules dictionary under the full name, so get a
2856 reference from there, if need be. (The exception is when the
2857 load failed with a SyntaxError -- then there's no trace in
2858 sys.modules. In that case, of course, do nothing extra.) */
2859 if (submod == NULL) {
2860 submod = PyDict_GetItemString(modules, fullname);
2861 if (submod == NULL)
2862 return 1;
2863 }
2864 if (PyModule_Check(mod)) {
2865 /* We can't use setattr here since it can give a
2866 * spurious warning if the submodule name shadows a
2867 * builtin name */
2868 PyObject *dict = PyModule_GetDict(mod);
2869 if (!dict)
2870 return 0;
2871 if (PyDict_SetItemString(dict, subname, submod) < 0)
2872 return 0;
2873 }
2874 else {
2875 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2876 return 0;
2877 }
2878 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002879}
2880
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002881static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002882import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 PyObject *modules = PyImport_GetModuleDict();
2885 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 /* Require:
2888 if mod == None: subname == fullname
2889 else: mod.__name__ + "." + subname == fullname
2890 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2893 Py_INCREF(m);
2894 }
2895 else {
2896 PyObject *path, *loader = NULL;
2897 char buf[MAXPATHLEN+1];
2898 struct filedescr *fdp;
2899 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if (mod == Py_None)
2902 path = NULL;
2903 else {
2904 path = PyObject_GetAttrString(mod, "__path__");
2905 if (path == NULL) {
2906 PyErr_Clear();
2907 Py_INCREF(Py_None);
2908 return Py_None;
2909 }
2910 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 buf[0] = '\0';
2913 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2914 &fp, &loader);
2915 Py_XDECREF(path);
2916 if (fdp == NULL) {
2917 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2918 return NULL;
2919 PyErr_Clear();
2920 Py_INCREF(Py_None);
2921 return Py_None;
2922 }
2923 m = load_module(fullname, fp, buf, fdp->type, loader);
2924 Py_XDECREF(loader);
2925 if (fp)
2926 fclose(fp);
2927 if (!add_submodule(mod, m, fullname, subname, modules)) {
2928 Py_XDECREF(m);
2929 m = NULL;
2930 }
2931 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002934}
2935
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002936
2937/* Re-import a module of any kind and return its module object, WITH
2938 INCREMENTED REFERENCE COUNT */
2939
Guido van Rossum79f25d91997-04-29 20:08:16 +00002940PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002941PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 PyInterpreterState *interp = PyThreadState_Get()->interp;
2944 PyObject *modules_reloading = interp->modules_reloading;
2945 PyObject *modules = PyImport_GetModuleDict();
2946 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2947 char *name, *subname;
2948 char buf[MAXPATHLEN+1];
2949 struct filedescr *fdp;
2950 FILE *fp = NULL;
2951 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 if (modules_reloading == NULL) {
2954 Py_FatalError("PyImport_ReloadModule: "
2955 "no modules_reloading dictionary!");
2956 return NULL;
2957 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 if (m == NULL || !PyModule_Check(m)) {
2960 PyErr_SetString(PyExc_TypeError,
2961 "reload() argument must be module");
2962 return NULL;
2963 }
2964 name = (char*)PyModule_GetName(m);
2965 if (name == NULL)
2966 return NULL;
2967 if (m != PyDict_GetItemString(modules, name)) {
2968 PyErr_Format(PyExc_ImportError,
2969 "reload(): module %.200s not in sys.modules",
2970 name);
2971 return NULL;
2972 }
2973 existing_m = PyDict_GetItemString(modules_reloading, name);
2974 if (existing_m != NULL) {
2975 /* Due to a recursive reload, this module is already
2976 being reloaded. */
2977 Py_INCREF(existing_m);
2978 return existing_m;
2979 }
2980 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2981 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 subname = strrchr(name, '.');
2984 if (subname == NULL)
2985 subname = name;
2986 else {
2987 PyObject *parentname, *parent;
2988 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2989 if (parentname == NULL) {
2990 imp_modules_reloading_clear();
2991 return NULL;
2992 }
2993 parent = PyDict_GetItem(modules, parentname);
2994 if (parent == NULL) {
2995 PyErr_Format(PyExc_ImportError,
2996 "reload(): parent %U not in sys.modules",
2997 parentname);
2998 Py_DECREF(parentname);
2999 imp_modules_reloading_clear();
3000 return NULL;
3001 }
3002 Py_DECREF(parentname);
3003 subname++;
3004 path = PyObject_GetAttrString(parent, "__path__");
3005 if (path == NULL)
3006 PyErr_Clear();
3007 }
3008 buf[0] = '\0';
3009 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3010 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 if (fdp == NULL) {
3013 Py_XDECREF(loader);
3014 imp_modules_reloading_clear();
3015 return NULL;
3016 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 newm = load_module(name, fp, buf, fdp->type, loader);
3019 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 if (fp)
3022 fclose(fp);
3023 if (newm == NULL) {
3024 /* load_module probably removed name from modules because of
3025 * the error. Put back the original module object. We're
3026 * going to return NULL in this case regardless of whether
3027 * replacing name succeeds, so the return value is ignored.
3028 */
3029 PyDict_SetItemString(modules, name, m);
3030 }
3031 imp_modules_reloading_clear();
3032 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003033}
3034
3035
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003036/* Higher-level import emulator which emulates the "import" statement
3037 more accurately -- it invokes the __import__() function from the
3038 builtins of the current globals. This means that the import is
3039 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00003040 environment, e.g. by "rexec".
3041 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003042 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003043 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003044
3045PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003046PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 static PyObject *silly_list = NULL;
3049 static PyObject *builtins_str = NULL;
3050 static PyObject *import_str = NULL;
3051 PyObject *globals = NULL;
3052 PyObject *import = NULL;
3053 PyObject *builtins = NULL;
3054 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 /* Initialize constant string objects */
3057 if (silly_list == NULL) {
3058 import_str = PyUnicode_InternFromString("__import__");
3059 if (import_str == NULL)
3060 return NULL;
3061 builtins_str = PyUnicode_InternFromString("__builtins__");
3062 if (builtins_str == NULL)
3063 return NULL;
3064 silly_list = Py_BuildValue("[s]", "__doc__");
3065 if (silly_list == NULL)
3066 return NULL;
3067 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 /* Get the builtins from current globals */
3070 globals = PyEval_GetGlobals();
3071 if (globals != NULL) {
3072 Py_INCREF(globals);
3073 builtins = PyObject_GetItem(globals, builtins_str);
3074 if (builtins == NULL)
3075 goto err;
3076 }
3077 else {
3078 /* No globals -- use standard builtins, and fake globals */
3079 builtins = PyImport_ImportModuleLevel("builtins",
3080 NULL, NULL, NULL, 0);
3081 if (builtins == NULL)
3082 return NULL;
3083 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3084 if (globals == NULL)
3085 goto err;
3086 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 /* Get the __import__ function from the builtins */
3089 if (PyDict_Check(builtins)) {
3090 import = PyObject_GetItem(builtins, import_str);
3091 if (import == NULL)
3092 PyErr_SetObject(PyExc_KeyError, import_str);
3093 }
3094 else
3095 import = PyObject_GetAttr(builtins, import_str);
3096 if (import == NULL)
3097 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 /* Call the __import__ function with the proper argument list
3100 * Always use absolute import here. */
3101 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3102 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003103
3104 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 Py_XDECREF(globals);
3106 Py_XDECREF(builtins);
3107 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003110}
3111
3112
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003113/* Module 'imp' provides Python access to the primitives used for
3114 importing modules.
3115*/
3116
Guido van Rossum79f25d91997-04-29 20:08:16 +00003117static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003118imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 buf[0] = (char) ((magic >> 0) & 0xff);
3123 buf[1] = (char) ((magic >> 8) & 0xff);
3124 buf[2] = (char) ((magic >> 16) & 0xff);
3125 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 return PyBytes_FromStringAndSize(buf, 4);
3128};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003129
3130static PyObject *
3131imp_get_magic(PyObject *self, PyObject *noargs)
3132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003134}
3135
3136static PyObject *
3137imp_get_tag(PyObject *self, PyObject *noargs)
3138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003140}
3141
Guido van Rossum79f25d91997-04-29 20:08:16 +00003142static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003143imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 PyObject *list;
3146 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 list = PyList_New(0);
3149 if (list == NULL)
3150 return NULL;
3151 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3152 PyObject *item = Py_BuildValue("ssi",
3153 fdp->suffix, fdp->mode, fdp->type);
3154 if (item == NULL) {
3155 Py_DECREF(list);
3156 return NULL;
3157 }
3158 if (PyList_Append(list, item) < 0) {
3159 Py_DECREF(list);
3160 Py_DECREF(item);
3161 return NULL;
3162 }
3163 Py_DECREF(item);
3164 }
3165 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003166}
3167
Guido van Rossum79f25d91997-04-29 20:08:16 +00003168static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003169call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 extern int fclose(FILE *);
3172 PyObject *fob, *ret;
3173 PyObject *pathobj;
3174 struct filedescr *fdp;
3175 char pathname[MAXPATHLEN+1];
3176 FILE *fp = NULL;
3177 int fd = -1;
3178 char *found_encoding = NULL;
3179 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 pathname[0] = '\0';
3182 if (path == Py_None)
3183 path = NULL;
3184 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3185 if (fdp == NULL)
3186 return NULL;
3187 if (fp != NULL) {
3188 fd = fileno(fp);
3189 if (fd != -1)
3190 fd = dup(fd);
3191 fclose(fp);
3192 fp = NULL;
3193 }
3194 if (fd != -1) {
3195 if (strchr(fdp->mode, 'b') == NULL) {
3196 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3197 memory. */
3198 found_encoding = PyTokenizer_FindEncoding(fd);
3199 lseek(fd, 0, 0); /* Reset position */
3200 if (found_encoding == NULL && PyErr_Occurred())
3201 return NULL;
3202 encoding = (found_encoding != NULL) ? found_encoding :
3203 (char*)PyUnicode_GetDefaultEncoding();
3204 }
3205 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3206 (char*)encoding, NULL, NULL, 1);
3207 if (fob == NULL) {
3208 close(fd);
3209 PyMem_FREE(found_encoding);
3210 return NULL;
3211 }
3212 }
3213 else {
3214 fob = Py_None;
3215 Py_INCREF(fob);
3216 }
3217 pathobj = PyUnicode_DecodeFSDefault(pathname);
3218 ret = Py_BuildValue("NN(ssi)",
3219 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3220 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003223}
3224
Guido van Rossum79f25d91997-04-29 20:08:16 +00003225static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003226imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 char *name;
3229 PyObject *ret, *path = NULL;
3230 if (!PyArg_ParseTuple(args, "es|O:find_module",
3231 Py_FileSystemDefaultEncoding, &name,
3232 &path))
3233 return NULL;
3234 ret = call_find_module(name, path);
3235 PyMem_Free(name);
3236 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003237}
3238
3239static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003240imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 char *name;
3243 int ret;
3244 PyObject *m;
3245 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3246 return NULL;
3247 ret = init_builtin(name);
3248 if (ret < 0)
3249 return NULL;
3250 if (ret == 0) {
3251 Py_INCREF(Py_None);
3252 return Py_None;
3253 }
3254 m = PyImport_AddModule(name);
3255 Py_XINCREF(m);
3256 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003257}
3258
Guido van Rossum79f25d91997-04-29 20:08:16 +00003259static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003260imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 char *name;
3263 int ret;
3264 PyObject *m;
3265 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3266 return NULL;
3267 ret = PyImport_ImportFrozenModule(name);
3268 if (ret < 0)
3269 return NULL;
3270 if (ret == 0) {
3271 Py_INCREF(Py_None);
3272 return Py_None;
3273 }
3274 m = PyImport_AddModule(name);
3275 Py_XINCREF(m);
3276 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003277}
3278
Guido van Rossum79f25d91997-04-29 20:08:16 +00003279static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003280imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3285 return NULL;
3286 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003287}
3288
Guido van Rossum79f25d91997-04-29 20:08:16 +00003289static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003290imp_is_frozen_package(PyObject *self, PyObject *args)
3291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3295 return NULL;
3296 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003297}
3298
3299static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003300imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 char *name;
3303 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3304 return NULL;
3305 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003306}
3307
Guido van Rossum79f25d91997-04-29 20:08:16 +00003308static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003309imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 char *name;
3312 struct _frozen *p;
3313 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3314 return NULL;
3315 p = find_frozen(name);
3316 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003317}
3318
3319static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003320get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 FILE *fp;
3323 if (mode[0] == 'U')
3324 mode = "r" PY_STDIOTEXTMODE;
3325 if (fob == NULL) {
3326 fp = fopen(pathname, mode);
3327 }
3328 else {
3329 int fd = PyObject_AsFileDescriptor(fob);
3330 if (fd == -1)
3331 return NULL;
3332 if (!_PyVerify_fd(fd))
3333 goto error;
3334 /* the FILE struct gets a new fd, so that it can be closed
3335 * independently of the file descriptor given
3336 */
3337 fd = dup(fd);
3338 if (fd == -1)
3339 goto error;
3340 fp = fdopen(fd, mode);
3341 }
3342 if (fp)
3343 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003344error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 PyErr_SetFromErrno(PyExc_IOError);
3346 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003347}
3348
Guido van Rossum79f25d91997-04-29 20:08:16 +00003349static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003350imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 char *name;
3353 char *pathname;
3354 PyObject *fob = NULL;
3355 PyObject *m;
3356 FILE *fp;
3357 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3358 &name,
3359 Py_FileSystemDefaultEncoding, &pathname,
3360 &fob))
3361 return NULL;
3362 fp = get_file(pathname, fob, "rb");
3363 if (fp == NULL) {
3364 PyMem_Free(pathname);
3365 return NULL;
3366 }
3367 m = load_compiled_module(name, pathname, fp);
3368 fclose(fp);
3369 PyMem_Free(pathname);
3370 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003371}
3372
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003373#ifdef HAVE_DYNAMIC_LOADING
3374
Guido van Rossum79f25d91997-04-29 20:08:16 +00003375static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003376imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 char *name;
3379 char *pathname;
3380 PyObject *fob = NULL;
3381 PyObject *m;
3382 FILE *fp = NULL;
3383 if (!PyArg_ParseTuple(args, "ses|O:load_dynamic",
3384 &name,
3385 Py_FileSystemDefaultEncoding, &pathname,
3386 &fob))
3387 return NULL;
3388 if (fob) {
3389 fp = get_file(pathname, fob, "r");
3390 if (fp == NULL) {
3391 PyMem_Free(pathname);
3392 return NULL;
3393 }
3394 }
3395 m = _PyImport_LoadDynamicModule(name, pathname, fp);
3396 PyMem_Free(pathname);
3397 if (fp)
3398 fclose(fp);
3399 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003400}
3401
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003402#endif /* HAVE_DYNAMIC_LOADING */
3403
Guido van Rossum79f25d91997-04-29 20:08:16 +00003404static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003405imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 char *name;
3408 char *pathname;
3409 PyObject *fob = NULL;
3410 PyObject *m;
3411 FILE *fp;
3412 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3413 &name,
3414 Py_FileSystemDefaultEncoding, &pathname,
3415 &fob))
3416 return NULL;
3417 fp = get_file(pathname, fob, "r");
3418 if (fp == NULL) {
3419 PyMem_Free(pathname);
3420 return NULL;
3421 }
3422 m = load_source_module(name, pathname, fp);
3423 PyMem_Free(pathname);
3424 fclose(fp);
3425 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003426}
3427
Guido van Rossum79f25d91997-04-29 20:08:16 +00003428static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003429imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 char *name;
3432 PyObject *fob;
3433 char *pathname;
3434 PyObject * ret;
3435 char *suffix; /* Unused */
3436 char *mode;
3437 int type;
3438 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
3441 &name, &fob,
3442 Py_FileSystemDefaultEncoding, &pathname,
3443 &suffix, &mode, &type))
3444 return NULL;
3445 if (*mode) {
3446 /* Mode must start with 'r' or 'U' and must not contain '+'.
3447 Implicit in this test is the assumption that the mode
3448 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3451 PyErr_Format(PyExc_ValueError,
3452 "invalid file open mode %.200s", mode);
3453 PyMem_Free(pathname);
3454 return NULL;
3455 }
3456 }
3457 if (fob == Py_None)
3458 fp = NULL;
3459 else {
3460 fp = get_file(NULL, fob, mode);
3461 if (fp == NULL) {
3462 PyMem_Free(pathname);
3463 return NULL;
3464 }
3465 }
3466 ret = load_module(name, fp, pathname, type, NULL);
3467 PyMem_Free(pathname);
3468 if (fp)
3469 fclose(fp);
3470 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003471}
3472
3473static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003474imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 char *name;
3477 char *pathname;
3478 PyObject * ret;
3479 if (!PyArg_ParseTuple(args, "ses:load_package",
3480 &name, Py_FileSystemDefaultEncoding, &pathname))
3481 return NULL;
3482 ret = load_package(name, pathname);
3483 PyMem_Free(pathname);
3484 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003485}
3486
3487static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003488imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 char *name;
3491 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3492 return NULL;
3493 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003494}
3495
Christian Heimes13a7a212008-01-07 17:13:09 +00003496static PyObject *
3497imp_reload(PyObject *self, PyObject *v)
3498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003500}
3501
3502PyDoc_STRVAR(doc_reload,
3503"reload(module) -> module\n\
3504\n\
3505Reload the module. The module must have been successfully imported before.");
3506
Barry Warsaw28a691b2010-04-17 00:19:56 +00003507static PyObject *
3508imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 char buf[MAXPATHLEN+1];
3513 char *pathname, *cpathname;
3514 PyObject *debug_override = Py_None;
3515 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 if (!PyArg_ParseTupleAndKeywords(
3518 args, kws, "es|O", kwlist,
3519 Py_FileSystemDefaultEncoding, &pathname, &debug_override))
3520 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 if (debug_override != Py_None)
3523 if ((debug = PyObject_IsTrue(debug_override)) < 0)
3524 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug);
3527 PyMem_Free(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 if (cpathname == NULL) {
3530 PyErr_Format(PyExc_SystemError, "path buffer too short");
3531 return NULL;
3532 }
3533 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003534}
3535
3536PyDoc_STRVAR(doc_cache_from_source,
3537"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3538\n\
3539The .py file does not need to exist; this simply returns the path to the\n\
3540.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3541will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3542\n\
3543If debug_override is not None, then it must be a boolean and is taken as\n\
3544the value of __debug__ instead.");
3545
3546static PyObject *
3547imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 char *pathname;
3552 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 if (!PyArg_ParseTupleAndKeywords(
3555 args, kws, "es", kwlist,
3556 Py_FileSystemDefaultEncoding, &pathname))
3557 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 if (make_source_pathname(pathname, buf) == NULL) {
3560 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3561 pathname);
3562 PyMem_Free(pathname);
3563 return NULL;
3564 }
3565 PyMem_Free(pathname);
3566 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003567}
3568
3569PyDoc_STRVAR(doc_source_from_cache,
3570"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3571\n\
3572The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3573the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3574does not conform to PEP 3147 format, ValueError will be raised.");
3575
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003576/* Doc strings */
3577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003578PyDoc_STRVAR(doc_imp,
3579"This module provides the components needed to build your own\n\
3580__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003582PyDoc_STRVAR(doc_find_module,
3583"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003584Search for a module. If path is omitted or None, search for a\n\
3585built-in, frozen or special module and continue search in sys.path.\n\
3586The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003587package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003589PyDoc_STRVAR(doc_load_module,
3590"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003591Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003592The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003594PyDoc_STRVAR(doc_get_magic,
3595"get_magic() -> string\n\
3596Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003597
Barry Warsaw28a691b2010-04-17 00:19:56 +00003598PyDoc_STRVAR(doc_get_tag,
3599"get_tag() -> string\n\
3600Return the magic tag for .pyc or .pyo files.");
3601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003602PyDoc_STRVAR(doc_get_suffixes,
3603"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003604Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003605that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003607PyDoc_STRVAR(doc_new_module,
3608"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003609Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003610The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003611
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003612PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003613"lock_held() -> boolean\n\
3614Return True if the import lock is currently held, else False.\n\
3615On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003616
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003617PyDoc_STRVAR(doc_acquire_lock,
3618"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003619Acquires the interpreter's import lock for the current thread.\n\
3620This lock should be used by import hooks to ensure thread-safety\n\
3621when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003622On platforms without threads, this function does nothing.");
3623
3624PyDoc_STRVAR(doc_release_lock,
3625"release_lock() -> None\n\
3626Release the interpreter's import lock.\n\
3627On platforms without threads, this function does nothing.");
3628
Guido van Rossum79f25d91997-04-29 20:08:16 +00003629static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3631 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3632 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3633 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3634 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3635 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3636 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3637 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3638 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3639 {"reload", imp_reload, METH_O, doc_reload},
3640 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3641 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3642 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3643 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3644 /* The rest are obsolete */
3645 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3646 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3647 {"init_builtin", imp_init_builtin, METH_VARARGS},
3648 {"init_frozen", imp_init_frozen, METH_VARARGS},
3649 {"is_builtin", imp_is_builtin, METH_VARARGS},
3650 {"is_frozen", imp_is_frozen, METH_VARARGS},
3651 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003652#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003654#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 {"load_package", imp_load_package, METH_VARARGS},
3656 {"load_source", imp_load_source, METH_VARARGS},
3657 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003658};
3659
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003660static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003661setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 PyObject *v;
3664 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 v = PyLong_FromLong((long)value);
3667 err = PyDict_SetItemString(d, name, v);
3668 Py_XDECREF(v);
3669 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003670}
3671
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003672typedef struct {
3673 PyObject_HEAD
3674} NullImporter;
3675
3676static int
3677NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3678{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003679#ifndef MS_WINDOWS
3680 PyObject *path;
3681 struct stat statbuf;
3682 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3685 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003686
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003687 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3688 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003690
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003691 if (PyBytes_GET_SIZE(path) == 0) {
3692 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 PyErr_SetString(PyExc_ImportError, "empty pathname");
3694 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003696
3697 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3698 Py_DECREF(path);
3699 if (rv == 0) {
3700 /* it exists */
3701 if (S_ISDIR(statbuf.st_mode)) {
3702 /* it's a directory */
3703 PyErr_SetString(PyExc_ImportError, "existing directory");
3704 return -1;
3705 }
3706 }
3707#else /* MS_WINDOWS */
3708 PyObject *pathobj;
3709 DWORD rv;
3710 wchar_t path[MAXPATHLEN+1];
3711 Py_ssize_t len;
3712
3713 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3714 return -1;
3715
3716 if (!PyArg_ParseTuple(args, "U:NullImporter",
3717 &pathobj))
3718 return -1;
3719
3720 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3721 PyErr_SetString(PyExc_ImportError, "empty pathname");
3722 return -1;
3723 }
3724
3725 len = PyUnicode_AsWideChar((PyUnicodeObject*)pathobj,
3726 path, sizeof(path) / sizeof(path[0]));
3727 if (len == -1)
3728 return -1;
3729 /* see issue1293 and issue3677:
3730 * stat() on Windows doesn't recognise paths like
3731 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3732 */
3733 rv = GetFileAttributesW(path);
3734 if (rv != INVALID_FILE_ATTRIBUTES) {
3735 /* it exists */
3736 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3737 /* it's a directory */
3738 PyErr_SetString(PyExc_ImportError, "existing directory");
3739 return -1;
3740 }
3741 }
3742#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003744}
3745
3746static PyObject *
3747NullImporter_find_module(NullImporter *self, PyObject *args)
3748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003750}
3751
3752static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3754 "Always return None"
3755 },
3756 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003757};
3758
3759
Christian Heimes9cd17752007-11-18 19:35:23 +00003760PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 PyVarObject_HEAD_INIT(NULL, 0)
3762 "imp.NullImporter", /*tp_name*/
3763 sizeof(NullImporter), /*tp_basicsize*/
3764 0, /*tp_itemsize*/
3765 0, /*tp_dealloc*/
3766 0, /*tp_print*/
3767 0, /*tp_getattr*/
3768 0, /*tp_setattr*/
3769 0, /*tp_reserved*/
3770 0, /*tp_repr*/
3771 0, /*tp_as_number*/
3772 0, /*tp_as_sequence*/
3773 0, /*tp_as_mapping*/
3774 0, /*tp_hash */
3775 0, /*tp_call*/
3776 0, /*tp_str*/
3777 0, /*tp_getattro*/
3778 0, /*tp_setattro*/
3779 0, /*tp_as_buffer*/
3780 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3781 "Null importer object", /* tp_doc */
3782 0, /* tp_traverse */
3783 0, /* tp_clear */
3784 0, /* tp_richcompare */
3785 0, /* tp_weaklistoffset */
3786 0, /* tp_iter */
3787 0, /* tp_iternext */
3788 NullImporter_methods, /* tp_methods */
3789 0, /* tp_members */
3790 0, /* tp_getset */
3791 0, /* tp_base */
3792 0, /* tp_dict */
3793 0, /* tp_descr_get */
3794 0, /* tp_descr_set */
3795 0, /* tp_dictoffset */
3796 (initproc)NullImporter_init, /* tp_init */
3797 0, /* tp_alloc */
3798 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003799};
3800
Martin v. Löwis1a214512008-06-11 05:26:20 +00003801static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 PyModuleDef_HEAD_INIT,
3803 "imp",
3804 doc_imp,
3805 0,
3806 imp_methods,
3807 NULL,
3808 NULL,
3809 NULL,
3810 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003811};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003812
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003813PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003814PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 if (PyType_Ready(&PyNullImporter_Type) < 0)
3819 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 m = PyModule_Create(&impmodule);
3822 if (m == NULL)
3823 goto failure;
3824 d = PyModule_GetDict(m);
3825 if (d == NULL)
3826 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3829 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3830 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3831 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3832 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3833 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3834 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3835 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3836 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3837 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 Py_INCREF(&PyNullImporter_Type);
3840 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3841 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003842 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 Py_XDECREF(m);
3844 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003845}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003846
3847
Guido van Rossumb18618d2000-05-03 23:44:39 +00003848/* API for embedding applications that want to add their own entries
3849 to the table of built-in modules. This should normally be called
3850 *before* Py_Initialize(). When the table resize fails, -1 is
3851 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003852
3853 After a similar function by Just van Rossum. */
3854
3855int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003856PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 static struct _inittab *our_copy = NULL;
3859 struct _inittab *p;
3860 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 /* Count the number of entries in both tables */
3863 for (n = 0; newtab[n].name != NULL; n++)
3864 ;
3865 if (n == 0)
3866 return 0; /* Nothing to do */
3867 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3868 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 /* Allocate new memory for the combined table */
3871 p = our_copy;
3872 PyMem_RESIZE(p, struct _inittab, i+n+1);
3873 if (p == NULL)
3874 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 /* Copy the tables into the new memory */
3877 if (our_copy != PyImport_Inittab)
3878 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3879 PyImport_Inittab = our_copy = p;
3880 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003883}
3884
3885/* Shorthand to add a single entry given a name and a function */
3886
3887int
Brett Cannona826f322009-04-02 03:41:46 +00003888PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 newtab[0].name = (char *)name;
3895 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003898}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003899
3900#ifdef __cplusplus
3901}
3902#endif