blob: 84ddc03c524706e374d18a7826283a529a99d4d6 [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
Tim Peters36515e22001-11-18 04:06:29 +0000104*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000105
Barry Warsaw28a691b2010-04-17 00:19:56 +0000106/* If you change MAGIC, you must change TAG and you must insert the old value
107 into _PyMagicNumberTags below.
108*/
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000109#define MAGIC (3160 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000110#define TAG "cpython-32"
111#define CACHEDIR "__pycache__"
112/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000113static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116/* See _PyImport_FixupExtension() below */
117static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000118
Guido van Rossum771c6c81997-10-31 18:37:24 +0000119/* This table is defined in config.c: */
120extern struct _inittab _PyImport_Inittab[];
121
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000122/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000123extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000124
Guido van Rossum771c6c81997-10-31 18:37:24 +0000125struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000126
Guido van Rossumed1170e1999-12-20 21:23:41 +0000127/* these tables define the module suffixes that Python recognizes */
128struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000129
Guido van Rossumed1170e1999-12-20 21:23:41 +0000130static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000132#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000134#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {".pyc", "rb", PY_COMPILED},
136 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000137};
138
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000140/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141
142void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000143_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 const struct filedescr *scan;
146 struct filedescr *filetab;
147 int countD = 0;
148 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 /* prepare _PyImport_Filetab: copy entries from
151 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
152 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000153#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
155 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000156#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
158 ++countS;
159 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
160 if (filetab == NULL)
161 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000162#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 memcpy(filetab, _PyImport_DynLoadFiletab,
164 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000165#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 memcpy(filetab + countD, _PyImport_StandardFiletab,
167 countS * sizeof(struct filedescr));
168 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (Py_OptimizeFlag) {
173 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
174 for (; filetab->suffix != NULL; filetab++) {
175 if (strcmp(filetab->suffix, ".pyc") == 0)
176 filetab->suffix = ".pyo";
177 }
178 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179}
180
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181void
Just van Rossum52e14d62002-12-30 22:08:05 +0000182_PyImportHooks_Init(void)
183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyObject *v, *path_hooks = NULL, *zimpimport;
185 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 /* adding sys.path_hooks and sys.path_importer_cache, setting up
188 zipimport */
189 if (PyType_Ready(&PyNullImporter_Type) < 0)
190 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (Py_VerboseFlag)
193 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 v = PyList_New(0);
196 if (v == NULL)
197 goto error;
198 err = PySys_SetObject("meta_path", v);
199 Py_DECREF(v);
200 if (err)
201 goto error;
202 v = PyDict_New();
203 if (v == NULL)
204 goto error;
205 err = PySys_SetObject("path_importer_cache", v);
206 Py_DECREF(v);
207 if (err)
208 goto error;
209 path_hooks = PyList_New(0);
210 if (path_hooks == NULL)
211 goto error;
212 err = PySys_SetObject("path_hooks", path_hooks);
213 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000214 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 PyErr_Print();
216 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
217 "path_importer_cache, or NullImporter failed"
218 );
219 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 zimpimport = PyImport_ImportModule("zipimport");
222 if (zimpimport == NULL) {
223 PyErr_Clear(); /* No zip import module -- okay */
224 if (Py_VerboseFlag)
225 PySys_WriteStderr("# can't import zipimport\n");
226 }
227 else {
228 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
229 "zipimporter");
230 Py_DECREF(zimpimport);
231 if (zipimporter == NULL) {
232 PyErr_Clear(); /* No zipimporter object -- okay */
233 if (Py_VerboseFlag)
234 PySys_WriteStderr(
235 "# can't import zipimport.zipimporter\n");
236 }
237 else {
238 /* sys.path_hooks.append(zipimporter) */
239 err = PyList_Append(path_hooks, zipimporter);
240 Py_DECREF(zipimporter);
241 if (err)
242 goto error;
243 if (Py_VerboseFlag)
244 PySys_WriteStderr(
245 "# installed zipimport hook\n");
246 }
247 }
248 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000249}
250
251void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000252_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_XDECREF(extensions);
255 extensions = NULL;
256 PyMem_DEL(_PyImport_Filetab);
257 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000258}
259
260
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000261/* Locking primitives to prevent parallel imports of the same module
262 in different threads to return with a partially loaded module.
263 These calls are serialized by the global interpreter lock. */
264
265#ifdef WITH_THREAD
266
Guido van Rossum49b56061998-10-01 20:42:43 +0000267#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000268
Guido van Rossum65d5b571998-12-21 19:32:43 +0000269static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000270static long import_lock_thread = -1;
271static int import_lock_level = 0;
272
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000273void
274_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 long me = PyThread_get_thread_ident();
277 if (me == -1)
278 return; /* Too bad */
279 if (import_lock == NULL) {
280 import_lock = PyThread_allocate_lock();
281 if (import_lock == NULL)
282 return; /* Nothing much we can do. */
283 }
284 if (import_lock_thread == me) {
285 import_lock_level++;
286 return;
287 }
288 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
289 {
290 PyThreadState *tstate = PyEval_SaveThread();
291 PyThread_acquire_lock(import_lock, 1);
292 PyEval_RestoreThread(tstate);
293 }
294 import_lock_thread = me;
295 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000296}
297
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000298int
299_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 long me = PyThread_get_thread_ident();
302 if (me == -1 || import_lock == NULL)
303 return 0; /* Too bad */
304 if (import_lock_thread != me)
305 return -1;
306 import_lock_level--;
307 if (import_lock_level == 0) {
308 import_lock_thread = -1;
309 PyThread_release_lock(import_lock);
310 }
311 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000312}
313
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000314/* This function is called from PyOS_AfterFork to ensure that newly
315 created child processes do not share locks with the parent.
316 We now acquire the import lock around fork() calls but on some platforms
317 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000318
319void
320_PyImport_ReInitLock(void)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 if (import_lock != NULL)
323 import_lock = PyThread_allocate_lock();
324 import_lock_thread = -1;
325 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000326}
327
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000328#endif
329
Tim Peters69232342001-08-30 05:16:13 +0000330static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000331imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000332{
Tim Peters69232342001-08-30 05:16:13 +0000333#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000335#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000337#endif
338}
339
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000340static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000341imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000343#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_INCREF(Py_None);
347 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348}
349
350static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000351imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (_PyImport_ReleaseLock() < 0) {
355 PyErr_SetString(PyExc_RuntimeError,
356 "not holding the import lock");
357 return NULL;
358 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000359#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 Py_INCREF(Py_None);
361 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000362}
363
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364static void
365imp_modules_reloading_clear(void)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyInterpreterState *interp = PyThreadState_Get()->interp;
368 if (interp->modules_reloading != NULL)
369 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000370}
371
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372/* Helper for sys */
373
374PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyInterpreterState *interp = PyThreadState_GET()->interp;
378 if (interp->modules == NULL)
379 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
380 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000381}
382
Guido van Rossum3f5da241990-12-20 15:06:42 +0000383
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000384/* List of names to clear in sys */
385static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 "path", "argv", "ps1", "ps2",
387 "last_type", "last_value", "last_traceback",
388 "path_hooks", "path_importer_cache", "meta_path",
389 /* misc stuff */
390 "flags", "float_info",
391 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392};
393
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000394static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 "stdin", "__stdin__",
396 "stdout", "__stdout__",
397 "stderr", "__stderr__",
398 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000399};
400
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000401
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000402/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000403
Guido van Rossum3f5da241990-12-20 15:06:42 +0000404void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000405PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_ssize_t pos, ndone;
408 char *name;
409 PyObject *key, *value, *dict;
410 PyInterpreterState *interp = PyThreadState_GET()->interp;
411 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (modules == NULL)
414 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 /* Delete some special variables first. These are common
417 places where user values hide and people complain when their
418 destructors fail. Since the modules containing them are
419 deleted *last* of all, they would come too late in the normal
420 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 value = PyDict_GetItemString(modules, "builtins");
423 if (value != NULL && PyModule_Check(value)) {
424 dict = PyModule_GetDict(value);
425 if (Py_VerboseFlag)
426 PySys_WriteStderr("# clear builtins._\n");
427 PyDict_SetItemString(dict, "_", Py_None);
428 }
429 value = PyDict_GetItemString(modules, "sys");
430 if (value != NULL && PyModule_Check(value)) {
431 char **p;
432 PyObject *v;
433 dict = PyModule_GetDict(value);
434 for (p = sys_deletes; *p != NULL; p++) {
435 if (Py_VerboseFlag)
436 PySys_WriteStderr("# clear sys.%s\n", *p);
437 PyDict_SetItemString(dict, *p, Py_None);
438 }
439 for (p = sys_files; *p != NULL; p+=2) {
440 if (Py_VerboseFlag)
441 PySys_WriteStderr("# restore sys.%s\n", *p);
442 v = PyDict_GetItemString(dict, *(p+1));
443 if (v == NULL)
444 v = Py_None;
445 PyDict_SetItemString(dict, *p, v);
446 }
447 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 /* First, delete __main__ */
450 value = PyDict_GetItemString(modules, "__main__");
451 if (value != NULL && PyModule_Check(value)) {
452 if (Py_VerboseFlag)
453 PySys_WriteStderr("# cleanup __main__\n");
454 _PyModule_Clear(value);
455 PyDict_SetItemString(modules, "__main__", Py_None);
456 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 /* The special treatment of "builtins" here is because even
459 when it's not referenced as a module, its dictionary is
460 referenced by almost every module's __builtins__. Since
461 deleting a module clears its dictionary (even if there are
462 references left to it), we need to delete the "builtins"
463 module last. Likewise, we don't delete sys until the very
464 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 Also note that we 'delete' modules by replacing their entry
467 in the modules dict with None, rather than really deleting
468 them; this avoids a rehash of the modules dictionary and
469 also marks them as "non existent" so they won't be
470 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 /* Next, repeatedly delete modules with a reference count of
473 one (skipping builtins and sys) and delete them */
474 do {
475 ndone = 0;
476 pos = 0;
477 while (PyDict_Next(modules, &pos, &key, &value)) {
478 if (value->ob_refcnt != 1)
479 continue;
480 if (PyUnicode_Check(key) && PyModule_Check(value)) {
481 name = _PyUnicode_AsString(key);
482 if (strcmp(name, "builtins") == 0)
483 continue;
484 if (strcmp(name, "sys") == 0)
485 continue;
486 if (Py_VerboseFlag)
487 PySys_WriteStderr(
488 "# cleanup[1] %s\n", name);
489 _PyModule_Clear(value);
490 PyDict_SetItem(modules, key, Py_None);
491 ndone++;
492 }
493 }
494 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* Next, delete all modules (still skipping builtins and sys) */
497 pos = 0;
498 while (PyDict_Next(modules, &pos, &key, &value)) {
499 if (PyUnicode_Check(key) && PyModule_Check(value)) {
500 name = _PyUnicode_AsString(key);
501 if (strcmp(name, "builtins") == 0)
502 continue;
503 if (strcmp(name, "sys") == 0)
504 continue;
505 if (Py_VerboseFlag)
506 PySys_WriteStderr("# cleanup[2] %s\n", name);
507 _PyModule_Clear(value);
508 PyDict_SetItem(modules, key, Py_None);
509 }
510 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Next, delete sys and builtins (in that order) */
513 value = PyDict_GetItemString(modules, "sys");
514 if (value != NULL && PyModule_Check(value)) {
515 if (Py_VerboseFlag)
516 PySys_WriteStderr("# cleanup sys\n");
517 _PyModule_Clear(value);
518 PyDict_SetItemString(modules, "sys", Py_None);
519 }
520 value = PyDict_GetItemString(modules, "builtins");
521 if (value != NULL && PyModule_Check(value)) {
522 if (Py_VerboseFlag)
523 PySys_WriteStderr("# cleanup builtins\n");
524 _PyModule_Clear(value);
525 PyDict_SetItemString(modules, "builtins", Py_None);
526 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Finally, clear and delete the modules directory */
529 PyDict_Clear(modules);
530 interp->modules = NULL;
531 Py_DECREF(modules);
532 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000533}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000534
535
Barry Warsaw28a691b2010-04-17 00:19:56 +0000536/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000537
538long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000539PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000542}
543
544
Barry Warsaw28a691b2010-04-17 00:19:56 +0000545const char *
546PyImport_GetMagicTag(void)
547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549}
550
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551/* Magic for extension modules (built-in as well as dynamically
552 loaded). To prevent initializing an extension module more than
553 once, we keep a static dictionary 'extensions' keyed by module name
554 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000555 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556 dictionary is stored by calling _PyImport_FixupExtension()
557 immediately after the module initialization function succeeds. A
558 copy can be retrieved from there by calling
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000559 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000561 Modules which do support multiple initialization set their m_size
562 field to a non-negative number (indicating the size of the
563 module-specific state). They are still recorded in the extensions
564 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000565*/
566
567int
568_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 PyObject *modules, *dict;
571 struct PyModuleDef *def;
572 if (extensions == NULL) {
573 extensions = PyDict_New();
574 if (extensions == NULL)
575 return -1;
576 }
577 if (mod == NULL || !PyModule_Check(mod)) {
578 PyErr_BadInternalCall();
579 return -1;
580 }
581 def = PyModule_GetDef(mod);
582 if (!def) {
583 PyErr_BadInternalCall();
584 return -1;
585 }
586 modules = PyImport_GetModuleDict();
587 if (PyDict_SetItemString(modules, name, mod) < 0)
588 return -1;
589 if (_PyState_AddModule(mod, def) < 0) {
590 PyDict_DelItemString(modules, name);
591 return -1;
592 }
593 if (def->m_size == -1) {
594 if (def->m_base.m_copy) {
595 /* Somebody already imported the module,
596 likely under a different name.
597 XXX this should really not happen. */
598 Py_DECREF(def->m_base.m_copy);
599 def->m_base.m_copy = NULL;
600 }
601 dict = PyModule_GetDict(mod);
602 if (dict == NULL)
603 return -1;
604 def->m_base.m_copy = PyDict_Copy(dict);
605 if (def->m_base.m_copy == NULL)
606 return -1;
607 }
608 PyDict_SetItemString(extensions, filename, (PyObject*)def);
609 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610}
611
612PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000613_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyObject *mod, *mdict;
616 PyModuleDef* def;
617 if (extensions == NULL)
618 return NULL;
619 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
620 if (def == NULL)
621 return NULL;
622 if (def->m_size == -1) {
623 /* Module does not support repeated initialization */
624 if (def->m_base.m_copy == NULL)
625 return NULL;
626 mod = PyImport_AddModule(name);
627 if (mod == NULL)
628 return NULL;
629 mdict = PyModule_GetDict(mod);
630 if (mdict == NULL)
631 return NULL;
632 if (PyDict_Update(mdict, def->m_base.m_copy))
633 return NULL;
634 }
635 else {
636 if (def->m_base.m_init == NULL)
637 return NULL;
638 mod = def->m_base.m_init();
639 if (mod == NULL)
640 return NULL;
641 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
642 Py_DECREF(mod);
643 }
644 if (_PyState_AddModule(mod, def) < 0) {
645 PyDict_DelItemString(PyImport_GetModuleDict(), name);
646 Py_DECREF(mod);
647 return NULL;
648 }
649 if (Py_VerboseFlag)
650 PySys_WriteStderr("import %s # previously loaded (%s)\n",
651 name, filename);
652 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000653
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000654}
655
656
657/* Get the module object corresponding to a module name.
658 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000659 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000660 Because the former action is most common, THIS DOES NOT RETURN A
661 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662
Guido van Rossum79f25d91997-04-29 20:08:16 +0000663PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000664PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 PyObject *modules = PyImport_GetModuleDict();
667 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
670 PyModule_Check(m))
671 return m;
672 m = PyModule_New(name);
673 if (m == NULL)
674 return NULL;
675 if (PyDict_SetItemString(modules, name, m) != 0) {
676 Py_DECREF(m);
677 return NULL;
678 }
679 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000682}
683
Tim Peters1cd70172004-08-02 03:52:12 +0000684/* Remove name from sys.modules, if it's there. */
685static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000686remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyObject *modules = PyImport_GetModuleDict();
689 if (PyDict_GetItemString(modules, name) == NULL)
690 return;
691 if (PyDict_DelItemString(modules, name) < 0)
692 Py_FatalError("import: deleting existing key in"
693 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000694}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000695
Barry Warsaw28a691b2010-04-17 00:19:56 +0000696static PyObject * get_sourcefile(char *file);
697static char *make_source_pathname(char *pathname, char *buf);
698static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000700
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000701/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000702 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
703 * removed from sys.modules, to avoid leaving damaged module objects
704 * in sys.modules. The caller may wish to restore the original
705 * module object (if any) in this case; PyImport_ReloadModule is an
706 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000707 *
708 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
709 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000710 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 return PyImport_ExecCodeModuleWithPathnames(
715 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000716}
717
718PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000719PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 return PyImport_ExecCodeModuleWithPathnames(
722 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000723}
724
725PyObject *
726PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyObject *modules = PyImport_GetModuleDict();
730 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 m = PyImport_AddModule(name);
733 if (m == NULL)
734 return NULL;
735 /* If the module is being reloaded, we get the old module back
736 and re-use its dict to exec the new code. */
737 d = PyModule_GetDict(m);
738 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
739 if (PyDict_SetItemString(d, "__builtins__",
740 PyEval_GetBuiltins()) != 0)
741 goto error;
742 }
743 /* Remember the filename as the __file__ attribute */
744 v = NULL;
745 if (pathname != NULL) {
746 v = get_sourcefile(pathname);
747 if (v == NULL)
748 PyErr_Clear();
749 }
750 if (v == NULL) {
751 v = ((PyCodeObject *)co)->co_filename;
752 Py_INCREF(v);
753 }
754 if (PyDict_SetItemString(d, "__file__", v) != 0)
755 PyErr_Clear(); /* Not important enough to report */
756 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* Remember the pyc path name as the __cached__ attribute. */
759 if (cpathname == NULL) {
760 v = Py_None;
761 Py_INCREF(v);
762 }
763 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
764 PyErr_Clear(); /* Not important enough to report */
765 v = Py_None;
766 Py_INCREF(v);
767 }
768 if (PyDict_SetItemString(d, "__cached__", v) != 0)
769 PyErr_Clear(); /* Not important enough to report */
770 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
773 if (v == NULL)
774 goto error;
775 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
778 PyErr_Format(PyExc_ImportError,
779 "Loaded module %.200s not found in sys.modules",
780 name);
781 return NULL;
782 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000787
788 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 remove_module(name);
790 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791}
792
793
Barry Warsaw28a691b2010-04-17 00:19:56 +0000794/* Like strrchr(string, '/') but searches for the rightmost of either SEP
795 or ALTSEP, if the latter is defined.
796*/
797static char *
798rightmost_sep(char *s)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 char *found, c;
801 for (found = NULL; (c = *s); s++) {
802 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000803#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000805#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 )
807 {
808 found = s;
809 }
810 }
811 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000812}
813
814
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000815/* Given a pathname for a Python source file, fill a buffer with the
816 pathname for the corresponding compiled file. Return the pathname
817 for the compiled file, or NULL if there's no space in the buffer.
818 Doesn't set an exception. */
819
820static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000821make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 /* foo.py -> __pycache__/foo.<tag>.pyc */
824 size_t len = strlen(pathname);
825 size_t i, save;
826 char *pos;
827 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 /* Sanity check that the buffer has roughly enough space to hold what
830 will eventually be the full path to the compiled file. The 5 extra
831 bytes include the slash afer __pycache__, the two extra dots, the
832 extra trailing character ('c' or 'o') and null. This isn't exact
833 because the contents of the buffer can affect how many actual
834 characters of the string get into the buffer. We'll do a final
835 sanity check before writing the extension to ensure we do not
836 overflow the buffer.
837 */
838 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
839 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 /* Find the last path separator and copy everything from the start of
842 the source string up to and including the separator.
843 */
844 if ((pos = rightmost_sep(pathname)) == NULL) {
845 i = 0;
846 }
847 else {
848 sep = *pos;
849 i = pos - pathname + 1;
850 strncpy(buf, pathname, i);
851 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 save = i;
854 buf[i++] = '\0';
855 /* Add __pycache__/ */
856 strcat(buf, CACHEDIR);
857 i += strlen(CACHEDIR) - 1;
858 buf[i++] = sep;
859 buf[i++] = '\0';
860 /* Add the base filename, but remove the .py or .pyw extension, since
861 the tag name must go before the extension.
862 */
863 strcat(buf, pathname + save);
864 if ((pos = strrchr(buf, '.')) != NULL)
865 *++pos = '\0';
866 strcat(buf, pyc_tag);
867 /* The length test above assumes that we're only adding one character
868 to the end of what would normally be the extension. What if there
869 is no extension, or the string ends in '.' or '.p', and otherwise
870 fills the buffer? By appending 4 more characters onto the string
871 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 As a simple example, let's say buflen=32 and the input string is
874 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 which is false and so the name mangling would continue. This would
879 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
884 We can even handle an input string of say 'xxxxx' above because
885 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
886 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 which is 32 characters including the nul, and thus fits in the
891 buffer. However, an input string of 'xxxxxx' would yield a result
892 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 which is 33 characters long (including the nul), thus overflowing
897 the buffer, even though the first test would fail, i.e.: the input
898 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 The reason the first test fails but we still overflow the buffer is
901 that the test above only expects to add one extra character to be
902 added to the extension, and here we're adding three (pyc). We
903 don't add the first dot, so that reclaims one of expected
904 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
905 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 The best we can do is ensure that we still have enough room in the
908 target buffer before we write the extension. Because it's always
909 only the extension that can cause the overflow, and never the other
910 path bytes we've written, it's sufficient to just do one more test
911 here. Still, the assertion that follows can't hurt.
912 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000913#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000915#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (strlen(buf) + 5 > buflen)
917 return NULL;
918 strcat(buf, debug ? ".pyc" : ".pyo");
919 assert(strlen(buf) < buflen);
920 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000921}
922
923
Barry Warsaw28a691b2010-04-17 00:19:56 +0000924/* Given a pathname to a Python byte compiled file, return the path to the
925 source file, if the path matches the PEP 3147 format. This does not check
926 for any file existence, however, if the pyc file name does not match PEP
927 3147 style, NULL is returned. buf must be at least as big as pathname;
928 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929
Barry Warsaw28a691b2010-04-17 00:19:56 +0000930static char *
931make_source_pathname(char *pathname, char *buf)
932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* __pycache__/foo.<tag>.pyc -> foo.py */
934 size_t i, j;
935 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* Look back two slashes from the end. In between these two slashes
938 must be the string __pycache__ or this is not a PEP 3147 style
939 path. It's possible for there to be only one slash.
940 */
941 if ((right = rightmost_sep(pathname)) == NULL)
942 return NULL;
943 sep = *right;
944 *right = '\0';
945 left = rightmost_sep(pathname);
946 *right = sep;
947 if (left == NULL)
948 left = pathname;
949 else
950 left++;
951 if (right-left != strlen(CACHEDIR) ||
952 strncmp(left, CACHEDIR, right-left) != 0)
953 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Now verify that the path component to the right of the last slash
956 has two dots in it.
957 */
958 if ((dot0 = strchr(right + 1, '.')) == NULL)
959 return NULL;
960 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
961 return NULL;
962 /* Too many dots? */
963 if (strchr(dot1 + 1, '.') != NULL)
964 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* This is a PEP 3147 path. Start by copying everything from the
967 start of pathname up to and including the leftmost slash. Then
968 copy the file's basename, removing the magic tag and adding a .py
969 suffix.
970 */
971 strncpy(buf, pathname, (i=left-pathname));
972 strncpy(buf+i, right+1, (j=dot0-right));
973 strcpy(buf+i+j, "py");
974 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000975}
976
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000977/* Given a pathname for a Python source file, its time of last
978 modification, and a pathname for a compiled file, check whether the
979 compiled file represents the same version of the source. If so,
980 return a FILE pointer for the compiled file, positioned just after
981 the header; if not, return NULL.
982 Doesn't set an exception. */
983
984static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000985check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 FILE *fp;
988 long magic;
989 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 fp = fopen(cpathname, "rb");
992 if (fp == NULL)
993 return NULL;
994 magic = PyMarshal_ReadLongFromFile(fp);
995 if (magic != pyc_magic) {
996 if (Py_VerboseFlag)
997 PySys_WriteStderr("# %s has bad magic\n", cpathname);
998 fclose(fp);
999 return NULL;
1000 }
1001 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1002 if (pyc_mtime != mtime) {
1003 if (Py_VerboseFlag)
1004 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1005 fclose(fp);
1006 return NULL;
1007 }
1008 if (Py_VerboseFlag)
1009 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1010 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001011}
1012
1013
1014/* Read a code object from a file and check it for validity */
1015
Guido van Rossum79f25d91997-04-29 20:08:16 +00001016static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001017read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 co = PyMarshal_ReadLastObjectFromFile(fp);
1022 if (co == NULL)
1023 return NULL;
1024 if (!PyCode_Check(co)) {
1025 PyErr_Format(PyExc_ImportError,
1026 "Non-code object in %.200s", cpathname);
1027 Py_DECREF(co);
1028 return NULL;
1029 }
1030 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001031}
1032
1033
1034/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001035 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001036
Guido van Rossum79f25d91997-04-29 20:08:16 +00001037static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001038load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 long magic;
1041 PyCodeObject *co;
1042 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 magic = PyMarshal_ReadLongFromFile(fp);
1045 if (magic != pyc_magic) {
1046 PyErr_Format(PyExc_ImportError,
1047 "Bad magic number in %.200s", cpathname);
1048 return NULL;
1049 }
1050 (void) PyMarshal_ReadLongFromFile(fp);
1051 co = read_compiled_module(cpathname, fp);
1052 if (co == NULL)
1053 return NULL;
1054 if (Py_VerboseFlag)
1055 PySys_WriteStderr("import %s # precompiled from %s\n",
1056 name, cpathname);
1057 m = PyImport_ExecCodeModuleWithPathnames(
1058 name, (PyObject *)co, cpathname, cpathname);
1059 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001062}
1063
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064/* Parse a source file and return the corresponding code object */
1065
Guido van Rossum79f25d91997-04-29 20:08:16 +00001066static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyCodeObject *co = NULL;
1070 mod_ty mod;
1071 PyCompilerFlags flags;
1072 PyArena *arena = PyArena_New();
1073 if (arena == NULL)
1074 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 flags.cf_flags = 0;
1077 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1078 Py_file_input, 0, 0, &flags,
1079 NULL, arena);
1080 if (mod) {
1081 co = PyAST_Compile(mod, pathname, NULL, arena);
1082 }
1083 PyArena_Free(arena);
1084 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001085}
1086
1087
Guido van Rossum55a83382000-09-20 20:31:38 +00001088/* Helper to open a bytecode file for writing in exclusive mode */
1089
1090static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001091open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001092{
1093#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* Use O_EXCL to avoid a race condition when another process tries to
1095 write the same file. When that happens, our open() call fails,
1096 which is just fine (since it's only a cache).
1097 XXX If the file exists and is writable but the directory is not
1098 writable, the file will never be written. Oh well.
1099 */
1100 int fd;
1101 (void) unlink(filename);
1102 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001103#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001105#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001106#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001108#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001110#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 );
1112 if (fd < 0)
1113 return NULL;
1114 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001115#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 /* Best we can do -- on Windows this can't happen anyway */
1117 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001118#endif
1119}
1120
1121
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122/* Write a compiled module to a file, placing the time of last
1123 modification of its source into the header.
1124 Errors are ignored, if a write error occurs an attempt is made to
1125 remove the file. */
1126
1127static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001128write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 FILE *fp;
1131 char *dirpath;
1132 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001133#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 mode_t mode = srcstat->st_mode & ~S_IEXEC;
1135 mode_t dirmode = srcstat->st_mode | S_IEXEC; /* XXX Is this correct
1136 for Windows?
1137 2010-04-07 BAW */
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001138#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1140 mode_t dirmode = (srcstat->st_mode |
1141 S_IXUSR | S_IXGRP | S_IXOTH |
1142 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001143#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 /* Ensure that the __pycache__ directory exists. */
1147 dirpath = rightmost_sep(cpathname);
1148 if (dirpath == NULL) {
1149 if (Py_VerboseFlag)
1150 PySys_WriteStderr(
1151 "# no %s path found %s\n",
1152 CACHEDIR, cpathname);
1153 return;
1154 }
1155 saved = *dirpath;
1156 *dirpath = '\0';
1157 /* XXX call os.mkdir() or maybe CreateDirectoryA() on Windows? */
1158 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
1159 *dirpath = saved;
1160 if (Py_VerboseFlag)
1161 PySys_WriteStderr(
1162 "# cannot create cache dir %s\n", cpathname);
1163 return;
1164 }
1165 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 fp = open_exclusive(cpathname, mode);
1168 if (fp == NULL) {
1169 if (Py_VerboseFlag)
1170 PySys_WriteStderr(
1171 "# can't create %s\n", cpathname);
1172 return;
1173 }
1174 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1175 /* First write a 0 for mtime */
1176 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1177 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1178 if (fflush(fp) != 0 || ferror(fp)) {
1179 if (Py_VerboseFlag)
1180 PySys_WriteStderr("# can't write %s\n", cpathname);
1181 /* Don't keep partial file */
1182 fclose(fp);
1183 (void) unlink(cpathname);
1184 return;
1185 }
1186 /* Now write the true mtime */
1187 fseek(fp, 4L, 0);
1188 assert(mtime < LONG_MAX);
1189 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1190 fflush(fp);
1191 fclose(fp);
1192 if (Py_VerboseFlag)
1193 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001194}
1195
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001196static void
1197update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *constants, *tmp;
1200 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (PyUnicode_Compare(co->co_filename, oldname))
1203 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 tmp = co->co_filename;
1206 co->co_filename = newname;
1207 Py_INCREF(co->co_filename);
1208 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 constants = co->co_consts;
1211 n = PyTuple_GET_SIZE(constants);
1212 for (i = 0; i < n; i++) {
1213 tmp = PyTuple_GET_ITEM(constants, i);
1214 if (PyCode_Check(tmp))
1215 update_code_filenames((PyCodeObject *)tmp,
1216 oldname, newname);
1217 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001218}
1219
1220static int
1221update_compiled_module(PyCodeObject *co, char *pathname)
1222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 newname = PyUnicode_DecodeFSDefault(pathname);
1226 if (newname == NULL)
1227 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (!PyUnicode_Compare(co->co_filename, newname)) {
1230 Py_DECREF(newname);
1231 return 0;
1232 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 oldname = co->co_filename;
1235 Py_INCREF(oldname);
1236 update_code_filenames(co, oldname, newname);
1237 Py_DECREF(oldname);
1238 Py_DECREF(newname);
1239 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001240}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001241
1242/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001243 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1244 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001245
Guido van Rossum79f25d91997-04-29 20:08:16 +00001246static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001247load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 struct stat st;
1250 FILE *fpc;
1251 char buf[MAXPATHLEN+1];
1252 char *cpathname;
1253 PyCodeObject *co;
1254 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (fstat(fileno(fp), &st) != 0) {
1257 PyErr_Format(PyExc_RuntimeError,
1258 "unable to get file status from '%s'",
1259 pathname);
1260 return NULL;
1261 }
Fred Drake4c82b232000-06-30 16:18:57 +00001262#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* Python's .pyc timestamp handling presumes that the timestamp fits
1264 in 4 bytes. This will be fine until sometime in the year 2038,
1265 when a 4-byte signed time_t will overflow.
1266 */
1267 if (st.st_mtime >> 32) {
1268 PyErr_SetString(PyExc_OverflowError,
1269 "modification time overflows a 4 byte field");
1270 return NULL;
1271 }
Fred Drake4c82b232000-06-30 16:18:57 +00001272#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 cpathname = make_compiled_pathname(
1274 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1275 if (cpathname != NULL &&
1276 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1277 co = read_compiled_module(cpathname, fpc);
1278 fclose(fpc);
1279 if (co == NULL)
1280 return NULL;
1281 if (update_compiled_module(co, pathname) < 0)
1282 return NULL;
1283 if (Py_VerboseFlag)
1284 PySys_WriteStderr("import %s # precompiled from %s\n",
1285 name, cpathname);
1286 pathname = cpathname;
1287 }
1288 else {
1289 co = parse_source_module(pathname, fp);
1290 if (co == NULL)
1291 return NULL;
1292 if (Py_VerboseFlag)
1293 PySys_WriteStderr("import %s # from %s\n",
1294 name, pathname);
1295 if (cpathname) {
1296 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1297 if (ro == NULL || !PyObject_IsTrue(ro))
1298 write_compiled_module(co, cpathname, &st);
1299 }
1300 }
1301 m = PyImport_ExecCodeModuleWithPathnames(
1302 name, (PyObject *)co, pathname, cpathname);
1303 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001306}
1307
Christian Heimes3b06e532008-01-07 20:12:44 +00001308/* Get source file -> unicode or None
1309 * Returns the path to the py file if available, else the given path
1310 */
1311static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001312get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 char py[MAXPATHLEN + 1];
1315 Py_ssize_t len;
1316 PyObject *u;
1317 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!file || !*file) {
1320 Py_RETURN_NONE;
1321 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 len = strlen(file);
1324 /* match '*.py?' */
1325 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1326 return PyUnicode_DecodeFSDefault(file);
1327 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* Start by trying to turn PEP 3147 path into source path. If that
1330 * fails, just chop off the trailing character, i.e. legacy pyc path
1331 * to py.
1332 */
1333 if (make_source_pathname(file, py) == NULL) {
1334 strncpy(py, file, len-1);
1335 py[len-1] = '\0';
1336 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 if (stat(py, &statbuf) == 0 &&
1339 S_ISREG(statbuf.st_mode)) {
1340 u = PyUnicode_DecodeFSDefault(py);
1341 }
1342 else {
1343 u = PyUnicode_DecodeFSDefault(file);
1344 }
1345 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001346}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001347
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001348/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001349static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1350static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001352static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001353
1354/* Load a package and return its module object WITH INCREMENTED
1355 REFERENCE COUNT */
1356
1357static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001358load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyObject *m, *d;
1361 PyObject *file = NULL;
1362 PyObject *path = NULL;
1363 int err;
1364 char buf[MAXPATHLEN+1];
1365 FILE *fp = NULL;
1366 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 m = PyImport_AddModule(name);
1369 if (m == NULL)
1370 return NULL;
1371 if (Py_VerboseFlag)
1372 PySys_WriteStderr("import %s # directory %s\n",
1373 name, pathname);
1374 d = PyModule_GetDict(m);
1375 file = get_sourcefile(pathname);
1376 if (file == NULL)
1377 goto error;
1378 path = Py_BuildValue("[O]", file);
1379 if (path == NULL)
1380 goto error;
1381 err = PyDict_SetItemString(d, "__file__", file);
1382 if (err == 0)
1383 err = PyDict_SetItemString(d, "__path__", path);
1384 if (err != 0)
1385 goto error;
1386 buf[0] = '\0';
1387 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1388 if (fdp == NULL) {
1389 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1390 PyErr_Clear();
1391 Py_INCREF(m);
1392 }
1393 else
1394 m = NULL;
1395 goto cleanup;
1396 }
1397 m = load_module(name, fp, buf, fdp->type, NULL);
1398 if (fp != NULL)
1399 fclose(fp);
1400 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001401
1402 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001404 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 Py_XDECREF(path);
1406 Py_XDECREF(file);
1407 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001408}
1409
1410
1411/* Helper to test for built-in module */
1412
1413static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001414is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 int i;
1417 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1418 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1419 if (PyImport_Inittab[i].initfunc == NULL)
1420 return -1;
1421 else
1422 return 1;
1423 }
1424 }
1425 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001426}
1427
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001428
Just van Rossum52e14d62002-12-30 22:08:05 +00001429/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1430 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001431 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001432 that can handle the path item. Return None if no hook could;
1433 this tells our caller it should fall back to the builtin
1434 import mechanism. Cache the result in path_importer_cache.
1435 Returns a borrowed reference. */
1436
1437static PyObject *
1438get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *importer;
1442 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 /* These conditions are the caller's responsibility: */
1445 assert(PyList_Check(path_hooks));
1446 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 nhooks = PyList_Size(path_hooks);
1449 if (nhooks < 0)
1450 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 importer = PyDict_GetItem(path_importer_cache, p);
1453 if (importer != NULL)
1454 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 /* set path_importer_cache[p] to None to avoid recursion */
1457 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1458 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 for (j = 0; j < nhooks; j++) {
1461 PyObject *hook = PyList_GetItem(path_hooks, j);
1462 if (hook == NULL)
1463 return NULL;
1464 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1465 if (importer != NULL)
1466 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1469 return NULL;
1470 }
1471 PyErr_Clear();
1472 }
1473 if (importer == NULL) {
1474 importer = PyObject_CallFunctionObjArgs(
1475 (PyObject *)&PyNullImporter_Type, p, NULL
1476 );
1477 if (importer == NULL) {
1478 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1479 PyErr_Clear();
1480 return Py_None;
1481 }
1482 }
1483 }
1484 if (importer != NULL) {
1485 int err = PyDict_SetItem(path_importer_cache, p, importer);
1486 Py_DECREF(importer);
1487 if (err != 0)
1488 return NULL;
1489 }
1490 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001491}
1492
Christian Heimes9cd17752007-11-18 19:35:23 +00001493PyAPI_FUNC(PyObject *)
1494PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1498 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1499 importer = get_path_importer(path_importer_cache,
1500 path_hooks, path);
1501 }
1502 }
1503 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1504 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001505}
1506
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001507/* Search the path (default sys.path) for a module. Return the
1508 corresponding filedescr struct, and (via return arguments) the
1509 pathname and an open file. Return NULL if the module is not found. */
1510
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001511#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001512extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001514#endif
1515
Martin v. Löwis18e16552006-02-15 17:27:45 +00001516static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001517static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001518static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001519
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001520static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001521find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_ssize_t i, npath;
1525 size_t len, namelen;
1526 struct filedescr *fdp = NULL;
1527 char *filemode;
1528 FILE *fp = NULL;
1529 PyObject *path_hooks, *path_importer_cache;
1530 struct stat statbuf;
1531 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1532 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1533 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1534 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001535#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 size_t saved_len;
1537 size_t saved_namelen;
1538 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001539#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 if (p_loader != NULL)
1541 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 if (strlen(subname) > MAXPATHLEN) {
1544 PyErr_SetString(PyExc_OverflowError,
1545 "module name is too long");
1546 return NULL;
1547 }
1548 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 /* sys.meta_path import hook */
1551 if (p_loader != NULL) {
1552 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 meta_path = PySys_GetObject("meta_path");
1555 if (meta_path == NULL || !PyList_Check(meta_path)) {
1556 PyErr_SetString(PyExc_ImportError,
1557 "sys.meta_path must be a list of "
1558 "import hooks");
1559 return NULL;
1560 }
1561 Py_INCREF(meta_path); /* zap guard */
1562 npath = PyList_Size(meta_path);
1563 for (i = 0; i < npath; i++) {
1564 PyObject *loader;
1565 PyObject *hook = PyList_GetItem(meta_path, i);
1566 loader = PyObject_CallMethod(hook, "find_module",
1567 "sO", fullname,
1568 path != NULL ?
1569 path : Py_None);
1570 if (loader == NULL) {
1571 Py_DECREF(meta_path);
1572 return NULL; /* true error */
1573 }
1574 if (loader != Py_None) {
1575 /* a loader was found */
1576 *p_loader = loader;
1577 Py_DECREF(meta_path);
1578 return &importhookdescr;
1579 }
1580 Py_DECREF(loader);
1581 }
1582 Py_DECREF(meta_path);
1583 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (find_frozen(fullname) != NULL) {
1586 strcpy(buf, fullname);
1587 return &fd_frozen;
1588 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if (path == NULL) {
1591 if (is_builtin(name)) {
1592 strcpy(buf, name);
1593 return &fd_builtin;
1594 }
Guido van Rossumac279101996-08-22 23:10:58 +00001595#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1597 if (fp != NULL) {
1598 *p_fp = fp;
1599 return fdp;
1600 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001601#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 path = PySys_GetObject("path");
1603 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (path == NULL || !PyList_Check(path)) {
1606 PyErr_SetString(PyExc_ImportError,
1607 "sys.path must be a list of directory names");
1608 return NULL;
1609 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 path_hooks = PySys_GetObject("path_hooks");
1612 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1613 PyErr_SetString(PyExc_ImportError,
1614 "sys.path_hooks must be a list of "
1615 "import hooks");
1616 return NULL;
1617 }
1618 path_importer_cache = PySys_GetObject("path_importer_cache");
1619 if (path_importer_cache == NULL ||
1620 !PyDict_Check(path_importer_cache)) {
1621 PyErr_SetString(PyExc_ImportError,
1622 "sys.path_importer_cache must be a dict");
1623 return NULL;
1624 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 npath = PyList_Size(path);
1627 namelen = strlen(name);
1628 for (i = 0; i < npath; i++) {
1629 PyObject *v = PyList_GetItem(path, i);
1630 PyObject *origv = v;
1631 const char *base;
1632 Py_ssize_t size;
1633 if (!v)
1634 return NULL;
1635 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001636 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (v == NULL)
1638 return NULL;
1639 }
1640 else if (!PyBytes_Check(v))
1641 continue;
1642 else
1643 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 base = PyBytes_AS_STRING(v);
1646 size = PyBytes_GET_SIZE(v);
1647 len = size;
1648 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1649 Py_DECREF(v);
1650 continue; /* Too long */
1651 }
1652 strcpy(buf, base);
1653 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 if (strlen(buf) != len) {
1656 continue; /* v contains '\0' */
1657 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 /* sys.path_hooks import hook */
1660 if (p_loader != NULL) {
1661 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 importer = get_path_importer(path_importer_cache,
1664 path_hooks, origv);
1665 if (importer == NULL) {
1666 return NULL;
1667 }
1668 /* Note: importer is a borrowed reference */
1669 if (importer != Py_None) {
1670 PyObject *loader;
1671 loader = PyObject_CallMethod(importer,
1672 "find_module",
1673 "s", fullname);
1674 if (loader == NULL)
1675 return NULL; /* error */
1676 if (loader != Py_None) {
1677 /* a loader was found */
1678 *p_loader = loader;
1679 return &importhookdescr;
1680 }
1681 Py_DECREF(loader);
1682 continue;
1683 }
1684 }
1685 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001688#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001690#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 )
1692 buf[len++] = SEP;
1693 strcpy(buf+len, name);
1694 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* Check for package import (buf holds a directory name,
1697 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001698#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (stat(buf, &statbuf) == 0 && /* it exists */
1700 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1701 case_ok(buf, len, namelen, name)) { /* case matches */
1702 if (find_init_module(buf)) { /* and has __init__.py */
1703 return &fd_package;
1704 }
1705 else {
1706 char warnstr[MAXPATHLEN+80];
1707 sprintf(warnstr, "Not importing directory "
1708 "'%.*s': missing __init__.py",
1709 MAXPATHLEN, buf);
1710 if (PyErr_WarnEx(PyExc_ImportWarning,
1711 warnstr, 1)) {
1712 return NULL;
1713 }
1714 }
1715 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001716#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001717#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 /* take a snapshot of the module spec for restoration
1719 * after the 8 character DLL hackery
1720 */
1721 saved_buf = strdup(buf);
1722 saved_len = len;
1723 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001724#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001726#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* OS/2 limits DLLs to 8 character names (w/o
1728 extension)
1729 * so if the name is longer than that and its a
1730 * dynamically loaded module we're going to try,
1731 * truncate the name before trying
1732 */
1733 if (strlen(subname) > 8) {
1734 /* is this an attempt to load a C extension? */
1735 const struct filedescr *scan;
1736 scan = _PyImport_DynLoadFiletab;
1737 while (scan->suffix != NULL) {
1738 if (!strcmp(scan->suffix, fdp->suffix))
1739 break;
1740 else
1741 scan++;
1742 }
1743 if (scan->suffix != NULL) {
1744 /* yes, so truncate the name */
1745 namelen = 8;
1746 len -= strlen(subname) - namelen;
1747 buf[len] = '\0';
1748 }
1749 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001750#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 strcpy(buf+len, fdp->suffix);
1752 if (Py_VerboseFlag > 1)
1753 PySys_WriteStderr("# trying %s\n", buf);
1754 filemode = fdp->mode;
1755 if (filemode[0] == 'U')
1756 filemode = "r" PY_STDIOTEXTMODE;
1757 fp = fopen(buf, filemode);
1758 if (fp != NULL) {
1759 if (case_ok(buf, len, namelen, name))
1760 break;
1761 else { /* continue search */
1762 fclose(fp);
1763 fp = NULL;
1764 }
1765 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001766#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 /* restore the saved snapshot */
1768 strcpy(buf, saved_buf);
1769 len = saved_len;
1770 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001771#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001773#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* don't need/want the module name snapshot anymore */
1775 if (saved_buf)
1776 {
1777 free(saved_buf);
1778 saved_buf = NULL;
1779 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001780#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (fp != NULL)
1782 break;
1783 }
1784 if (fp == NULL) {
1785 PyErr_Format(PyExc_ImportError,
1786 "No module named %.200s", name);
1787 return NULL;
1788 }
1789 *p_fp = fp;
1790 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001791}
1792
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001793/* Helpers for main.c
1794 * Find the source file corresponding to a named module
1795 */
1796struct filedescr *
1797_PyImport_FindModule(const char *name, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 size_t buflen, FILE **p_fp, PyObject **p_loader)
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 return find_module((char *) name, (char *) name, path,
1801 buf, buflen, p_fp, p_loader);
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001802}
1803
1804PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001807}
1808
Martin v. Löwis18e16552006-02-15 17:27:45 +00001809/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001810 * The arguments here are tricky, best shown by example:
1811 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1812 * ^ ^ ^ ^
1813 * |--------------------- buf ---------------------|
1814 * |------------------- len ------------------|
1815 * |------ name -------|
1816 * |----- namelen -----|
1817 * buf is the full path, but len only counts up to (& exclusive of) the
1818 * extension. name is the module name, also exclusive of extension.
1819 *
1820 * We've already done a successful stat() or fopen() on buf, so know that
1821 * there's some match, possibly case-insensitive.
1822 *
Tim Peters50d8d372001-02-28 05:34:27 +00001823 * case_ok() is to return 1 if there's a case-sensitive match for
1824 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1825 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001826 *
Tim Peters50d8d372001-02-28 05:34:27 +00001827 * case_ok() is used to implement case-sensitive import semantics even
1828 * on platforms with case-insensitive filesystems. It's trivial to implement
1829 * for case-sensitive filesystems. It's pretty much a cross-platform
1830 * nightmare for systems with case-insensitive filesystems.
1831 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001832
Tim Peters50d8d372001-02-28 05:34:27 +00001833/* First we may need a pile of platform-specific header files; the sequence
1834 * of #if's here should match the sequence in the body of case_ok().
1835 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001836#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001837#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001838
Tim Peters50d8d372001-02-28 05:34:27 +00001839#elif defined(DJGPP)
1840#include <dir.h>
1841
Jason Tishler7961aa62005-05-20 00:56:54 +00001842#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001843#include <sys/types.h>
1844#include <dirent.h>
1845
Andrew MacIntyred9400542002-02-26 11:41:34 +00001846#elif defined(PYOS_OS2)
1847#define INCL_DOS
1848#define INCL_DOSERRORS
1849#define INCL_NOPMAPI
1850#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001851#endif
1852
Guido van Rossum0980bd91998-02-13 17:18:36 +00001853static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001854case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001855{
Tim Peters50d8d372001-02-28 05:34:27 +00001856/* Pick a platform-specific implementation; the sequence of #if's here should
1857 * match the sequence just above.
1858 */
1859
Jason Tishler7961aa62005-05-20 00:56:54 +00001860/* MS_WINDOWS */
1861#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 WIN32_FIND_DATA data;
1863 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (Py_GETENV("PYTHONCASEOK") != NULL)
1866 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 h = FindFirstFile(buf, &data);
1869 if (h == INVALID_HANDLE_VALUE) {
1870 PyErr_Format(PyExc_NameError,
1871 "Can't find file for module %.100s\n(filename %.300s)",
1872 name, buf);
1873 return 0;
1874 }
1875 FindClose(h);
1876 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001877
1878/* DJGPP */
1879#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 struct ffblk ffblk;
1881 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (Py_GETENV("PYTHONCASEOK") != NULL)
1884 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1887 if (done) {
1888 PyErr_Format(PyExc_NameError,
1889 "Can't find file for module %.100s\n(filename %.300s)",
1890 name, buf);
1891 return 0;
1892 }
1893 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001894
Jason Tishler7961aa62005-05-20 00:56:54 +00001895/* new-fangled macintosh (macosx) or Cygwin */
1896#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 DIR *dirp;
1898 struct dirent *dp;
1899 char dirname[MAXPATHLEN + 1];
1900 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 if (Py_GETENV("PYTHONCASEOK") != NULL)
1903 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Copy the dir component into dirname; substitute "." if empty */
1906 if (dirlen <= 0) {
1907 dirname[0] = '.';
1908 dirname[1] = '\0';
1909 }
1910 else {
1911 assert(dirlen <= MAXPATHLEN);
1912 memcpy(dirname, buf, dirlen);
1913 dirname[dirlen] = '\0';
1914 }
1915 /* Open the directory and search the entries for an exact match. */
1916 dirp = opendir(dirname);
1917 if (dirp) {
1918 char *nameWithExt = buf + len - namelen;
1919 while ((dp = readdir(dirp)) != NULL) {
1920 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001921#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001923#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001925#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 if (thislen >= namelen &&
1927 strcmp(dp->d_name, nameWithExt) == 0) {
1928 (void)closedir(dirp);
1929 return 1; /* Found */
1930 }
1931 }
1932 (void)closedir(dirp);
1933 }
1934 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001935
Andrew MacIntyred9400542002-02-26 11:41:34 +00001936/* OS/2 */
1937#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 HDIR hdir = 1;
1939 ULONG srchcnt = 1;
1940 FILEFINDBUF3 ffbuf;
1941 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (Py_GETENV("PYTHONCASEOK") != NULL)
1944 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 rc = DosFindFirst(buf,
1947 &hdir,
1948 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1949 &ffbuf, sizeof(ffbuf),
1950 &srchcnt,
1951 FIL_STANDARD);
1952 if (rc != NO_ERROR)
1953 return 0;
1954 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001955
Tim Peters50d8d372001-02-28 05:34:27 +00001956/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1957#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001959
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001960#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001961}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001962
Guido van Rossum0980bd91998-02-13 17:18:36 +00001963
Guido van Rossum197346f1997-10-31 18:38:52 +00001964#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001965
1966/* Call _wstat() on Windows, or stat() otherwise. Only fill st_mode
1967 attribute on Windows. Return 0 on success, -1 on stat error or (if
1968 PyErr_Occurred()) unicode error. */
1969
1970int
1971_Py_stat(PyObject *unicode, struct stat *statbuf)
1972{
1973#ifdef MS_WINDOWS
1974 wchar_t path[MAXPATHLEN+1];
1975 Py_ssize_t len;
1976 int err;
1977 struct _stat wstatbuf;
1978
Victor Stinner8a79dcc2010-08-14 16:59:08 +00001979 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
Victor Stinner4f4402c2010-08-14 14:50:26 +00001980 if (len == -1)
1981 return -1;
Victor Stinner8a79dcc2010-08-14 16:59:08 +00001982 path[len] = L'\0';
1983
Victor Stinner4f4402c2010-08-14 14:50:26 +00001984 err = _wstat(path, &wstatbuf);
1985 if (!err)
1986 statbuf->st_mode = wstatbuf.st_mode;
1987 return err;
1988#else
1989 int ret;
1990 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
1991 if (bytes == NULL)
1992 return -1;
1993 ret = stat(PyBytes_AS_STRING(bytes), statbuf);
1994 Py_DECREF(bytes);
1995 return ret;
1996#endif
1997}
1998
Guido van Rossum197346f1997-10-31 18:38:52 +00001999/* Helper to look for __init__.py or __init__.py[co] in potential package */
2000static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002001find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 const size_t save_len = strlen(buf);
2004 size_t i = save_len;
2005 char *pname; /* pointer to start of __init__ */
2006 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008/* For calling case_ok(buf, len, namelen, name):
2009 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2010 * ^ ^ ^ ^
2011 * |--------------------- buf ---------------------|
2012 * |------------------- len ------------------|
2013 * |------ name -------|
2014 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002015 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (save_len + 13 >= MAXPATHLEN)
2017 return 0;
2018 buf[i++] = SEP;
2019 pname = buf + i;
2020 strcpy(pname, "__init__.py");
2021 if (stat(buf, &statbuf) == 0) {
2022 if (case_ok(buf,
2023 save_len + 9, /* len("/__init__") */
2024 8, /* len("__init__") */
2025 pname)) {
2026 buf[save_len] = '\0';
2027 return 1;
2028 }
2029 }
2030 i += strlen(pname);
2031 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2032 if (stat(buf, &statbuf) == 0) {
2033 if (case_ok(buf,
2034 save_len + 9, /* len("/__init__") */
2035 8, /* len("__init__") */
2036 pname)) {
2037 buf[save_len] = '\0';
2038 return 1;
2039 }
2040 }
2041 buf[save_len] = '\0';
2042 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002043}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002044
Guido van Rossum197346f1997-10-31 18:38:52 +00002045#endif /* HAVE_STAT */
2046
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002047
Tim Petersdbd9ba62000-07-09 03:09:57 +00002048static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002049
Victor Stinner44c6c152010-08-09 00:59:10 +00002050static PyObject*
2051load_builtin(char *name, char *pathname, int type)
2052{
2053 PyObject *m, *modules;
2054 int err;
2055
2056 if (pathname != NULL && pathname[0] != '\0')
2057 name = pathname;
2058
2059 if (type == C_BUILTIN)
2060 err = init_builtin(name);
2061 else
2062 err = PyImport_ImportFrozenModule(name);
2063 if (err < 0)
2064 return NULL;
2065 if (err == 0) {
2066 PyErr_Format(PyExc_ImportError,
2067 "Purported %s module %.200s not found",
2068 type == C_BUILTIN ?
2069 "builtin" : "frozen",
2070 name);
2071 return NULL;
2072 }
2073
2074 modules = PyImport_GetModuleDict();
2075 m = PyDict_GetItemString(modules, name);
2076 if (m == NULL) {
2077 PyErr_Format(
2078 PyExc_ImportError,
2079 "%s module %.200s not properly initialized",
2080 type == C_BUILTIN ?
2081 "builtin" : "frozen",
2082 name);
2083 return NULL;
2084 }
2085 Py_INCREF(m);
2086 return m;
2087}
2088
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002089/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002090 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002091
Guido van Rossum79f25d91997-04-29 20:08:16 +00002092static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002093load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* First check that there's an open file (if we need one) */
2098 switch (type) {
2099 case PY_SOURCE:
2100 case PY_COMPILED:
2101 if (fp == NULL) {
2102 PyErr_Format(PyExc_ValueError,
2103 "file object required for import (type code %d)",
2104 type);
2105 return NULL;
2106 }
2107 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 case PY_SOURCE:
2112 m = load_source_module(name, pathname, fp);
2113 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 case PY_COMPILED:
2116 m = load_compiled_module(name, pathname, fp);
2117 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002118
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002119#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 case C_EXTENSION:
2121 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2122 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002123#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 case PKG_DIRECTORY:
2126 m = load_package(name, pathname);
2127 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 case C_BUILTIN:
2130 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002131 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 case IMP_HOOK: {
2135 if (loader == NULL) {
2136 PyErr_SetString(PyExc_ImportError,
2137 "import hook without loader");
2138 return NULL;
2139 }
2140 m = PyObject_CallMethod(loader, "load_module", "s", name);
2141 break;
2142 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 default:
2145 PyErr_Format(PyExc_ImportError,
2146 "Don't know how to import %.200s (type code %d)",
2147 name, type);
2148 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002153}
2154
2155
2156/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002157 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002158 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002159
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002160static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (_PyImport_FindExtension(name, name) != NULL)
2166 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 for (p = PyImport_Inittab; p->name != NULL; p++) {
2169 PyObject *mod;
2170 if (strcmp(name, p->name) == 0) {
2171 if (p->initfunc == NULL) {
2172 PyErr_Format(PyExc_ImportError,
2173 "Cannot re-init internal module %.200s",
2174 name);
2175 return -1;
2176 }
2177 if (Py_VerboseFlag)
2178 PySys_WriteStderr("import %s # builtin\n", name);
2179 mod = (*p->initfunc)();
2180 if (mod == 0)
2181 return -1;
2182 if (_PyImport_FixupExtension(mod, name, name) < 0)
2183 return -1;
2184 /* FixupExtension has put the module into sys.modules,
2185 so we can release our own reference. */
2186 Py_DECREF(mod);
2187 return 1;
2188 }
2189 }
2190 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002191}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002192
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002193
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002194/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002195
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002196static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002197find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (!name)
2202 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 for (p = PyImport_FrozenModules; ; p++) {
2205 if (p->name == NULL)
2206 return NULL;
2207 if (strcmp(p->name, name) == 0)
2208 break;
2209 }
2210 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002211}
2212
Guido van Rossum79f25d91997-04-29 20:08:16 +00002213static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002214get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 struct _frozen *p = find_frozen(name);
2217 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if (p == NULL) {
2220 PyErr_Format(PyExc_ImportError,
2221 "No such frozen object named %.200s",
2222 name);
2223 return NULL;
2224 }
2225 if (p->code == NULL) {
2226 PyErr_Format(PyExc_ImportError,
2227 "Excluded frozen object named %.200s",
2228 name);
2229 return NULL;
2230 }
2231 size = p->size;
2232 if (size < 0)
2233 size = -size;
2234 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002235}
2236
Brett Cannon8d110132009-03-15 02:20:16 +00002237static PyObject *
2238is_frozen_package(char *name)
2239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 struct _frozen *p = find_frozen(name);
2241 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (p == NULL) {
2244 PyErr_Format(PyExc_ImportError,
2245 "No such frozen object named %.200s",
2246 name);
2247 return NULL;
2248 }
Brett Cannon8d110132009-03-15 02:20:16 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (size < 0)
2253 Py_RETURN_TRUE;
2254 else
2255 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002256}
2257
2258
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002259/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002260 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002261 an exception set if the initialization failed.
2262 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002263
2264int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002265PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 struct _frozen *p = find_frozen(name);
2268 PyObject *co;
2269 PyObject *m;
2270 int ispackage;
2271 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (p == NULL)
2274 return 0;
2275 if (p->code == NULL) {
2276 PyErr_Format(PyExc_ImportError,
2277 "Excluded frozen object named %.200s",
2278 name);
2279 return -1;
2280 }
2281 size = p->size;
2282 ispackage = (size < 0);
2283 if (ispackage)
2284 size = -size;
2285 if (Py_VerboseFlag)
2286 PySys_WriteStderr("import %s # frozen%s\n",
2287 name, ispackage ? " package" : "");
2288 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2289 if (co == NULL)
2290 return -1;
2291 if (!PyCode_Check(co)) {
2292 PyErr_Format(PyExc_TypeError,
2293 "frozen object %.200s is not a code object",
2294 name);
2295 goto err_return;
2296 }
2297 if (ispackage) {
2298 /* Set __path__ to the package name */
2299 PyObject *d, *s, *l;
2300 int err;
2301 m = PyImport_AddModule(name);
2302 if (m == NULL)
2303 goto err_return;
2304 d = PyModule_GetDict(m);
2305 s = PyUnicode_InternFromString(name);
2306 if (s == NULL)
2307 goto err_return;
2308 l = PyList_New(1);
2309 if (l == NULL) {
2310 Py_DECREF(s);
2311 goto err_return;
2312 }
2313 PyList_SET_ITEM(l, 0, s);
2314 err = PyDict_SetItemString(d, "__path__", l);
2315 Py_DECREF(l);
2316 if (err != 0)
2317 goto err_return;
2318 }
2319 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2320 if (m == NULL)
2321 goto err_return;
2322 Py_DECREF(co);
2323 Py_DECREF(m);
2324 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002325err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 Py_DECREF(co);
2327 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002328}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002329
2330
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002331/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002332 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002333
Guido van Rossum79f25d91997-04-29 20:08:16 +00002334PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002335PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 PyObject *pname;
2338 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 pname = PyUnicode_FromString(name);
2341 if (pname == NULL)
2342 return NULL;
2343 result = PyImport_Import(pname);
2344 Py_DECREF(pname);
2345 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002346}
2347
Christian Heimes072c0f12008-01-03 23:01:04 +00002348/* Import a module without blocking
2349 *
2350 * At first it tries to fetch the module from sys.modules. If the module was
2351 * never loaded before it loads it with PyImport_ImportModule() unless another
2352 * thread holds the import lock. In the latter case the function raises an
2353 * ImportError instead of blocking.
2354 *
2355 * Returns the module object with incremented ref count.
2356 */
2357PyObject *
2358PyImport_ImportModuleNoBlock(const char *name)
2359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 PyObject *result;
2361 PyObject *modules;
2362 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* Try to get the module from sys.modules[name] */
2365 modules = PyImport_GetModuleDict();
2366 if (modules == NULL)
2367 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 result = PyDict_GetItemString(modules, name);
2370 if (result != NULL) {
2371 Py_INCREF(result);
2372 return result;
2373 }
2374 else {
2375 PyErr_Clear();
2376 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002377#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* check the import lock
2379 * me might be -1 but I ignore the error here, the lock function
2380 * takes care of the problem */
2381 me = PyThread_get_thread_ident();
2382 if (import_lock_thread == -1 || import_lock_thread == me) {
2383 /* no thread or me is holding the lock */
2384 return PyImport_ImportModule(name);
2385 }
2386 else {
2387 PyErr_Format(PyExc_ImportError,
2388 "Failed to import %.200s because the import lock"
2389 "is held by another thread.",
2390 name);
2391 return NULL;
2392 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002393#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002395#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002396}
2397
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002398/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002399static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002401static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002403static int mark_miss(char *name);
2404static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002406static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002407
2408/* The Magnum Opus of dotted-name import :-) */
2409
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002410static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002411import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 char buf[MAXPATHLEN+1];
2415 Py_ssize_t buflen = 0;
2416 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002419#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002421#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 ) {
2423 PyErr_SetString(PyExc_ImportError,
2424 "Import by filename is not supported.");
2425 return NULL;
2426 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 parent = get_parent(globals, buf, &buflen, level);
2429 if (parent == NULL)
2430 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002431
Benjamin Peterson556d8002010-06-27 22:37:28 +00002432 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2433 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (head == NULL)
2435 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 tail = head;
2438 Py_INCREF(tail);
2439 while (name) {
2440 next = load_next(tail, tail, &name, buf, &buflen);
2441 Py_DECREF(tail);
2442 if (next == NULL) {
2443 Py_DECREF(head);
2444 return NULL;
2445 }
2446 tail = next;
2447 }
2448 if (tail == Py_None) {
2449 /* If tail is Py_None, both get_parent and load_next found
2450 an empty module name: someone called __import__("") or
2451 doctored faulty bytecode */
2452 Py_DECREF(tail);
2453 Py_DECREF(head);
2454 PyErr_SetString(PyExc_ValueError,
2455 "Empty module name");
2456 return NULL;
2457 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 if (fromlist != NULL) {
2460 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2461 fromlist = NULL;
2462 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (fromlist == NULL) {
2465 Py_DECREF(tail);
2466 return head;
2467 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 Py_DECREF(head);
2470 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2471 Py_DECREF(tail);
2472 return NULL;
2473 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002476}
2477
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002478PyObject *
2479PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyObject *result;
2483 _PyImport_AcquireLock();
2484 result = import_module_level(name, globals, locals, fromlist, level);
2485 if (_PyImport_ReleaseLock() < 0) {
2486 Py_XDECREF(result);
2487 PyErr_SetString(PyExc_RuntimeError,
2488 "not holding the import lock");
2489 return NULL;
2490 }
2491 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002492}
2493
Fred Drake87590902004-05-28 20:21:36 +00002494/* Return the package that an import is being performed in. If globals comes
2495 from the module foo.bar.bat (not itself a package), this returns the
2496 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002497 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002498
2499 The *name* of the returned package is returned in buf, with the length of
2500 the name in *p_buflen.
2501
2502 If globals doesn't come from a package or a module in a package, or a
2503 corresponding entry is not found in sys.modules, Py_None is returned.
2504*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002505static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002506get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 static PyObject *namestr = NULL;
2509 static PyObject *pathstr = NULL;
2510 static PyObject *pkgstr = NULL;
2511 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2512 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (globals == NULL || !PyDict_Check(globals) || !level)
2515 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (namestr == NULL) {
2518 namestr = PyUnicode_InternFromString("__name__");
2519 if (namestr == NULL)
2520 return NULL;
2521 }
2522 if (pathstr == NULL) {
2523 pathstr = PyUnicode_InternFromString("__path__");
2524 if (pathstr == NULL)
2525 return NULL;
2526 }
2527 if (pkgstr == NULL) {
2528 pkgstr = PyUnicode_InternFromString("__package__");
2529 if (pkgstr == NULL)
2530 return NULL;
2531 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 *buf = '\0';
2534 *p_buflen = 0;
2535 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if ((pkgname != NULL) && (pkgname != Py_None)) {
2538 /* __package__ is set, so use it */
2539 char *pkgname_str;
2540 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 if (!PyUnicode_Check(pkgname)) {
2543 PyErr_SetString(PyExc_ValueError,
2544 "__package__ set to non-string");
2545 return NULL;
2546 }
2547 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2548 if (len == 0) {
2549 if (level > 0) {
2550 PyErr_SetString(PyExc_ValueError,
2551 "Attempted relative import in non-package");
2552 return NULL;
2553 }
2554 return Py_None;
2555 }
2556 if (len > MAXPATHLEN) {
2557 PyErr_SetString(PyExc_ValueError,
2558 "Package name too long");
2559 return NULL;
2560 }
2561 strcpy(buf, pkgname_str);
2562 } else {
2563 /* __package__ not set, so figure it out and set it */
2564 modname = PyDict_GetItem(globals, namestr);
2565 if (modname == NULL || !PyUnicode_Check(modname))
2566 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 modpath = PyDict_GetItem(globals, pathstr);
2569 if (modpath != NULL) {
2570 /* __path__ is set, so modname is already the package name */
2571 char *modname_str;
2572 Py_ssize_t len;
2573 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2576 if (len > MAXPATHLEN) {
2577 PyErr_SetString(PyExc_ValueError,
2578 "Module name too long");
2579 return NULL;
2580 }
2581 strcpy(buf, modname_str);
2582 error = PyDict_SetItem(globals, pkgstr, modname);
2583 if (error) {
2584 PyErr_SetString(PyExc_ValueError,
2585 "Could not set __package__");
2586 return NULL;
2587 }
2588 } else {
2589 /* Normal module, so work out the package name if any */
2590 char *start = _PyUnicode_AsString(modname);
2591 char *lastdot = strrchr(start, '.');
2592 size_t len;
2593 int error;
2594 if (lastdot == NULL && level > 0) {
2595 PyErr_SetString(PyExc_ValueError,
2596 "Attempted relative import in non-package");
2597 return NULL;
2598 }
2599 if (lastdot == NULL) {
2600 error = PyDict_SetItem(globals, pkgstr, Py_None);
2601 if (error) {
2602 PyErr_SetString(PyExc_ValueError,
2603 "Could not set __package__");
2604 return NULL;
2605 }
2606 return Py_None;
2607 }
2608 len = lastdot - start;
2609 if (len >= MAXPATHLEN) {
2610 PyErr_SetString(PyExc_ValueError,
2611 "Module name too long");
2612 return NULL;
2613 }
2614 strncpy(buf, start, len);
2615 buf[len] = '\0';
2616 pkgname = PyUnicode_FromString(buf);
2617 if (pkgname == NULL) {
2618 return NULL;
2619 }
2620 error = PyDict_SetItem(globals, pkgstr, pkgname);
2621 Py_DECREF(pkgname);
2622 if (error) {
2623 PyErr_SetString(PyExc_ValueError,
2624 "Could not set __package__");
2625 return NULL;
2626 }
2627 }
2628 }
2629 while (--level > 0) {
2630 char *dot = strrchr(buf, '.');
2631 if (dot == NULL) {
2632 PyErr_SetString(PyExc_ValueError,
2633 "Attempted relative import beyond "
2634 "toplevel package");
2635 return NULL;
2636 }
2637 *dot = '\0';
2638 }
2639 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 modules = PyImport_GetModuleDict();
2642 parent = PyDict_GetItemString(modules, buf);
2643 if (parent == NULL) {
2644 if (orig_level < 1) {
2645 PyObject *err_msg = PyBytes_FromFormat(
2646 "Parent module '%.200s' not found "
2647 "while handling absolute import", buf);
2648 if (err_msg == NULL) {
2649 return NULL;
2650 }
2651 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2652 PyBytes_AsString(err_msg), 1)) {
2653 *buf = '\0';
2654 *p_buflen = 0;
2655 parent = Py_None;
2656 }
2657 Py_DECREF(err_msg);
2658 } else {
2659 PyErr_Format(PyExc_SystemError,
2660 "Parent module '%.200s' not loaded, "
2661 "cannot perform relative import", buf);
2662 }
2663 }
2664 return parent;
2665 /* We expect, but can't guarantee, if parent != None, that:
2666 - parent.__name__ == buf
2667 - parent.__dict__ is globals
2668 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002669}
2670
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002671/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002672static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002673load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 char *name = *p_name;
2677 char *dot = strchr(name, '.');
2678 size_t len;
2679 char *p;
2680 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 if (strlen(name) == 0) {
2683 /* completely empty module name should only happen in
2684 'from . import' (or '__import__("")')*/
2685 Py_INCREF(mod);
2686 *p_name = NULL;
2687 return mod;
2688 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 if (dot == NULL) {
2691 *p_name = NULL;
2692 len = strlen(name);
2693 }
2694 else {
2695 *p_name = dot+1;
2696 len = dot-name;
2697 }
2698 if (len == 0) {
2699 PyErr_SetString(PyExc_ValueError,
2700 "Empty module name");
2701 return NULL;
2702 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 p = buf + *p_buflen;
2705 if (p != buf)
2706 *p++ = '.';
2707 if (p+len-buf >= MAXPATHLEN) {
2708 PyErr_SetString(PyExc_ValueError,
2709 "Module name too long");
2710 return NULL;
2711 }
2712 strncpy(p, name, len);
2713 p[len] = '\0';
2714 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 result = import_submodule(mod, p, buf);
2717 if (result == Py_None && altmod != mod) {
2718 Py_DECREF(result);
2719 /* Here, altmod must be None and mod must not be None */
2720 result = import_submodule(altmod, p, p);
2721 if (result != NULL && result != Py_None) {
2722 if (mark_miss(buf) != 0) {
2723 Py_DECREF(result);
2724 return NULL;
2725 }
2726 strncpy(buf, name, len);
2727 buf[len] = '\0';
2728 *p_buflen = len;
2729 }
2730 }
2731 if (result == NULL)
2732 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 if (result == Py_None) {
2735 Py_DECREF(result);
2736 PyErr_Format(PyExc_ImportError,
2737 "No module named %.200s", name);
2738 return NULL;
2739 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002742}
2743
2744static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002745mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 PyObject *modules = PyImport_GetModuleDict();
2748 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002749}
2750
2751static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002752ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 if (!PyObject_HasAttrString(mod, "__path__"))
2758 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 for (i = 0; ; i++) {
2761 PyObject *item = PySequence_GetItem(fromlist, i);
2762 int hasit;
2763 if (item == NULL) {
2764 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2765 PyErr_Clear();
2766 return 1;
2767 }
2768 return 0;
2769 }
2770 if (!PyUnicode_Check(item)) {
2771 PyErr_SetString(PyExc_TypeError,
2772 "Item in ``from list'' not a string");
2773 Py_DECREF(item);
2774 return 0;
2775 }
2776 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2777 PyObject *all;
2778 Py_DECREF(item);
2779 /* See if the package defines __all__ */
2780 if (recursive)
2781 continue; /* Avoid endless recursion */
2782 all = PyObject_GetAttrString(mod, "__all__");
2783 if (all == NULL)
2784 PyErr_Clear();
2785 else {
2786 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2787 Py_DECREF(all);
2788 if (!ret)
2789 return 0;
2790 }
2791 continue;
2792 }
2793 hasit = PyObject_HasAttr(mod, item);
2794 if (!hasit) {
2795 PyObject *item8;
2796 char *subname;
2797 PyObject *submod;
2798 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002799 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 if (!item8) {
2801 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2802 return 0;
2803 }
2804 subname = PyBytes_AS_STRING(item8);
2805 if (buflen + strlen(subname) >= MAXPATHLEN) {
2806 PyErr_SetString(PyExc_ValueError,
2807 "Module name too long");
2808 Py_DECREF(item);
2809 return 0;
2810 }
2811 p = buf + buflen;
2812 *p++ = '.';
2813 strcpy(p, subname);
2814 submod = import_submodule(mod, subname, buf);
2815 Py_DECREF(item8);
2816 Py_XDECREF(submod);
2817 if (submod == NULL) {
2818 Py_DECREF(item);
2819 return 0;
2820 }
2821 }
2822 Py_DECREF(item);
2823 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002826}
2827
Neil Schemenauer00b09662003-06-16 21:03:07 +00002828static int
2829add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 if (mod == Py_None)
2833 return 1;
2834 /* Irrespective of the success of this load, make a
2835 reference to it in the parent package module. A copy gets
2836 saved in the modules dictionary under the full name, so get a
2837 reference from there, if need be. (The exception is when the
2838 load failed with a SyntaxError -- then there's no trace in
2839 sys.modules. In that case, of course, do nothing extra.) */
2840 if (submod == NULL) {
2841 submod = PyDict_GetItemString(modules, fullname);
2842 if (submod == NULL)
2843 return 1;
2844 }
2845 if (PyModule_Check(mod)) {
2846 /* We can't use setattr here since it can give a
2847 * spurious warning if the submodule name shadows a
2848 * builtin name */
2849 PyObject *dict = PyModule_GetDict(mod);
2850 if (!dict)
2851 return 0;
2852 if (PyDict_SetItemString(dict, subname, submod) < 0)
2853 return 0;
2854 }
2855 else {
2856 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2857 return 0;
2858 }
2859 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002860}
2861
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002862static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002863import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 PyObject *modules = PyImport_GetModuleDict();
2866 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 /* Require:
2869 if mod == None: subname == fullname
2870 else: mod.__name__ + "." + subname == fullname
2871 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2874 Py_INCREF(m);
2875 }
2876 else {
2877 PyObject *path, *loader = NULL;
2878 char buf[MAXPATHLEN+1];
2879 struct filedescr *fdp;
2880 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 if (mod == Py_None)
2883 path = NULL;
2884 else {
2885 path = PyObject_GetAttrString(mod, "__path__");
2886 if (path == NULL) {
2887 PyErr_Clear();
2888 Py_INCREF(Py_None);
2889 return Py_None;
2890 }
2891 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 buf[0] = '\0';
2894 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2895 &fp, &loader);
2896 Py_XDECREF(path);
2897 if (fdp == NULL) {
2898 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2899 return NULL;
2900 PyErr_Clear();
2901 Py_INCREF(Py_None);
2902 return Py_None;
2903 }
2904 m = load_module(fullname, fp, buf, fdp->type, loader);
2905 Py_XDECREF(loader);
2906 if (fp)
2907 fclose(fp);
2908 if (!add_submodule(mod, m, fullname, subname, modules)) {
2909 Py_XDECREF(m);
2910 m = NULL;
2911 }
2912 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002915}
2916
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002917
2918/* Re-import a module of any kind and return its module object, WITH
2919 INCREMENTED REFERENCE COUNT */
2920
Guido van Rossum79f25d91997-04-29 20:08:16 +00002921PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002922PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 PyInterpreterState *interp = PyThreadState_Get()->interp;
2925 PyObject *modules_reloading = interp->modules_reloading;
2926 PyObject *modules = PyImport_GetModuleDict();
2927 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2928 char *name, *subname;
2929 char buf[MAXPATHLEN+1];
2930 struct filedescr *fdp;
2931 FILE *fp = NULL;
2932 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 if (modules_reloading == NULL) {
2935 Py_FatalError("PyImport_ReloadModule: "
2936 "no modules_reloading dictionary!");
2937 return NULL;
2938 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 if (m == NULL || !PyModule_Check(m)) {
2941 PyErr_SetString(PyExc_TypeError,
2942 "reload() argument must be module");
2943 return NULL;
2944 }
2945 name = (char*)PyModule_GetName(m);
2946 if (name == NULL)
2947 return NULL;
2948 if (m != PyDict_GetItemString(modules, name)) {
2949 PyErr_Format(PyExc_ImportError,
2950 "reload(): module %.200s not in sys.modules",
2951 name);
2952 return NULL;
2953 }
2954 existing_m = PyDict_GetItemString(modules_reloading, name);
2955 if (existing_m != NULL) {
2956 /* Due to a recursive reload, this module is already
2957 being reloaded. */
2958 Py_INCREF(existing_m);
2959 return existing_m;
2960 }
2961 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2962 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 subname = strrchr(name, '.');
2965 if (subname == NULL)
2966 subname = name;
2967 else {
2968 PyObject *parentname, *parent;
2969 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2970 if (parentname == NULL) {
2971 imp_modules_reloading_clear();
2972 return NULL;
2973 }
2974 parent = PyDict_GetItem(modules, parentname);
2975 if (parent == NULL) {
2976 PyErr_Format(PyExc_ImportError,
2977 "reload(): parent %U not in sys.modules",
2978 parentname);
2979 Py_DECREF(parentname);
2980 imp_modules_reloading_clear();
2981 return NULL;
2982 }
2983 Py_DECREF(parentname);
2984 subname++;
2985 path = PyObject_GetAttrString(parent, "__path__");
2986 if (path == NULL)
2987 PyErr_Clear();
2988 }
2989 buf[0] = '\0';
2990 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2991 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 if (fdp == NULL) {
2994 Py_XDECREF(loader);
2995 imp_modules_reloading_clear();
2996 return NULL;
2997 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 newm = load_module(name, fp, buf, fdp->type, loader);
3000 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 if (fp)
3003 fclose(fp);
3004 if (newm == NULL) {
3005 /* load_module probably removed name from modules because of
3006 * the error. Put back the original module object. We're
3007 * going to return NULL in this case regardless of whether
3008 * replacing name succeeds, so the return value is ignored.
3009 */
3010 PyDict_SetItemString(modules, name, m);
3011 }
3012 imp_modules_reloading_clear();
3013 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003014}
3015
3016
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003017/* Higher-level import emulator which emulates the "import" statement
3018 more accurately -- it invokes the __import__() function from the
3019 builtins of the current globals. This means that the import is
3020 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00003021 environment, e.g. by "rexec".
3022 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003023 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003024 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003025
3026PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003027PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 static PyObject *silly_list = NULL;
3030 static PyObject *builtins_str = NULL;
3031 static PyObject *import_str = NULL;
3032 PyObject *globals = NULL;
3033 PyObject *import = NULL;
3034 PyObject *builtins = NULL;
3035 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* Initialize constant string objects */
3038 if (silly_list == NULL) {
3039 import_str = PyUnicode_InternFromString("__import__");
3040 if (import_str == NULL)
3041 return NULL;
3042 builtins_str = PyUnicode_InternFromString("__builtins__");
3043 if (builtins_str == NULL)
3044 return NULL;
3045 silly_list = Py_BuildValue("[s]", "__doc__");
3046 if (silly_list == NULL)
3047 return NULL;
3048 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 /* Get the builtins from current globals */
3051 globals = PyEval_GetGlobals();
3052 if (globals != NULL) {
3053 Py_INCREF(globals);
3054 builtins = PyObject_GetItem(globals, builtins_str);
3055 if (builtins == NULL)
3056 goto err;
3057 }
3058 else {
3059 /* No globals -- use standard builtins, and fake globals */
3060 builtins = PyImport_ImportModuleLevel("builtins",
3061 NULL, NULL, NULL, 0);
3062 if (builtins == NULL)
3063 return NULL;
3064 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3065 if (globals == NULL)
3066 goto err;
3067 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 /* Get the __import__ function from the builtins */
3070 if (PyDict_Check(builtins)) {
3071 import = PyObject_GetItem(builtins, import_str);
3072 if (import == NULL)
3073 PyErr_SetObject(PyExc_KeyError, import_str);
3074 }
3075 else
3076 import = PyObject_GetAttr(builtins, import_str);
3077 if (import == NULL)
3078 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 /* Call the __import__ function with the proper argument list
3081 * Always use absolute import here. */
3082 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3083 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003084
3085 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 Py_XDECREF(globals);
3087 Py_XDECREF(builtins);
3088 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003091}
3092
3093
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003094/* Module 'imp' provides Python access to the primitives used for
3095 importing modules.
3096*/
3097
Guido van Rossum79f25d91997-04-29 20:08:16 +00003098static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003099imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003101 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 buf[0] = (char) ((magic >> 0) & 0xff);
3104 buf[1] = (char) ((magic >> 8) & 0xff);
3105 buf[2] = (char) ((magic >> 16) & 0xff);
3106 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 return PyBytes_FromStringAndSize(buf, 4);
3109};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003110
3111static PyObject *
3112imp_get_magic(PyObject *self, PyObject *noargs)
3113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003115}
3116
3117static PyObject *
3118imp_get_tag(PyObject *self, PyObject *noargs)
3119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003121}
3122
Guido van Rossum79f25d91997-04-29 20:08:16 +00003123static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003124imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 PyObject *list;
3127 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 list = PyList_New(0);
3130 if (list == NULL)
3131 return NULL;
3132 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3133 PyObject *item = Py_BuildValue("ssi",
3134 fdp->suffix, fdp->mode, fdp->type);
3135 if (item == NULL) {
3136 Py_DECREF(list);
3137 return NULL;
3138 }
3139 if (PyList_Append(list, item) < 0) {
3140 Py_DECREF(list);
3141 Py_DECREF(item);
3142 return NULL;
3143 }
3144 Py_DECREF(item);
3145 }
3146 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003147}
3148
Guido van Rossum79f25d91997-04-29 20:08:16 +00003149static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003150call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 extern int fclose(FILE *);
3153 PyObject *fob, *ret;
3154 PyObject *pathobj;
3155 struct filedescr *fdp;
3156 char pathname[MAXPATHLEN+1];
3157 FILE *fp = NULL;
3158 int fd = -1;
3159 char *found_encoding = NULL;
3160 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 pathname[0] = '\0';
3163 if (path == Py_None)
3164 path = NULL;
3165 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3166 if (fdp == NULL)
3167 return NULL;
3168 if (fp != NULL) {
3169 fd = fileno(fp);
3170 if (fd != -1)
3171 fd = dup(fd);
3172 fclose(fp);
3173 fp = NULL;
3174 }
3175 if (fd != -1) {
3176 if (strchr(fdp->mode, 'b') == NULL) {
3177 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3178 memory. */
3179 found_encoding = PyTokenizer_FindEncoding(fd);
3180 lseek(fd, 0, 0); /* Reset position */
3181 if (found_encoding == NULL && PyErr_Occurred())
3182 return NULL;
3183 encoding = (found_encoding != NULL) ? found_encoding :
3184 (char*)PyUnicode_GetDefaultEncoding();
3185 }
3186 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3187 (char*)encoding, NULL, NULL, 1);
3188 if (fob == NULL) {
3189 close(fd);
3190 PyMem_FREE(found_encoding);
3191 return NULL;
3192 }
3193 }
3194 else {
3195 fob = Py_None;
3196 Py_INCREF(fob);
3197 }
3198 pathobj = PyUnicode_DecodeFSDefault(pathname);
3199 ret = Py_BuildValue("NN(ssi)",
3200 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3201 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003204}
3205
Guido van Rossum79f25d91997-04-29 20:08:16 +00003206static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003207imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 char *name;
3210 PyObject *ret, *path = NULL;
3211 if (!PyArg_ParseTuple(args, "es|O:find_module",
3212 Py_FileSystemDefaultEncoding, &name,
3213 &path))
3214 return NULL;
3215 ret = call_find_module(name, path);
3216 PyMem_Free(name);
3217 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003218}
3219
3220static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003221imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 char *name;
3224 int ret;
3225 PyObject *m;
3226 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3227 return NULL;
3228 ret = init_builtin(name);
3229 if (ret < 0)
3230 return NULL;
3231 if (ret == 0) {
3232 Py_INCREF(Py_None);
3233 return Py_None;
3234 }
3235 m = PyImport_AddModule(name);
3236 Py_XINCREF(m);
3237 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003238}
3239
Guido van Rossum79f25d91997-04-29 20:08:16 +00003240static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003241imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 char *name;
3244 int ret;
3245 PyObject *m;
3246 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3247 return NULL;
3248 ret = PyImport_ImportFrozenModule(name);
3249 if (ret < 0)
3250 return NULL;
3251 if (ret == 0) {
3252 Py_INCREF(Py_None);
3253 return Py_None;
3254 }
3255 m = PyImport_AddModule(name);
3256 Py_XINCREF(m);
3257 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003258}
3259
Guido van Rossum79f25d91997-04-29 20:08:16 +00003260static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003261imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3266 return NULL;
3267 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003268}
3269
Guido van Rossum79f25d91997-04-29 20:08:16 +00003270static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003271imp_is_frozen_package(PyObject *self, PyObject *args)
3272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3276 return NULL;
3277 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003278}
3279
3280static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003281imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 char *name;
3284 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3285 return NULL;
3286 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003287}
3288
Guido van Rossum79f25d91997-04-29 20:08:16 +00003289static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003290imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 char *name;
3293 struct _frozen *p;
3294 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3295 return NULL;
3296 p = find_frozen(name);
3297 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003298}
3299
3300static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003301get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 FILE *fp;
3304 if (mode[0] == 'U')
3305 mode = "r" PY_STDIOTEXTMODE;
3306 if (fob == NULL) {
3307 fp = fopen(pathname, mode);
3308 }
3309 else {
3310 int fd = PyObject_AsFileDescriptor(fob);
3311 if (fd == -1)
3312 return NULL;
3313 if (!_PyVerify_fd(fd))
3314 goto error;
3315 /* the FILE struct gets a new fd, so that it can be closed
3316 * independently of the file descriptor given
3317 */
3318 fd = dup(fd);
3319 if (fd == -1)
3320 goto error;
3321 fp = fdopen(fd, mode);
3322 }
3323 if (fp)
3324 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003325error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 PyErr_SetFromErrno(PyExc_IOError);
3327 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003328}
3329
Guido van Rossum79f25d91997-04-29 20:08:16 +00003330static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003331imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 char *name;
3334 char *pathname;
3335 PyObject *fob = NULL;
3336 PyObject *m;
3337 FILE *fp;
3338 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3339 &name,
3340 Py_FileSystemDefaultEncoding, &pathname,
3341 &fob))
3342 return NULL;
3343 fp = get_file(pathname, fob, "rb");
3344 if (fp == NULL) {
3345 PyMem_Free(pathname);
3346 return NULL;
3347 }
3348 m = load_compiled_module(name, pathname, fp);
3349 fclose(fp);
3350 PyMem_Free(pathname);
3351 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003352}
3353
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003354#ifdef HAVE_DYNAMIC_LOADING
3355
Guido van Rossum79f25d91997-04-29 20:08:16 +00003356static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003357imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 char *name;
3360 char *pathname;
3361 PyObject *fob = NULL;
3362 PyObject *m;
3363 FILE *fp = NULL;
3364 if (!PyArg_ParseTuple(args, "ses|O:load_dynamic",
3365 &name,
3366 Py_FileSystemDefaultEncoding, &pathname,
3367 &fob))
3368 return NULL;
3369 if (fob) {
3370 fp = get_file(pathname, fob, "r");
3371 if (fp == NULL) {
3372 PyMem_Free(pathname);
3373 return NULL;
3374 }
3375 }
3376 m = _PyImport_LoadDynamicModule(name, pathname, fp);
3377 PyMem_Free(pathname);
3378 if (fp)
3379 fclose(fp);
3380 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003381}
3382
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003383#endif /* HAVE_DYNAMIC_LOADING */
3384
Guido van Rossum79f25d91997-04-29 20:08:16 +00003385static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003386imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 char *name;
3389 char *pathname;
3390 PyObject *fob = NULL;
3391 PyObject *m;
3392 FILE *fp;
3393 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3394 &name,
3395 Py_FileSystemDefaultEncoding, &pathname,
3396 &fob))
3397 return NULL;
3398 fp = get_file(pathname, fob, "r");
3399 if (fp == NULL) {
3400 PyMem_Free(pathname);
3401 return NULL;
3402 }
3403 m = load_source_module(name, pathname, fp);
3404 PyMem_Free(pathname);
3405 fclose(fp);
3406 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003407}
3408
Guido van Rossum79f25d91997-04-29 20:08:16 +00003409static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003410imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 char *name;
3413 PyObject *fob;
3414 char *pathname;
3415 PyObject * ret;
3416 char *suffix; /* Unused */
3417 char *mode;
3418 int type;
3419 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
3422 &name, &fob,
3423 Py_FileSystemDefaultEncoding, &pathname,
3424 &suffix, &mode, &type))
3425 return NULL;
3426 if (*mode) {
3427 /* Mode must start with 'r' or 'U' and must not contain '+'.
3428 Implicit in this test is the assumption that the mode
3429 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3432 PyErr_Format(PyExc_ValueError,
3433 "invalid file open mode %.200s", mode);
3434 PyMem_Free(pathname);
3435 return NULL;
3436 }
3437 }
3438 if (fob == Py_None)
3439 fp = NULL;
3440 else {
3441 fp = get_file(NULL, fob, mode);
3442 if (fp == NULL) {
3443 PyMem_Free(pathname);
3444 return NULL;
3445 }
3446 }
3447 ret = load_module(name, fp, pathname, type, NULL);
3448 PyMem_Free(pathname);
3449 if (fp)
3450 fclose(fp);
3451 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003452}
3453
3454static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003455imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 char *name;
3458 char *pathname;
3459 PyObject * ret;
3460 if (!PyArg_ParseTuple(args, "ses:load_package",
3461 &name, Py_FileSystemDefaultEncoding, &pathname))
3462 return NULL;
3463 ret = load_package(name, pathname);
3464 PyMem_Free(pathname);
3465 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003466}
3467
3468static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003469imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 char *name;
3472 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3473 return NULL;
3474 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003475}
3476
Christian Heimes13a7a212008-01-07 17:13:09 +00003477static PyObject *
3478imp_reload(PyObject *self, PyObject *v)
3479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003481}
3482
3483PyDoc_STRVAR(doc_reload,
3484"reload(module) -> module\n\
3485\n\
3486Reload the module. The module must have been successfully imported before.");
3487
Barry Warsaw28a691b2010-04-17 00:19:56 +00003488static PyObject *
3489imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 char buf[MAXPATHLEN+1];
3494 char *pathname, *cpathname;
3495 PyObject *debug_override = Py_None;
3496 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 if (!PyArg_ParseTupleAndKeywords(
3499 args, kws, "es|O", kwlist,
3500 Py_FileSystemDefaultEncoding, &pathname, &debug_override))
3501 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 if (debug_override != Py_None)
3504 if ((debug = PyObject_IsTrue(debug_override)) < 0)
3505 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug);
3508 PyMem_Free(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 if (cpathname == NULL) {
3511 PyErr_Format(PyExc_SystemError, "path buffer too short");
3512 return NULL;
3513 }
3514 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003515}
3516
3517PyDoc_STRVAR(doc_cache_from_source,
3518"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3519\n\
3520The .py file does not need to exist; this simply returns the path to the\n\
3521.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3522will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3523\n\
3524If debug_override is not None, then it must be a boolean and is taken as\n\
3525the value of __debug__ instead.");
3526
3527static PyObject *
3528imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 char *pathname;
3533 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 if (!PyArg_ParseTupleAndKeywords(
3536 args, kws, "es", kwlist,
3537 Py_FileSystemDefaultEncoding, &pathname))
3538 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 if (make_source_pathname(pathname, buf) == NULL) {
3541 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3542 pathname);
3543 PyMem_Free(pathname);
3544 return NULL;
3545 }
3546 PyMem_Free(pathname);
3547 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003548}
3549
3550PyDoc_STRVAR(doc_source_from_cache,
3551"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3552\n\
3553The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3554the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3555does not conform to PEP 3147 format, ValueError will be raised.");
3556
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003557/* Doc strings */
3558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003559PyDoc_STRVAR(doc_imp,
3560"This module provides the components needed to build your own\n\
3561__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563PyDoc_STRVAR(doc_find_module,
3564"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003565Search for a module. If path is omitted or None, search for a\n\
3566built-in, frozen or special module and continue search in sys.path.\n\
3567The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003568package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003570PyDoc_STRVAR(doc_load_module,
3571"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003572Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003573The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003575PyDoc_STRVAR(doc_get_magic,
3576"get_magic() -> string\n\
3577Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003578
Barry Warsaw28a691b2010-04-17 00:19:56 +00003579PyDoc_STRVAR(doc_get_tag,
3580"get_tag() -> string\n\
3581Return the magic tag for .pyc or .pyo files.");
3582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003583PyDoc_STRVAR(doc_get_suffixes,
3584"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003585Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003586that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003588PyDoc_STRVAR(doc_new_module,
3589"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003590Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003591The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003593PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003594"lock_held() -> boolean\n\
3595Return True if the import lock is currently held, else False.\n\
3596On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003597
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003598PyDoc_STRVAR(doc_acquire_lock,
3599"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003600Acquires the interpreter's import lock for the current thread.\n\
3601This lock should be used by import hooks to ensure thread-safety\n\
3602when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003603On platforms without threads, this function does nothing.");
3604
3605PyDoc_STRVAR(doc_release_lock,
3606"release_lock() -> None\n\
3607Release the interpreter's import lock.\n\
3608On platforms without threads, this function does nothing.");
3609
Guido van Rossum79f25d91997-04-29 20:08:16 +00003610static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3612 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3613 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3614 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3615 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3616 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3617 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3618 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3619 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3620 {"reload", imp_reload, METH_O, doc_reload},
3621 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3622 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3623 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3624 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3625 /* The rest are obsolete */
3626 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3627 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3628 {"init_builtin", imp_init_builtin, METH_VARARGS},
3629 {"init_frozen", imp_init_frozen, METH_VARARGS},
3630 {"is_builtin", imp_is_builtin, METH_VARARGS},
3631 {"is_frozen", imp_is_frozen, METH_VARARGS},
3632 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003633#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003635#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 {"load_package", imp_load_package, METH_VARARGS},
3637 {"load_source", imp_load_source, METH_VARARGS},
3638 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003639};
3640
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003641static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003642setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 PyObject *v;
3645 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 v = PyLong_FromLong((long)value);
3648 err = PyDict_SetItemString(d, name, v);
3649 Py_XDECREF(v);
3650 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003651}
3652
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003653typedef struct {
3654 PyObject_HEAD
3655} NullImporter;
3656
3657static int
3658NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3659{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003660#ifndef MS_WINDOWS
3661 PyObject *path;
3662 struct stat statbuf;
3663 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3666 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003667
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003668 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3669 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003671
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003672 if (PyBytes_GET_SIZE(path) == 0) {
3673 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 PyErr_SetString(PyExc_ImportError, "empty pathname");
3675 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003677
3678 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3679 Py_DECREF(path);
3680 if (rv == 0) {
3681 /* it exists */
3682 if (S_ISDIR(statbuf.st_mode)) {
3683 /* it's a directory */
3684 PyErr_SetString(PyExc_ImportError, "existing directory");
3685 return -1;
3686 }
3687 }
3688#else /* MS_WINDOWS */
3689 PyObject *pathobj;
3690 DWORD rv;
3691 wchar_t path[MAXPATHLEN+1];
3692 Py_ssize_t len;
3693
3694 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3695 return -1;
3696
3697 if (!PyArg_ParseTuple(args, "U:NullImporter",
3698 &pathobj))
3699 return -1;
3700
3701 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3702 PyErr_SetString(PyExc_ImportError, "empty pathname");
3703 return -1;
3704 }
3705
3706 len = PyUnicode_AsWideChar((PyUnicodeObject*)pathobj,
3707 path, sizeof(path) / sizeof(path[0]));
3708 if (len == -1)
3709 return -1;
3710 /* see issue1293 and issue3677:
3711 * stat() on Windows doesn't recognise paths like
3712 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3713 */
3714 rv = GetFileAttributesW(path);
3715 if (rv != INVALID_FILE_ATTRIBUTES) {
3716 /* it exists */
3717 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3718 /* it's a directory */
3719 PyErr_SetString(PyExc_ImportError, "existing directory");
3720 return -1;
3721 }
3722 }
3723#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003725}
3726
3727static PyObject *
3728NullImporter_find_module(NullImporter *self, PyObject *args)
3729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003731}
3732
3733static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3735 "Always return None"
3736 },
3737 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003738};
3739
3740
Christian Heimes9cd17752007-11-18 19:35:23 +00003741PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 PyVarObject_HEAD_INIT(NULL, 0)
3743 "imp.NullImporter", /*tp_name*/
3744 sizeof(NullImporter), /*tp_basicsize*/
3745 0, /*tp_itemsize*/
3746 0, /*tp_dealloc*/
3747 0, /*tp_print*/
3748 0, /*tp_getattr*/
3749 0, /*tp_setattr*/
3750 0, /*tp_reserved*/
3751 0, /*tp_repr*/
3752 0, /*tp_as_number*/
3753 0, /*tp_as_sequence*/
3754 0, /*tp_as_mapping*/
3755 0, /*tp_hash */
3756 0, /*tp_call*/
3757 0, /*tp_str*/
3758 0, /*tp_getattro*/
3759 0, /*tp_setattro*/
3760 0, /*tp_as_buffer*/
3761 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3762 "Null importer object", /* tp_doc */
3763 0, /* tp_traverse */
3764 0, /* tp_clear */
3765 0, /* tp_richcompare */
3766 0, /* tp_weaklistoffset */
3767 0, /* tp_iter */
3768 0, /* tp_iternext */
3769 NullImporter_methods, /* tp_methods */
3770 0, /* tp_members */
3771 0, /* tp_getset */
3772 0, /* tp_base */
3773 0, /* tp_dict */
3774 0, /* tp_descr_get */
3775 0, /* tp_descr_set */
3776 0, /* tp_dictoffset */
3777 (initproc)NullImporter_init, /* tp_init */
3778 0, /* tp_alloc */
3779 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003780};
3781
Martin v. Löwis1a214512008-06-11 05:26:20 +00003782static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 PyModuleDef_HEAD_INIT,
3784 "imp",
3785 doc_imp,
3786 0,
3787 imp_methods,
3788 NULL,
3789 NULL,
3790 NULL,
3791 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003792};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003793
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003794PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003795PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 if (PyType_Ready(&PyNullImporter_Type) < 0)
3800 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 m = PyModule_Create(&impmodule);
3803 if (m == NULL)
3804 goto failure;
3805 d = PyModule_GetDict(m);
3806 if (d == NULL)
3807 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3810 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3811 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3812 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3813 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3814 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3815 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3816 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3817 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3818 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 Py_INCREF(&PyNullImporter_Type);
3821 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3822 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003823 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 Py_XDECREF(m);
3825 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003826}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003827
3828
Guido van Rossumb18618d2000-05-03 23:44:39 +00003829/* API for embedding applications that want to add their own entries
3830 to the table of built-in modules. This should normally be called
3831 *before* Py_Initialize(). When the table resize fails, -1 is
3832 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003833
3834 After a similar function by Just van Rossum. */
3835
3836int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003837PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 static struct _inittab *our_copy = NULL;
3840 struct _inittab *p;
3841 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 /* Count the number of entries in both tables */
3844 for (n = 0; newtab[n].name != NULL; n++)
3845 ;
3846 if (n == 0)
3847 return 0; /* Nothing to do */
3848 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3849 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 /* Allocate new memory for the combined table */
3852 p = our_copy;
3853 PyMem_RESIZE(p, struct _inittab, i+n+1);
3854 if (p == NULL)
3855 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 /* Copy the tables into the new memory */
3858 if (our_copy != PyImport_Inittab)
3859 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3860 PyImport_Inittab = our_copy = p;
3861 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003864}
3865
3866/* Shorthand to add a single entry given a name and a function */
3867
3868int
Brett Cannona826f322009-04-02 03:41:46 +00003869PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 newtab[0].name = (char *)name;
3876 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003879}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003880
3881#ifdef __cplusplus
3882}
3883#endif