blob: f5bc03ddd8341db33dcf13249d6f0dc2d0dc6637 [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;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000028/* for _mkdir */
29#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000030#endif
31
Guido van Rossum21d335e1993-10-15 13:01:11 +000032
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000033/* Magic word to reject .pyc files generated by other Python versions.
34 It should change for each incompatible change to the bytecode.
35
36 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000037 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000038 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Guido van Rossum45aecf42006-03-15 04:58:47 +000040 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000041 -U interpeter flag will cause MAGIC+1 being used. They have been
42 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000044 There were a variety of old schemes for setting the magic number.
45 The current working scheme is to increment the previous value by
46 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000047
Barry Warsaw28a691b2010-04-17 00:19:56 +000048 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
49 number also includes a new "magic tag", i.e. a human readable string used
50 to represent the magic number in __pycache__ directories. When you change
51 the magic number, you must also set a new unique magic tag. Generally this
52 can be named after the Python major version of the magic number bump, but
53 it can really be anything, as long as it's different than anything else
54 that's come before. The tags are included in the following table, starting
55 with Python 3.2a0.
56
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000057 Known values:
58 Python 1.5: 20121
59 Python 1.5.1: 20121
60 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000062 Python 2.0: 50823
63 Python 2.0.1: 50823
64 Python 2.1: 60202
65 Python 2.1.1: 60202
66 Python 2.1.2: 60202
67 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000068 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000069 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000070 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000071 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000072 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000073 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000074 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000075 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000076 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000077 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
79 Python 2.5b3: 62111 (fix wrong code: x += yield)
80 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000082 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000083 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000084 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000085 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 3010 (removed UNARY_CONVERT)
87 3020 (added BUILD_SET)
88 3030 (added keyword-only parameters)
89 3040 (added signature annotations)
90 3050 (print becomes a function)
91 3060 (PEP 3115 metaclass syntax)
92 3061 (string literals become unicode)
93 3071 (PEP 3109 raise changes)
94 3081 (PEP 3137 make __file__ and __name__ unicode)
95 3091 (kill str8 interning)
96 3101 (merge from 2.6a0, see 62151)
97 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
99 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
100 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +0000102 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000104 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000106 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
107 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000108 Python 3.2a2 3180 (add DELETE_DEREF)
Tim Peters36515e22001-11-18 04:06:29 +0000109*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000110
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111/* If you change MAGIC, you must change TAG and you must insert the old value
112 into _PyMagicNumberTags below.
113*/
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000114#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000115#define TAG "cpython-32"
116#define CACHEDIR "__pycache__"
117/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000118static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000119static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121/* See _PyImport_FixupExtension() below */
122static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000123
Guido van Rossum771c6c81997-10-31 18:37:24 +0000124/* This table is defined in config.c: */
125extern struct _inittab _PyImport_Inittab[];
126
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000127/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000128extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000129
Guido van Rossum771c6c81997-10-31 18:37:24 +0000130struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000131
Guido van Rossumed1170e1999-12-20 21:23:41 +0000132/* these tables define the module suffixes that Python recognizes */
133struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000134
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000137#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000139#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 {".pyc", "rb", PY_COMPILED},
141 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000142};
143
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000145/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146
147void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000148_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 const struct filedescr *scan;
151 struct filedescr *filetab;
152 int countD = 0;
153 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 /* prepare _PyImport_Filetab: copy entries from
156 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
157 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000158#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
160 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000161#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
163 ++countS;
164 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
165 if (filetab == NULL)
166 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000167#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 memcpy(filetab, _PyImport_DynLoadFiletab,
169 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000170#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 memcpy(filetab + countD, _PyImport_StandardFiletab,
172 countS * sizeof(struct filedescr));
173 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (Py_OptimizeFlag) {
178 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
179 for (; filetab->suffix != NULL; filetab++) {
180 if (strcmp(filetab->suffix, ".pyc") == 0)
181 filetab->suffix = ".pyo";
182 }
183 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184}
185
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186void
Just van Rossum52e14d62002-12-30 22:08:05 +0000187_PyImportHooks_Init(void)
188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 PyObject *v, *path_hooks = NULL, *zimpimport;
190 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 /* adding sys.path_hooks and sys.path_importer_cache, setting up
193 zipimport */
194 if (PyType_Ready(&PyNullImporter_Type) < 0)
195 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if (Py_VerboseFlag)
198 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 v = PyList_New(0);
201 if (v == NULL)
202 goto error;
203 err = PySys_SetObject("meta_path", v);
204 Py_DECREF(v);
205 if (err)
206 goto error;
207 v = PyDict_New();
208 if (v == NULL)
209 goto error;
210 err = PySys_SetObject("path_importer_cache", v);
211 Py_DECREF(v);
212 if (err)
213 goto error;
214 path_hooks = PyList_New(0);
215 if (path_hooks == NULL)
216 goto error;
217 err = PySys_SetObject("path_hooks", path_hooks);
218 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000219 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyErr_Print();
221 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
222 "path_importer_cache, or NullImporter failed"
223 );
224 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 zimpimport = PyImport_ImportModule("zipimport");
227 if (zimpimport == NULL) {
228 PyErr_Clear(); /* No zip import module -- okay */
229 if (Py_VerboseFlag)
230 PySys_WriteStderr("# can't import zipimport\n");
231 }
232 else {
233 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
234 "zipimporter");
235 Py_DECREF(zimpimport);
236 if (zipimporter == NULL) {
237 PyErr_Clear(); /* No zipimporter object -- okay */
238 if (Py_VerboseFlag)
239 PySys_WriteStderr(
240 "# can't import zipimport.zipimporter\n");
241 }
242 else {
243 /* sys.path_hooks.append(zipimporter) */
244 err = PyList_Append(path_hooks, zipimporter);
245 Py_DECREF(zipimporter);
246 if (err)
247 goto error;
248 if (Py_VerboseFlag)
249 PySys_WriteStderr(
250 "# installed zipimport hook\n");
251 }
252 }
253 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000254}
255
256void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000257_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 Py_XDECREF(extensions);
260 extensions = NULL;
261 PyMem_DEL(_PyImport_Filetab);
262 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263}
264
265
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000266/* Locking primitives to prevent parallel imports of the same module
267 in different threads to return with a partially loaded module.
268 These calls are serialized by the global interpreter lock. */
269
270#ifdef WITH_THREAD
271
Guido van Rossum49b56061998-10-01 20:42:43 +0000272#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000273
Guido van Rossum65d5b571998-12-21 19:32:43 +0000274static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000275static long import_lock_thread = -1;
276static int import_lock_level = 0;
277
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000278void
279_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 long me = PyThread_get_thread_ident();
282 if (me == -1)
283 return; /* Too bad */
284 if (import_lock == NULL) {
285 import_lock = PyThread_allocate_lock();
286 if (import_lock == NULL)
287 return; /* Nothing much we can do. */
288 }
289 if (import_lock_thread == me) {
290 import_lock_level++;
291 return;
292 }
293 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
294 {
295 PyThreadState *tstate = PyEval_SaveThread();
296 PyThread_acquire_lock(import_lock, 1);
297 PyEval_RestoreThread(tstate);
298 }
299 import_lock_thread = me;
300 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000301}
302
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000303int
304_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 long me = PyThread_get_thread_ident();
307 if (me == -1 || import_lock == NULL)
308 return 0; /* Too bad */
309 if (import_lock_thread != me)
310 return -1;
311 import_lock_level--;
312 if (import_lock_level == 0) {
313 import_lock_thread = -1;
314 PyThread_release_lock(import_lock);
315 }
316 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000317}
318
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000319/* This function is called from PyOS_AfterFork to ensure that newly
320 created child processes do not share locks with the parent.
321 We now acquire the import lock around fork() calls but on some platforms
322 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000323
324void
325_PyImport_ReInitLock(void)
326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (import_lock != NULL)
328 import_lock = PyThread_allocate_lock();
329 import_lock_thread = -1;
330 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000331}
332
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000333#endif
334
Tim Peters69232342001-08-30 05:16:13 +0000335static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000336imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000337{
Tim Peters69232342001-08-30 05:16:13 +0000338#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000340#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000342#endif
343}
344
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000346imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000347{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000350#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 Py_INCREF(Py_None);
352 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353}
354
355static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000356imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000357{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000358#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (_PyImport_ReleaseLock() < 0) {
360 PyErr_SetString(PyExc_RuntimeError,
361 "not holding the import lock");
362 return NULL;
363 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000364#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 Py_INCREF(Py_None);
366 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000367}
368
Guido van Rossumd8faa362007-04-27 19:54:29 +0000369static void
370imp_modules_reloading_clear(void)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyInterpreterState *interp = PyThreadState_Get()->interp;
373 if (interp->modules_reloading != NULL)
374 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000375}
376
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377/* Helper for sys */
378
379PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000380PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyInterpreterState *interp = PyThreadState_GET()->interp;
383 if (interp->modules == NULL)
384 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
385 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000386}
387
Guido van Rossum3f5da241990-12-20 15:06:42 +0000388
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000389/* List of names to clear in sys */
390static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 "path", "argv", "ps1", "ps2",
392 "last_type", "last_value", "last_traceback",
393 "path_hooks", "path_importer_cache", "meta_path",
394 /* misc stuff */
395 "flags", "float_info",
396 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000397};
398
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000399static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 "stdin", "__stdin__",
401 "stdout", "__stdout__",
402 "stderr", "__stderr__",
403 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000404};
405
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000406
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000407/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000408
Guido van Rossum3f5da241990-12-20 15:06:42 +0000409void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000410PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 Py_ssize_t pos, ndone;
413 char *name;
414 PyObject *key, *value, *dict;
415 PyInterpreterState *interp = PyThreadState_GET()->interp;
416 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (modules == NULL)
419 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 /* Delete some special variables first. These are common
422 places where user values hide and people complain when their
423 destructors fail. Since the modules containing them are
424 deleted *last* of all, they would come too late in the normal
425 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 value = PyDict_GetItemString(modules, "builtins");
428 if (value != NULL && PyModule_Check(value)) {
429 dict = PyModule_GetDict(value);
430 if (Py_VerboseFlag)
431 PySys_WriteStderr("# clear builtins._\n");
432 PyDict_SetItemString(dict, "_", Py_None);
433 }
434 value = PyDict_GetItemString(modules, "sys");
435 if (value != NULL && PyModule_Check(value)) {
436 char **p;
437 PyObject *v;
438 dict = PyModule_GetDict(value);
439 for (p = sys_deletes; *p != NULL; p++) {
440 if (Py_VerboseFlag)
441 PySys_WriteStderr("# clear sys.%s\n", *p);
442 PyDict_SetItemString(dict, *p, Py_None);
443 }
444 for (p = sys_files; *p != NULL; p+=2) {
445 if (Py_VerboseFlag)
446 PySys_WriteStderr("# restore sys.%s\n", *p);
447 v = PyDict_GetItemString(dict, *(p+1));
448 if (v == NULL)
449 v = Py_None;
450 PyDict_SetItemString(dict, *p, v);
451 }
452 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* First, delete __main__ */
455 value = PyDict_GetItemString(modules, "__main__");
456 if (value != NULL && PyModule_Check(value)) {
457 if (Py_VerboseFlag)
458 PySys_WriteStderr("# cleanup __main__\n");
459 _PyModule_Clear(value);
460 PyDict_SetItemString(modules, "__main__", Py_None);
461 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 /* The special treatment of "builtins" here is because even
464 when it's not referenced as a module, its dictionary is
465 referenced by almost every module's __builtins__. Since
466 deleting a module clears its dictionary (even if there are
467 references left to it), we need to delete the "builtins"
468 module last. Likewise, we don't delete sys until the very
469 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Also note that we 'delete' modules by replacing their entry
472 in the modules dict with None, rather than really deleting
473 them; this avoids a rehash of the modules dictionary and
474 also marks them as "non existent" so they won't be
475 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Next, repeatedly delete modules with a reference count of
478 one (skipping builtins and sys) and delete them */
479 do {
480 ndone = 0;
481 pos = 0;
482 while (PyDict_Next(modules, &pos, &key, &value)) {
483 if (value->ob_refcnt != 1)
484 continue;
485 if (PyUnicode_Check(key) && PyModule_Check(value)) {
486 name = _PyUnicode_AsString(key);
487 if (strcmp(name, "builtins") == 0)
488 continue;
489 if (strcmp(name, "sys") == 0)
490 continue;
491 if (Py_VerboseFlag)
492 PySys_WriteStderr(
493 "# cleanup[1] %s\n", name);
494 _PyModule_Clear(value);
495 PyDict_SetItem(modules, key, Py_None);
496 ndone++;
497 }
498 }
499 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Next, delete all modules (still skipping builtins and sys) */
502 pos = 0;
503 while (PyDict_Next(modules, &pos, &key, &value)) {
504 if (PyUnicode_Check(key) && PyModule_Check(value)) {
505 name = _PyUnicode_AsString(key);
506 if (strcmp(name, "builtins") == 0)
507 continue;
508 if (strcmp(name, "sys") == 0)
509 continue;
510 if (Py_VerboseFlag)
511 PySys_WriteStderr("# cleanup[2] %s\n", name);
512 _PyModule_Clear(value);
513 PyDict_SetItem(modules, key, Py_None);
514 }
515 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Next, delete sys and builtins (in that order) */
518 value = PyDict_GetItemString(modules, "sys");
519 if (value != NULL && PyModule_Check(value)) {
520 if (Py_VerboseFlag)
521 PySys_WriteStderr("# cleanup sys\n");
522 _PyModule_Clear(value);
523 PyDict_SetItemString(modules, "sys", Py_None);
524 }
525 value = PyDict_GetItemString(modules, "builtins");
526 if (value != NULL && PyModule_Check(value)) {
527 if (Py_VerboseFlag)
528 PySys_WriteStderr("# cleanup builtins\n");
529 _PyModule_Clear(value);
530 PyDict_SetItemString(modules, "builtins", Py_None);
531 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* Finally, clear and delete the modules directory */
534 PyDict_Clear(modules);
535 interp->modules = NULL;
536 Py_DECREF(modules);
537 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000538}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000539
540
Barry Warsaw28a691b2010-04-17 00:19:56 +0000541/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000542
543long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547}
548
549
Barry Warsaw28a691b2010-04-17 00:19:56 +0000550const char *
551PyImport_GetMagicTag(void)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000554}
555
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556/* Magic for extension modules (built-in as well as dynamically
557 loaded). To prevent initializing an extension module more than
558 once, we keep a static dictionary 'extensions' keyed by module name
559 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000560 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561 dictionary is stored by calling _PyImport_FixupExtension()
562 immediately after the module initialization function succeeds. A
563 copy can be retrieved from there by calling
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000564 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000566 Modules which do support multiple initialization set their m_size
567 field to a non-negative number (indicating the size of the
568 module-specific state). They are still recorded in the extensions
569 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000570*/
571
572int
573_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 PyObject *modules, *dict;
576 struct PyModuleDef *def;
577 if (extensions == NULL) {
578 extensions = PyDict_New();
579 if (extensions == NULL)
580 return -1;
581 }
582 if (mod == NULL || !PyModule_Check(mod)) {
583 PyErr_BadInternalCall();
584 return -1;
585 }
586 def = PyModule_GetDef(mod);
587 if (!def) {
588 PyErr_BadInternalCall();
589 return -1;
590 }
591 modules = PyImport_GetModuleDict();
592 if (PyDict_SetItemString(modules, name, mod) < 0)
593 return -1;
594 if (_PyState_AddModule(mod, def) < 0) {
595 PyDict_DelItemString(modules, name);
596 return -1;
597 }
598 if (def->m_size == -1) {
599 if (def->m_base.m_copy) {
600 /* Somebody already imported the module,
601 likely under a different name.
602 XXX this should really not happen. */
603 Py_DECREF(def->m_base.m_copy);
604 def->m_base.m_copy = NULL;
605 }
606 dict = PyModule_GetDict(mod);
607 if (dict == NULL)
608 return -1;
609 def->m_base.m_copy = PyDict_Copy(dict);
610 if (def->m_base.m_copy == NULL)
611 return -1;
612 }
613 PyDict_SetItemString(extensions, filename, (PyObject*)def);
614 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615}
616
617PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000618_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 PyObject *mod, *mdict;
621 PyModuleDef* def;
622 if (extensions == NULL)
623 return NULL;
624 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
625 if (def == NULL)
626 return NULL;
627 if (def->m_size == -1) {
628 /* Module does not support repeated initialization */
629 if (def->m_base.m_copy == NULL)
630 return NULL;
631 mod = PyImport_AddModule(name);
632 if (mod == NULL)
633 return NULL;
634 mdict = PyModule_GetDict(mod);
635 if (mdict == NULL)
636 return NULL;
637 if (PyDict_Update(mdict, def->m_base.m_copy))
638 return NULL;
639 }
640 else {
641 if (def->m_base.m_init == NULL)
642 return NULL;
643 mod = def->m_base.m_init();
644 if (mod == NULL)
645 return NULL;
646 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
647 Py_DECREF(mod);
648 }
649 if (_PyState_AddModule(mod, def) < 0) {
650 PyDict_DelItemString(PyImport_GetModuleDict(), name);
651 Py_DECREF(mod);
652 return NULL;
653 }
654 if (Py_VerboseFlag)
655 PySys_WriteStderr("import %s # previously loaded (%s)\n",
656 name, filename);
657 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000658
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000659}
660
661
662/* Get the module object corresponding to a module name.
663 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000664 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000665 Because the former action is most common, THIS DOES NOT RETURN A
666 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000667
Guido van Rossum79f25d91997-04-29 20:08:16 +0000668PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000669PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyObject *modules = PyImport_GetModuleDict();
672 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
675 PyModule_Check(m))
676 return m;
677 m = PyModule_New(name);
678 if (m == NULL)
679 return NULL;
680 if (PyDict_SetItemString(modules, name, m) != 0) {
681 Py_DECREF(m);
682 return NULL;
683 }
684 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000687}
688
Tim Peters1cd70172004-08-02 03:52:12 +0000689/* Remove name from sys.modules, if it's there. */
690static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000691remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 PyObject *modules = PyImport_GetModuleDict();
694 if (PyDict_GetItemString(modules, name) == NULL)
695 return;
696 if (PyDict_DelItemString(modules, name) < 0)
697 Py_FatalError("import: deleting existing key in"
698 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000699}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000700
Barry Warsaw28a691b2010-04-17 00:19:56 +0000701static PyObject * get_sourcefile(char *file);
702static char *make_source_pathname(char *pathname, char *buf);
703static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000705
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000706/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000707 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
708 * removed from sys.modules, to avoid leaving damaged module objects
709 * in sys.modules. The caller may wish to restore the original
710 * module object (if any) in this case; PyImport_ReloadModule is an
711 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000712 *
713 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
714 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000715 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000716PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000717PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return PyImport_ExecCodeModuleWithPathnames(
720 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000721}
722
723PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000724PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return PyImport_ExecCodeModuleWithPathnames(
727 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000728}
729
730PyObject *
731PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyObject *modules = PyImport_GetModuleDict();
735 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 m = PyImport_AddModule(name);
738 if (m == NULL)
739 return NULL;
740 /* If the module is being reloaded, we get the old module back
741 and re-use its dict to exec the new code. */
742 d = PyModule_GetDict(m);
743 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
744 if (PyDict_SetItemString(d, "__builtins__",
745 PyEval_GetBuiltins()) != 0)
746 goto error;
747 }
748 /* Remember the filename as the __file__ attribute */
749 v = NULL;
750 if (pathname != NULL) {
751 v = get_sourcefile(pathname);
752 if (v == NULL)
753 PyErr_Clear();
754 }
755 if (v == NULL) {
756 v = ((PyCodeObject *)co)->co_filename;
757 Py_INCREF(v);
758 }
759 if (PyDict_SetItemString(d, "__file__", v) != 0)
760 PyErr_Clear(); /* Not important enough to report */
761 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 /* Remember the pyc path name as the __cached__ attribute. */
764 if (cpathname == NULL) {
765 v = Py_None;
766 Py_INCREF(v);
767 }
768 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
769 PyErr_Clear(); /* Not important enough to report */
770 v = Py_None;
771 Py_INCREF(v);
772 }
773 if (PyDict_SetItemString(d, "__cached__", v) != 0)
774 PyErr_Clear(); /* Not important enough to report */
775 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
778 if (v == NULL)
779 goto error;
780 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
783 PyErr_Format(PyExc_ImportError,
784 "Loaded module %.200s not found in sys.modules",
785 name);
786 return NULL;
787 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000792
793 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 remove_module(name);
795 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000796}
797
798
Barry Warsaw28a691b2010-04-17 00:19:56 +0000799/* Like strrchr(string, '/') but searches for the rightmost of either SEP
800 or ALTSEP, if the latter is defined.
801*/
802static char *
803rightmost_sep(char *s)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 char *found, c;
806 for (found = NULL; (c = *s); s++) {
807 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000808#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000810#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 )
812 {
813 found = s;
814 }
815 }
816 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000817}
818
819
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000820/* Given a pathname for a Python source file, fill a buffer with the
821 pathname for the corresponding compiled file. Return the pathname
822 for the compiled file, or NULL if there's no space in the buffer.
823 Doesn't set an exception. */
824
825static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000826make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 /* foo.py -> __pycache__/foo.<tag>.pyc */
829 size_t len = strlen(pathname);
830 size_t i, save;
831 char *pos;
832 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* Sanity check that the buffer has roughly enough space to hold what
835 will eventually be the full path to the compiled file. The 5 extra
836 bytes include the slash afer __pycache__, the two extra dots, the
837 extra trailing character ('c' or 'o') and null. This isn't exact
838 because the contents of the buffer can affect how many actual
839 characters of the string get into the buffer. We'll do a final
840 sanity check before writing the extension to ensure we do not
841 overflow the buffer.
842 */
843 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
844 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 /* Find the last path separator and copy everything from the start of
847 the source string up to and including the separator.
848 */
849 if ((pos = rightmost_sep(pathname)) == NULL) {
850 i = 0;
851 }
852 else {
853 sep = *pos;
854 i = pos - pathname + 1;
855 strncpy(buf, pathname, i);
856 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 save = i;
859 buf[i++] = '\0';
860 /* Add __pycache__/ */
861 strcat(buf, CACHEDIR);
862 i += strlen(CACHEDIR) - 1;
863 buf[i++] = sep;
864 buf[i++] = '\0';
865 /* Add the base filename, but remove the .py or .pyw extension, since
866 the tag name must go before the extension.
867 */
868 strcat(buf, pathname + save);
869 if ((pos = strrchr(buf, '.')) != NULL)
870 *++pos = '\0';
871 strcat(buf, pyc_tag);
872 /* The length test above assumes that we're only adding one character
873 to the end of what would normally be the extension. What if there
874 is no extension, or the string ends in '.' or '.p', and otherwise
875 fills the buffer? By appending 4 more characters onto the string
876 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 As a simple example, let's say buflen=32 and the input string is
879 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 which is false and so the name mangling would continue. This would
884 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
889 We can even handle an input string of say 'xxxxx' above because
890 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
891 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 which is 32 characters including the nul, and thus fits in the
896 buffer. However, an input string of 'xxxxxx' would yield a result
897 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 which is 33 characters long (including the nul), thus overflowing
902 the buffer, even though the first test would fail, i.e.: the input
903 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 The reason the first test fails but we still overflow the buffer is
906 that the test above only expects to add one extra character to be
907 added to the extension, and here we're adding three (pyc). We
908 don't add the first dot, so that reclaims one of expected
909 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
910 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 The best we can do is ensure that we still have enough room in the
913 target buffer before we write the extension. Because it's always
914 only the extension that can cause the overflow, and never the other
915 path bytes we've written, it's sufficient to just do one more test
916 here. Still, the assertion that follows can't hurt.
917 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000918#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000920#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (strlen(buf) + 5 > buflen)
922 return NULL;
923 strcat(buf, debug ? ".pyc" : ".pyo");
924 assert(strlen(buf) < buflen);
925 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000926}
927
928
Barry Warsaw28a691b2010-04-17 00:19:56 +0000929/* Given a pathname to a Python byte compiled file, return the path to the
930 source file, if the path matches the PEP 3147 format. This does not check
931 for any file existence, however, if the pyc file name does not match PEP
932 3147 style, NULL is returned. buf must be at least as big as pathname;
933 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934
Barry Warsaw28a691b2010-04-17 00:19:56 +0000935static char *
936make_source_pathname(char *pathname, char *buf)
937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* __pycache__/foo.<tag>.pyc -> foo.py */
939 size_t i, j;
940 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Look back two slashes from the end. In between these two slashes
943 must be the string __pycache__ or this is not a PEP 3147 style
944 path. It's possible for there to be only one slash.
945 */
946 if ((right = rightmost_sep(pathname)) == NULL)
947 return NULL;
948 sep = *right;
949 *right = '\0';
950 left = rightmost_sep(pathname);
951 *right = sep;
952 if (left == NULL)
953 left = pathname;
954 else
955 left++;
956 if (right-left != strlen(CACHEDIR) ||
957 strncmp(left, CACHEDIR, right-left) != 0)
958 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Now verify that the path component to the right of the last slash
961 has two dots in it.
962 */
963 if ((dot0 = strchr(right + 1, '.')) == NULL)
964 return NULL;
965 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
966 return NULL;
967 /* Too many dots? */
968 if (strchr(dot1 + 1, '.') != NULL)
969 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* This is a PEP 3147 path. Start by copying everything from the
972 start of pathname up to and including the leftmost slash. Then
973 copy the file's basename, removing the magic tag and adding a .py
974 suffix.
975 */
976 strncpy(buf, pathname, (i=left-pathname));
977 strncpy(buf+i, right+1, (j=dot0-right));
978 strcpy(buf+i+j, "py");
979 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000980}
981
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000982/* Given a pathname for a Python source file, its time of last
983 modification, and a pathname for a compiled file, check whether the
984 compiled file represents the same version of the source. If so,
985 return a FILE pointer for the compiled file, positioned just after
986 the header; if not, return NULL.
987 Doesn't set an exception. */
988
989static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000990check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 FILE *fp;
993 long magic;
994 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 fp = fopen(cpathname, "rb");
997 if (fp == NULL)
998 return NULL;
999 magic = PyMarshal_ReadLongFromFile(fp);
1000 if (magic != pyc_magic) {
1001 if (Py_VerboseFlag)
1002 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1003 fclose(fp);
1004 return NULL;
1005 }
1006 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1007 if (pyc_mtime != mtime) {
1008 if (Py_VerboseFlag)
1009 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1010 fclose(fp);
1011 return NULL;
1012 }
1013 if (Py_VerboseFlag)
1014 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1015 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001016}
1017
1018
1019/* Read a code object from a file and check it for validity */
1020
Guido van Rossum79f25d91997-04-29 20:08:16 +00001021static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001022read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 co = PyMarshal_ReadLastObjectFromFile(fp);
1027 if (co == NULL)
1028 return NULL;
1029 if (!PyCode_Check(co)) {
1030 PyErr_Format(PyExc_ImportError,
1031 "Non-code object in %.200s", cpathname);
1032 Py_DECREF(co);
1033 return NULL;
1034 }
1035 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001036}
1037
1038
1039/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001040 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001041
Guido van Rossum79f25d91997-04-29 20:08:16 +00001042static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001043load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 long magic;
1046 PyCodeObject *co;
1047 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 magic = PyMarshal_ReadLongFromFile(fp);
1050 if (magic != pyc_magic) {
1051 PyErr_Format(PyExc_ImportError,
1052 "Bad magic number in %.200s", cpathname);
1053 return NULL;
1054 }
1055 (void) PyMarshal_ReadLongFromFile(fp);
1056 co = read_compiled_module(cpathname, fp);
1057 if (co == NULL)
1058 return NULL;
1059 if (Py_VerboseFlag)
1060 PySys_WriteStderr("import %s # precompiled from %s\n",
1061 name, cpathname);
1062 m = PyImport_ExecCodeModuleWithPathnames(
1063 name, (PyObject *)co, cpathname, cpathname);
1064 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001067}
1068
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001069/* Parse a source file and return the corresponding code object */
1070
Guido van Rossum79f25d91997-04-29 20:08:16 +00001071static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001072parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyCodeObject *co = NULL;
1075 mod_ty mod;
1076 PyCompilerFlags flags;
1077 PyArena *arena = PyArena_New();
1078 if (arena == NULL)
1079 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 flags.cf_flags = 0;
1082 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1083 Py_file_input, 0, 0, &flags,
1084 NULL, arena);
1085 if (mod) {
1086 co = PyAST_Compile(mod, pathname, NULL, arena);
1087 }
1088 PyArena_Free(arena);
1089 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001090}
1091
1092
Guido van Rossum55a83382000-09-20 20:31:38 +00001093/* Helper to open a bytecode file for writing in exclusive mode */
1094
1095static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001096open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001097{
1098#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 /* Use O_EXCL to avoid a race condition when another process tries to
1100 write the same file. When that happens, our open() call fails,
1101 which is just fine (since it's only a cache).
1102 XXX If the file exists and is writable but the directory is not
1103 writable, the file will never be written. Oh well.
1104 */
1105 int fd;
1106 (void) unlink(filename);
1107 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001108#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001110#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001111#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001113#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001115#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 );
1117 if (fd < 0)
1118 return NULL;
1119 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001120#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* Best we can do -- on Windows this can't happen anyway */
1122 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001123#endif
1124}
1125
1126
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001127/* Write a compiled module to a file, placing the time of last
1128 modification of its source into the header.
1129 Errors are ignored, if a write error occurs an attempt is made to
1130 remove the file. */
1131
1132static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001133write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 FILE *fp;
1136 char *dirpath;
1137 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001138#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001140#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1142 mode_t dirmode = (srcstat->st_mode |
1143 S_IXUSR | S_IXGRP | S_IXOTH |
1144 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001145#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 /* Ensure that the __pycache__ directory exists. */
1149 dirpath = rightmost_sep(cpathname);
1150 if (dirpath == NULL) {
1151 if (Py_VerboseFlag)
1152 PySys_WriteStderr(
1153 "# no %s path found %s\n",
1154 CACHEDIR, cpathname);
1155 return;
1156 }
1157 saved = *dirpath;
1158 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001159
1160#ifdef MS_WINDOWS
1161 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1162#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001164#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 *dirpath = saved;
1166 if (Py_VerboseFlag)
1167 PySys_WriteStderr(
1168 "# cannot create cache dir %s\n", cpathname);
1169 return;
1170 }
1171 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 fp = open_exclusive(cpathname, mode);
1174 if (fp == NULL) {
1175 if (Py_VerboseFlag)
1176 PySys_WriteStderr(
1177 "# can't create %s\n", cpathname);
1178 return;
1179 }
1180 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1181 /* First write a 0 for mtime */
1182 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1183 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1184 if (fflush(fp) != 0 || ferror(fp)) {
1185 if (Py_VerboseFlag)
1186 PySys_WriteStderr("# can't write %s\n", cpathname);
1187 /* Don't keep partial file */
1188 fclose(fp);
1189 (void) unlink(cpathname);
1190 return;
1191 }
1192 /* Now write the true mtime */
1193 fseek(fp, 4L, 0);
1194 assert(mtime < LONG_MAX);
1195 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1196 fflush(fp);
1197 fclose(fp);
1198 if (Py_VerboseFlag)
1199 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001200}
1201
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001202static void
1203update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyObject *constants, *tmp;
1206 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 if (PyUnicode_Compare(co->co_filename, oldname))
1209 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 tmp = co->co_filename;
1212 co->co_filename = newname;
1213 Py_INCREF(co->co_filename);
1214 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 constants = co->co_consts;
1217 n = PyTuple_GET_SIZE(constants);
1218 for (i = 0; i < n; i++) {
1219 tmp = PyTuple_GET_ITEM(constants, i);
1220 if (PyCode_Check(tmp))
1221 update_code_filenames((PyCodeObject *)tmp,
1222 oldname, newname);
1223 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001224}
1225
1226static int
1227update_compiled_module(PyCodeObject *co, char *pathname)
1228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 newname = PyUnicode_DecodeFSDefault(pathname);
1232 if (newname == NULL)
1233 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (!PyUnicode_Compare(co->co_filename, newname)) {
1236 Py_DECREF(newname);
1237 return 0;
1238 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 oldname = co->co_filename;
1241 Py_INCREF(oldname);
1242 update_code_filenames(co, oldname, newname);
1243 Py_DECREF(oldname);
1244 Py_DECREF(newname);
1245 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001246}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247
1248/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001249 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1250 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001251
Guido van Rossum79f25d91997-04-29 20:08:16 +00001252static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001253load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 struct stat st;
1256 FILE *fpc;
1257 char buf[MAXPATHLEN+1];
1258 char *cpathname;
1259 PyCodeObject *co;
1260 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (fstat(fileno(fp), &st) != 0) {
1263 PyErr_Format(PyExc_RuntimeError,
1264 "unable to get file status from '%s'",
1265 pathname);
1266 return NULL;
1267 }
Fred Drake4c82b232000-06-30 16:18:57 +00001268#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* Python's .pyc timestamp handling presumes that the timestamp fits
1270 in 4 bytes. This will be fine until sometime in the year 2038,
1271 when a 4-byte signed time_t will overflow.
1272 */
1273 if (st.st_mtime >> 32) {
1274 PyErr_SetString(PyExc_OverflowError,
1275 "modification time overflows a 4 byte field");
1276 return NULL;
1277 }
Fred Drake4c82b232000-06-30 16:18:57 +00001278#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 cpathname = make_compiled_pathname(
1280 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1281 if (cpathname != NULL &&
1282 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1283 co = read_compiled_module(cpathname, fpc);
1284 fclose(fpc);
1285 if (co == NULL)
1286 return NULL;
1287 if (update_compiled_module(co, pathname) < 0)
1288 return NULL;
1289 if (Py_VerboseFlag)
1290 PySys_WriteStderr("import %s # precompiled from %s\n",
1291 name, cpathname);
1292 pathname = cpathname;
1293 }
1294 else {
1295 co = parse_source_module(pathname, fp);
1296 if (co == NULL)
1297 return NULL;
1298 if (Py_VerboseFlag)
1299 PySys_WriteStderr("import %s # from %s\n",
1300 name, pathname);
1301 if (cpathname) {
1302 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1303 if (ro == NULL || !PyObject_IsTrue(ro))
1304 write_compiled_module(co, cpathname, &st);
1305 }
1306 }
1307 m = PyImport_ExecCodeModuleWithPathnames(
1308 name, (PyObject *)co, pathname, cpathname);
1309 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001312}
1313
Christian Heimes3b06e532008-01-07 20:12:44 +00001314/* Get source file -> unicode or None
1315 * Returns the path to the py file if available, else the given path
1316 */
1317static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001318get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 char py[MAXPATHLEN + 1];
1321 Py_ssize_t len;
1322 PyObject *u;
1323 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (!file || !*file) {
1326 Py_RETURN_NONE;
1327 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 len = strlen(file);
1330 /* match '*.py?' */
1331 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1332 return PyUnicode_DecodeFSDefault(file);
1333 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* Start by trying to turn PEP 3147 path into source path. If that
1336 * fails, just chop off the trailing character, i.e. legacy pyc path
1337 * to py.
1338 */
1339 if (make_source_pathname(file, py) == NULL) {
1340 strncpy(py, file, len-1);
1341 py[len-1] = '\0';
1342 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (stat(py, &statbuf) == 0 &&
1345 S_ISREG(statbuf.st_mode)) {
1346 u = PyUnicode_DecodeFSDefault(py);
1347 }
1348 else {
1349 u = PyUnicode_DecodeFSDefault(file);
1350 }
1351 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001352}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001353
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001354/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001355static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1356static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001358static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001359
1360/* Load a package and return its module object WITH INCREMENTED
1361 REFERENCE COUNT */
1362
1363static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001364load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 PyObject *m, *d;
1367 PyObject *file = NULL;
1368 PyObject *path = NULL;
1369 int err;
1370 char buf[MAXPATHLEN+1];
1371 FILE *fp = NULL;
1372 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 m = PyImport_AddModule(name);
1375 if (m == NULL)
1376 return NULL;
1377 if (Py_VerboseFlag)
1378 PySys_WriteStderr("import %s # directory %s\n",
1379 name, pathname);
1380 d = PyModule_GetDict(m);
1381 file = get_sourcefile(pathname);
1382 if (file == NULL)
1383 goto error;
1384 path = Py_BuildValue("[O]", file);
1385 if (path == NULL)
1386 goto error;
1387 err = PyDict_SetItemString(d, "__file__", file);
1388 if (err == 0)
1389 err = PyDict_SetItemString(d, "__path__", path);
1390 if (err != 0)
1391 goto error;
1392 buf[0] = '\0';
1393 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1394 if (fdp == NULL) {
1395 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1396 PyErr_Clear();
1397 Py_INCREF(m);
1398 }
1399 else
1400 m = NULL;
1401 goto cleanup;
1402 }
1403 m = load_module(name, fp, buf, fdp->type, NULL);
1404 if (fp != NULL)
1405 fclose(fp);
1406 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001407
1408 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001410 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 Py_XDECREF(path);
1412 Py_XDECREF(file);
1413 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001414}
1415
1416
1417/* Helper to test for built-in module */
1418
1419static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001420is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 int i;
1423 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1424 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1425 if (PyImport_Inittab[i].initfunc == NULL)
1426 return -1;
1427 else
1428 return 1;
1429 }
1430 }
1431 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001432}
1433
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001434
Just van Rossum52e14d62002-12-30 22:08:05 +00001435/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1436 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001437 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001438 that can handle the path item. Return None if no hook could;
1439 this tells our caller it should fall back to the builtin
1440 import mechanism. Cache the result in path_importer_cache.
1441 Returns a borrowed reference. */
1442
1443static PyObject *
1444get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyObject *importer;
1448 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 /* These conditions are the caller's responsibility: */
1451 assert(PyList_Check(path_hooks));
1452 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 nhooks = PyList_Size(path_hooks);
1455 if (nhooks < 0)
1456 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 importer = PyDict_GetItem(path_importer_cache, p);
1459 if (importer != NULL)
1460 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* set path_importer_cache[p] to None to avoid recursion */
1463 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1464 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 for (j = 0; j < nhooks; j++) {
1467 PyObject *hook = PyList_GetItem(path_hooks, j);
1468 if (hook == NULL)
1469 return NULL;
1470 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1471 if (importer != NULL)
1472 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1475 return NULL;
1476 }
1477 PyErr_Clear();
1478 }
1479 if (importer == NULL) {
1480 importer = PyObject_CallFunctionObjArgs(
1481 (PyObject *)&PyNullImporter_Type, p, NULL
1482 );
1483 if (importer == NULL) {
1484 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1485 PyErr_Clear();
1486 return Py_None;
1487 }
1488 }
1489 }
1490 if (importer != NULL) {
1491 int err = PyDict_SetItem(path_importer_cache, p, importer);
1492 Py_DECREF(importer);
1493 if (err != 0)
1494 return NULL;
1495 }
1496 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001497}
1498
Christian Heimes9cd17752007-11-18 19:35:23 +00001499PyAPI_FUNC(PyObject *)
1500PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1504 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1505 importer = get_path_importer(path_importer_cache,
1506 path_hooks, path);
1507 }
1508 }
1509 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1510 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001511}
1512
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001513/* Search the path (default sys.path) for a module. Return the
1514 corresponding filedescr struct, and (via return arguments) the
1515 pathname and an open file. Return NULL if the module is not found. */
1516
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001517#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001518extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001520#endif
1521
Martin v. Löwis18e16552006-02-15 17:27:45 +00001522static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001523static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001524static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001525
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001526static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001527find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_ssize_t i, npath;
1531 size_t len, namelen;
1532 struct filedescr *fdp = NULL;
1533 char *filemode;
1534 FILE *fp = NULL;
1535 PyObject *path_hooks, *path_importer_cache;
1536 struct stat statbuf;
1537 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1538 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1539 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1540 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001541#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 size_t saved_len;
1543 size_t saved_namelen;
1544 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001545#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (p_loader != NULL)
1547 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (strlen(subname) > MAXPATHLEN) {
1550 PyErr_SetString(PyExc_OverflowError,
1551 "module name is too long");
1552 return NULL;
1553 }
1554 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 /* sys.meta_path import hook */
1557 if (p_loader != NULL) {
1558 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 meta_path = PySys_GetObject("meta_path");
1561 if (meta_path == NULL || !PyList_Check(meta_path)) {
1562 PyErr_SetString(PyExc_ImportError,
1563 "sys.meta_path must be a list of "
1564 "import hooks");
1565 return NULL;
1566 }
1567 Py_INCREF(meta_path); /* zap guard */
1568 npath = PyList_Size(meta_path);
1569 for (i = 0; i < npath; i++) {
1570 PyObject *loader;
1571 PyObject *hook = PyList_GetItem(meta_path, i);
1572 loader = PyObject_CallMethod(hook, "find_module",
1573 "sO", fullname,
1574 path != NULL ?
1575 path : Py_None);
1576 if (loader == NULL) {
1577 Py_DECREF(meta_path);
1578 return NULL; /* true error */
1579 }
1580 if (loader != Py_None) {
1581 /* a loader was found */
1582 *p_loader = loader;
1583 Py_DECREF(meta_path);
1584 return &importhookdescr;
1585 }
1586 Py_DECREF(loader);
1587 }
1588 Py_DECREF(meta_path);
1589 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (find_frozen(fullname) != NULL) {
1592 strcpy(buf, fullname);
1593 return &fd_frozen;
1594 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 if (path == NULL) {
1597 if (is_builtin(name)) {
1598 strcpy(buf, name);
1599 return &fd_builtin;
1600 }
Guido van Rossumac279101996-08-22 23:10:58 +00001601#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1603 if (fp != NULL) {
1604 *p_fp = fp;
1605 return fdp;
1606 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001607#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 path = PySys_GetObject("path");
1609 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 if (path == NULL || !PyList_Check(path)) {
1612 PyErr_SetString(PyExc_ImportError,
1613 "sys.path must be a list of directory names");
1614 return NULL;
1615 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 path_hooks = PySys_GetObject("path_hooks");
1618 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1619 PyErr_SetString(PyExc_ImportError,
1620 "sys.path_hooks must be a list of "
1621 "import hooks");
1622 return NULL;
1623 }
1624 path_importer_cache = PySys_GetObject("path_importer_cache");
1625 if (path_importer_cache == NULL ||
1626 !PyDict_Check(path_importer_cache)) {
1627 PyErr_SetString(PyExc_ImportError,
1628 "sys.path_importer_cache must be a dict");
1629 return NULL;
1630 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 npath = PyList_Size(path);
1633 namelen = strlen(name);
1634 for (i = 0; i < npath; i++) {
1635 PyObject *v = PyList_GetItem(path, i);
1636 PyObject *origv = v;
1637 const char *base;
1638 Py_ssize_t size;
1639 if (!v)
1640 return NULL;
1641 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001642 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (v == NULL)
1644 return NULL;
1645 }
1646 else if (!PyBytes_Check(v))
1647 continue;
1648 else
1649 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 base = PyBytes_AS_STRING(v);
1652 size = PyBytes_GET_SIZE(v);
1653 len = size;
1654 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1655 Py_DECREF(v);
1656 continue; /* Too long */
1657 }
1658 strcpy(buf, base);
1659 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (strlen(buf) != len) {
1662 continue; /* v contains '\0' */
1663 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 /* sys.path_hooks import hook */
1666 if (p_loader != NULL) {
1667 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 importer = get_path_importer(path_importer_cache,
1670 path_hooks, origv);
1671 if (importer == NULL) {
1672 return NULL;
1673 }
1674 /* Note: importer is a borrowed reference */
1675 if (importer != Py_None) {
1676 PyObject *loader;
1677 loader = PyObject_CallMethod(importer,
1678 "find_module",
1679 "s", fullname);
1680 if (loader == NULL)
1681 return NULL; /* error */
1682 if (loader != Py_None) {
1683 /* a loader was found */
1684 *p_loader = loader;
1685 return &importhookdescr;
1686 }
1687 Py_DECREF(loader);
1688 continue;
1689 }
1690 }
1691 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001694#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001696#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 )
1698 buf[len++] = SEP;
1699 strcpy(buf+len, name);
1700 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* Check for package import (buf holds a directory name,
1703 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001704#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (stat(buf, &statbuf) == 0 && /* it exists */
1706 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1707 case_ok(buf, len, namelen, name)) { /* case matches */
1708 if (find_init_module(buf)) { /* and has __init__.py */
1709 return &fd_package;
1710 }
1711 else {
1712 char warnstr[MAXPATHLEN+80];
1713 sprintf(warnstr, "Not importing directory "
1714 "'%.*s': missing __init__.py",
1715 MAXPATHLEN, buf);
1716 if (PyErr_WarnEx(PyExc_ImportWarning,
1717 warnstr, 1)) {
1718 return NULL;
1719 }
1720 }
1721 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001722#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001723#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 /* take a snapshot of the module spec for restoration
1725 * after the 8 character DLL hackery
1726 */
1727 saved_buf = strdup(buf);
1728 saved_len = len;
1729 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001730#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001732#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* OS/2 limits DLLs to 8 character names (w/o
1734 extension)
1735 * so if the name is longer than that and its a
1736 * dynamically loaded module we're going to try,
1737 * truncate the name before trying
1738 */
1739 if (strlen(subname) > 8) {
1740 /* is this an attempt to load a C extension? */
1741 const struct filedescr *scan;
1742 scan = _PyImport_DynLoadFiletab;
1743 while (scan->suffix != NULL) {
1744 if (!strcmp(scan->suffix, fdp->suffix))
1745 break;
1746 else
1747 scan++;
1748 }
1749 if (scan->suffix != NULL) {
1750 /* yes, so truncate the name */
1751 namelen = 8;
1752 len -= strlen(subname) - namelen;
1753 buf[len] = '\0';
1754 }
1755 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001756#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 strcpy(buf+len, fdp->suffix);
1758 if (Py_VerboseFlag > 1)
1759 PySys_WriteStderr("# trying %s\n", buf);
1760 filemode = fdp->mode;
1761 if (filemode[0] == 'U')
1762 filemode = "r" PY_STDIOTEXTMODE;
1763 fp = fopen(buf, filemode);
1764 if (fp != NULL) {
1765 if (case_ok(buf, len, namelen, name))
1766 break;
1767 else { /* continue search */
1768 fclose(fp);
1769 fp = NULL;
1770 }
1771 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001772#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 /* restore the saved snapshot */
1774 strcpy(buf, saved_buf);
1775 len = saved_len;
1776 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001777#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001779#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* don't need/want the module name snapshot anymore */
1781 if (saved_buf)
1782 {
1783 free(saved_buf);
1784 saved_buf = NULL;
1785 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001786#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (fp != NULL)
1788 break;
1789 }
1790 if (fp == NULL) {
1791 PyErr_Format(PyExc_ImportError,
1792 "No module named %.200s", name);
1793 return NULL;
1794 }
1795 *p_fp = fp;
1796 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001797}
1798
Martin v. Löwis18e16552006-02-15 17:27:45 +00001799/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001800 * The arguments here are tricky, best shown by example:
1801 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1802 * ^ ^ ^ ^
1803 * |--------------------- buf ---------------------|
1804 * |------------------- len ------------------|
1805 * |------ name -------|
1806 * |----- namelen -----|
1807 * buf is the full path, but len only counts up to (& exclusive of) the
1808 * extension. name is the module name, also exclusive of extension.
1809 *
1810 * We've already done a successful stat() or fopen() on buf, so know that
1811 * there's some match, possibly case-insensitive.
1812 *
Tim Peters50d8d372001-02-28 05:34:27 +00001813 * case_ok() is to return 1 if there's a case-sensitive match for
1814 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1815 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001816 *
Tim Peters50d8d372001-02-28 05:34:27 +00001817 * case_ok() is used to implement case-sensitive import semantics even
1818 * on platforms with case-insensitive filesystems. It's trivial to implement
1819 * for case-sensitive filesystems. It's pretty much a cross-platform
1820 * nightmare for systems with case-insensitive filesystems.
1821 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001822
Tim Peters50d8d372001-02-28 05:34:27 +00001823/* First we may need a pile of platform-specific header files; the sequence
1824 * of #if's here should match the sequence in the body of case_ok().
1825 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001826#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001827#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001828
Tim Peters50d8d372001-02-28 05:34:27 +00001829#elif defined(DJGPP)
1830#include <dir.h>
1831
Jason Tishler7961aa62005-05-20 00:56:54 +00001832#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001833#include <sys/types.h>
1834#include <dirent.h>
1835
Andrew MacIntyred9400542002-02-26 11:41:34 +00001836#elif defined(PYOS_OS2)
1837#define INCL_DOS
1838#define INCL_DOSERRORS
1839#define INCL_NOPMAPI
1840#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001841#endif
1842
Guido van Rossum0980bd91998-02-13 17:18:36 +00001843static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001844case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001845{
Tim Peters50d8d372001-02-28 05:34:27 +00001846/* Pick a platform-specific implementation; the sequence of #if's here should
1847 * match the sequence just above.
1848 */
1849
Jason Tishler7961aa62005-05-20 00:56:54 +00001850/* MS_WINDOWS */
1851#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 WIN32_FIND_DATA data;
1853 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (Py_GETENV("PYTHONCASEOK") != NULL)
1856 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 h = FindFirstFile(buf, &data);
1859 if (h == INVALID_HANDLE_VALUE) {
1860 PyErr_Format(PyExc_NameError,
1861 "Can't find file for module %.100s\n(filename %.300s)",
1862 name, buf);
1863 return 0;
1864 }
1865 FindClose(h);
1866 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001867
1868/* DJGPP */
1869#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 struct ffblk ffblk;
1871 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (Py_GETENV("PYTHONCASEOK") != NULL)
1874 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1877 if (done) {
1878 PyErr_Format(PyExc_NameError,
1879 "Can't find file for module %.100s\n(filename %.300s)",
1880 name, buf);
1881 return 0;
1882 }
1883 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001884
Jason Tishler7961aa62005-05-20 00:56:54 +00001885/* new-fangled macintosh (macosx) or Cygwin */
1886#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 DIR *dirp;
1888 struct dirent *dp;
1889 char dirname[MAXPATHLEN + 1];
1890 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (Py_GETENV("PYTHONCASEOK") != NULL)
1893 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* Copy the dir component into dirname; substitute "." if empty */
1896 if (dirlen <= 0) {
1897 dirname[0] = '.';
1898 dirname[1] = '\0';
1899 }
1900 else {
1901 assert(dirlen <= MAXPATHLEN);
1902 memcpy(dirname, buf, dirlen);
1903 dirname[dirlen] = '\0';
1904 }
1905 /* Open the directory and search the entries for an exact match. */
1906 dirp = opendir(dirname);
1907 if (dirp) {
1908 char *nameWithExt = buf + len - namelen;
1909 while ((dp = readdir(dirp)) != NULL) {
1910 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001911#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001913#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001915#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (thislen >= namelen &&
1917 strcmp(dp->d_name, nameWithExt) == 0) {
1918 (void)closedir(dirp);
1919 return 1; /* Found */
1920 }
1921 }
1922 (void)closedir(dirp);
1923 }
1924 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001925
Andrew MacIntyred9400542002-02-26 11:41:34 +00001926/* OS/2 */
1927#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 HDIR hdir = 1;
1929 ULONG srchcnt = 1;
1930 FILEFINDBUF3 ffbuf;
1931 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (Py_GETENV("PYTHONCASEOK") != NULL)
1934 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 rc = DosFindFirst(buf,
1937 &hdir,
1938 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1939 &ffbuf, sizeof(ffbuf),
1940 &srchcnt,
1941 FIL_STANDARD);
1942 if (rc != NO_ERROR)
1943 return 0;
1944 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001945
Tim Peters50d8d372001-02-28 05:34:27 +00001946/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1947#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001949
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001950#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001951}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001952
Victor Stinnerf52b7052010-08-14 17:06:04 +00001953/* Call _wfopen() on Windows, or fopen() otherwise. Return the new file
1954 object on success, or NULL if the file cannot be open or (if
1955 PyErr_Occurred()) on unicode error */
1956
1957FILE*
1958_Py_fopen(PyObject *unicode, const char *mode)
1959{
1960#ifdef MS_WINDOWS
1961 wchar_t path[MAXPATHLEN+1];
1962 wchar_t wmode[10];
1963 Py_ssize_t len;
1964 int usize;
1965
1966 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
1967 if (len == -1)
1968 return NULL;
1969 path[len] = L'\0';
1970
1971 usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
1972 if (usize == 0)
1973 return NULL;
1974
1975 return _wfopen(path, wmode);
1976#else
1977 FILE *f;
1978 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
1979 if (bytes == NULL)
1980 return NULL;
1981 f = fopen(PyBytes_AS_STRING(bytes), mode);
1982 Py_DECREF(bytes);
1983 return f;
1984#endif
1985}
Guido van Rossum0980bd91998-02-13 17:18:36 +00001986
Guido van Rossum197346f1997-10-31 18:38:52 +00001987#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001988
1989/* Call _wstat() on Windows, or stat() otherwise. Only fill st_mode
1990 attribute on Windows. Return 0 on success, -1 on stat error or (if
1991 PyErr_Occurred()) unicode error. */
1992
1993int
1994_Py_stat(PyObject *unicode, struct stat *statbuf)
1995{
1996#ifdef MS_WINDOWS
1997 wchar_t path[MAXPATHLEN+1];
1998 Py_ssize_t len;
1999 int err;
2000 struct _stat wstatbuf;
2001
Victor Stinner8a79dcc2010-08-14 16:59:08 +00002002 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
Victor Stinner4f4402c2010-08-14 14:50:26 +00002003 if (len == -1)
2004 return -1;
Victor Stinner8a79dcc2010-08-14 16:59:08 +00002005 path[len] = L'\0';
2006
Victor Stinner4f4402c2010-08-14 14:50:26 +00002007 err = _wstat(path, &wstatbuf);
2008 if (!err)
2009 statbuf->st_mode = wstatbuf.st_mode;
2010 return err;
2011#else
2012 int ret;
2013 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
2014 if (bytes == NULL)
2015 return -1;
2016 ret = stat(PyBytes_AS_STRING(bytes), statbuf);
2017 Py_DECREF(bytes);
2018 return ret;
2019#endif
2020}
2021
Guido van Rossum197346f1997-10-31 18:38:52 +00002022/* Helper to look for __init__.py or __init__.py[co] in potential package */
2023static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002024find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 const size_t save_len = strlen(buf);
2027 size_t i = save_len;
2028 char *pname; /* pointer to start of __init__ */
2029 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031/* For calling case_ok(buf, len, namelen, name):
2032 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2033 * ^ ^ ^ ^
2034 * |--------------------- buf ---------------------|
2035 * |------------------- len ------------------|
2036 * |------ name -------|
2037 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002038 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (save_len + 13 >= MAXPATHLEN)
2040 return 0;
2041 buf[i++] = SEP;
2042 pname = buf + i;
2043 strcpy(pname, "__init__.py");
2044 if (stat(buf, &statbuf) == 0) {
2045 if (case_ok(buf,
2046 save_len + 9, /* len("/__init__") */
2047 8, /* len("__init__") */
2048 pname)) {
2049 buf[save_len] = '\0';
2050 return 1;
2051 }
2052 }
2053 i += strlen(pname);
2054 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2055 if (stat(buf, &statbuf) == 0) {
2056 if (case_ok(buf,
2057 save_len + 9, /* len("/__init__") */
2058 8, /* len("__init__") */
2059 pname)) {
2060 buf[save_len] = '\0';
2061 return 1;
2062 }
2063 }
2064 buf[save_len] = '\0';
2065 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002066}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002067
Guido van Rossum197346f1997-10-31 18:38:52 +00002068#endif /* HAVE_STAT */
2069
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070
Tim Petersdbd9ba62000-07-09 03:09:57 +00002071static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002072
Victor Stinner44c6c152010-08-09 00:59:10 +00002073static PyObject*
2074load_builtin(char *name, char *pathname, int type)
2075{
2076 PyObject *m, *modules;
2077 int err;
2078
2079 if (pathname != NULL && pathname[0] != '\0')
2080 name = pathname;
2081
2082 if (type == C_BUILTIN)
2083 err = init_builtin(name);
2084 else
2085 err = PyImport_ImportFrozenModule(name);
2086 if (err < 0)
2087 return NULL;
2088 if (err == 0) {
2089 PyErr_Format(PyExc_ImportError,
2090 "Purported %s module %.200s not found",
2091 type == C_BUILTIN ?
2092 "builtin" : "frozen",
2093 name);
2094 return NULL;
2095 }
2096
2097 modules = PyImport_GetModuleDict();
2098 m = PyDict_GetItemString(modules, name);
2099 if (m == NULL) {
2100 PyErr_Format(
2101 PyExc_ImportError,
2102 "%s module %.200s not properly initialized",
2103 type == C_BUILTIN ?
2104 "builtin" : "frozen",
2105 name);
2106 return NULL;
2107 }
2108 Py_INCREF(m);
2109 return m;
2110}
2111
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002112/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002113 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002114
Guido van Rossum79f25d91997-04-29 20:08:16 +00002115static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002116load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 /* First check that there's an open file (if we need one) */
2121 switch (type) {
2122 case PY_SOURCE:
2123 case PY_COMPILED:
2124 if (fp == NULL) {
2125 PyErr_Format(PyExc_ValueError,
2126 "file object required for import (type code %d)",
2127 type);
2128 return NULL;
2129 }
2130 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 case PY_SOURCE:
2135 m = load_source_module(name, pathname, fp);
2136 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 case PY_COMPILED:
2139 m = load_compiled_module(name, pathname, fp);
2140 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002141
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002142#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 case C_EXTENSION:
2144 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2145 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002146#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 case PKG_DIRECTORY:
2149 m = load_package(name, pathname);
2150 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 case C_BUILTIN:
2153 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002154 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 case IMP_HOOK: {
2158 if (loader == NULL) {
2159 PyErr_SetString(PyExc_ImportError,
2160 "import hook without loader");
2161 return NULL;
2162 }
2163 m = PyObject_CallMethod(loader, "load_module", "s", name);
2164 break;
2165 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 default:
2168 PyErr_Format(PyExc_ImportError,
2169 "Don't know how to import %.200s (type code %d)",
2170 name, type);
2171 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002176}
2177
2178
2179/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002180 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002181 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002182
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002183static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002184init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (_PyImport_FindExtension(name, name) != NULL)
2189 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 for (p = PyImport_Inittab; p->name != NULL; p++) {
2192 PyObject *mod;
2193 if (strcmp(name, p->name) == 0) {
2194 if (p->initfunc == NULL) {
2195 PyErr_Format(PyExc_ImportError,
2196 "Cannot re-init internal module %.200s",
2197 name);
2198 return -1;
2199 }
2200 if (Py_VerboseFlag)
2201 PySys_WriteStderr("import %s # builtin\n", name);
2202 mod = (*p->initfunc)();
2203 if (mod == 0)
2204 return -1;
2205 if (_PyImport_FixupExtension(mod, name, name) < 0)
2206 return -1;
2207 /* FixupExtension has put the module into sys.modules,
2208 so we can release our own reference. */
2209 Py_DECREF(mod);
2210 return 1;
2211 }
2212 }
2213 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002214}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002215
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002216
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002217/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002218
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002219static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002220find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (!name)
2225 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 for (p = PyImport_FrozenModules; ; p++) {
2228 if (p->name == NULL)
2229 return NULL;
2230 if (strcmp(p->name, name) == 0)
2231 break;
2232 }
2233 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002234}
2235
Guido van Rossum79f25d91997-04-29 20:08:16 +00002236static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002237get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 struct _frozen *p = find_frozen(name);
2240 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if (p == NULL) {
2243 PyErr_Format(PyExc_ImportError,
2244 "No such frozen object named %.200s",
2245 name);
2246 return NULL;
2247 }
2248 if (p->code == NULL) {
2249 PyErr_Format(PyExc_ImportError,
2250 "Excluded frozen object named %.200s",
2251 name);
2252 return NULL;
2253 }
2254 size = p->size;
2255 if (size < 0)
2256 size = -size;
2257 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002258}
2259
Brett Cannon8d110132009-03-15 02:20:16 +00002260static PyObject *
2261is_frozen_package(char *name)
2262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 struct _frozen *p = find_frozen(name);
2264 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (p == NULL) {
2267 PyErr_Format(PyExc_ImportError,
2268 "No such frozen object named %.200s",
2269 name);
2270 return NULL;
2271 }
Brett Cannon8d110132009-03-15 02:20:16 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 if (size < 0)
2276 Py_RETURN_TRUE;
2277 else
2278 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002279}
2280
2281
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002282/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002283 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002284 an exception set if the initialization failed.
2285 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002286
2287int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002288PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 struct _frozen *p = find_frozen(name);
2291 PyObject *co;
2292 PyObject *m;
2293 int ispackage;
2294 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 if (p == NULL)
2297 return 0;
2298 if (p->code == NULL) {
2299 PyErr_Format(PyExc_ImportError,
2300 "Excluded frozen object named %.200s",
2301 name);
2302 return -1;
2303 }
2304 size = p->size;
2305 ispackage = (size < 0);
2306 if (ispackage)
2307 size = -size;
2308 if (Py_VerboseFlag)
2309 PySys_WriteStderr("import %s # frozen%s\n",
2310 name, ispackage ? " package" : "");
2311 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2312 if (co == NULL)
2313 return -1;
2314 if (!PyCode_Check(co)) {
2315 PyErr_Format(PyExc_TypeError,
2316 "frozen object %.200s is not a code object",
2317 name);
2318 goto err_return;
2319 }
2320 if (ispackage) {
2321 /* Set __path__ to the package name */
2322 PyObject *d, *s, *l;
2323 int err;
2324 m = PyImport_AddModule(name);
2325 if (m == NULL)
2326 goto err_return;
2327 d = PyModule_GetDict(m);
2328 s = PyUnicode_InternFromString(name);
2329 if (s == NULL)
2330 goto err_return;
2331 l = PyList_New(1);
2332 if (l == NULL) {
2333 Py_DECREF(s);
2334 goto err_return;
2335 }
2336 PyList_SET_ITEM(l, 0, s);
2337 err = PyDict_SetItemString(d, "__path__", l);
2338 Py_DECREF(l);
2339 if (err != 0)
2340 goto err_return;
2341 }
2342 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2343 if (m == NULL)
2344 goto err_return;
2345 Py_DECREF(co);
2346 Py_DECREF(m);
2347 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002348err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 Py_DECREF(co);
2350 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002351}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002352
2353
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002354/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002355 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002356
Guido van Rossum79f25d91997-04-29 20:08:16 +00002357PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002358PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 PyObject *pname;
2361 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 pname = PyUnicode_FromString(name);
2364 if (pname == NULL)
2365 return NULL;
2366 result = PyImport_Import(pname);
2367 Py_DECREF(pname);
2368 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002369}
2370
Christian Heimes072c0f12008-01-03 23:01:04 +00002371/* Import a module without blocking
2372 *
2373 * At first it tries to fetch the module from sys.modules. If the module was
2374 * never loaded before it loads it with PyImport_ImportModule() unless another
2375 * thread holds the import lock. In the latter case the function raises an
2376 * ImportError instead of blocking.
2377 *
2378 * Returns the module object with incremented ref count.
2379 */
2380PyObject *
2381PyImport_ImportModuleNoBlock(const char *name)
2382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyObject *result;
2384 PyObject *modules;
2385 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* Try to get the module from sys.modules[name] */
2388 modules = PyImport_GetModuleDict();
2389 if (modules == NULL)
2390 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 result = PyDict_GetItemString(modules, name);
2393 if (result != NULL) {
2394 Py_INCREF(result);
2395 return result;
2396 }
2397 else {
2398 PyErr_Clear();
2399 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002400#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 /* check the import lock
2402 * me might be -1 but I ignore the error here, the lock function
2403 * takes care of the problem */
2404 me = PyThread_get_thread_ident();
2405 if (import_lock_thread == -1 || import_lock_thread == me) {
2406 /* no thread or me is holding the lock */
2407 return PyImport_ImportModule(name);
2408 }
2409 else {
2410 PyErr_Format(PyExc_ImportError,
2411 "Failed to import %.200s because the import lock"
2412 "is held by another thread.",
2413 name);
2414 return NULL;
2415 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002416#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002418#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002419}
2420
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002421/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002422static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002424static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002426static int mark_miss(char *name);
2427static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002429static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002430
2431/* The Magnum Opus of dotted-name import :-) */
2432
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002433static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002434import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 char buf[MAXPATHLEN+1];
2438 Py_ssize_t buflen = 0;
2439 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002442#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002444#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 ) {
2446 PyErr_SetString(PyExc_ImportError,
2447 "Import by filename is not supported.");
2448 return NULL;
2449 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 parent = get_parent(globals, buf, &buflen, level);
2452 if (parent == NULL)
2453 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002454
Benjamin Peterson556d8002010-06-27 22:37:28 +00002455 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2456 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 if (head == NULL)
2458 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 tail = head;
2461 Py_INCREF(tail);
2462 while (name) {
2463 next = load_next(tail, tail, &name, buf, &buflen);
2464 Py_DECREF(tail);
2465 if (next == NULL) {
2466 Py_DECREF(head);
2467 return NULL;
2468 }
2469 tail = next;
2470 }
2471 if (tail == Py_None) {
2472 /* If tail is Py_None, both get_parent and load_next found
2473 an empty module name: someone called __import__("") or
2474 doctored faulty bytecode */
2475 Py_DECREF(tail);
2476 Py_DECREF(head);
2477 PyErr_SetString(PyExc_ValueError,
2478 "Empty module name");
2479 return NULL;
2480 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 if (fromlist != NULL) {
2483 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2484 fromlist = NULL;
2485 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 if (fromlist == NULL) {
2488 Py_DECREF(tail);
2489 return head;
2490 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 Py_DECREF(head);
2493 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2494 Py_DECREF(tail);
2495 return NULL;
2496 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002499}
2500
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002501PyObject *
2502PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 PyObject *result;
2506 _PyImport_AcquireLock();
2507 result = import_module_level(name, globals, locals, fromlist, level);
2508 if (_PyImport_ReleaseLock() < 0) {
2509 Py_XDECREF(result);
2510 PyErr_SetString(PyExc_RuntimeError,
2511 "not holding the import lock");
2512 return NULL;
2513 }
2514 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002515}
2516
Fred Drake87590902004-05-28 20:21:36 +00002517/* Return the package that an import is being performed in. If globals comes
2518 from the module foo.bar.bat (not itself a package), this returns the
2519 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002520 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002521
2522 The *name* of the returned package is returned in buf, with the length of
2523 the name in *p_buflen.
2524
2525 If globals doesn't come from a package or a module in a package, or a
2526 corresponding entry is not found in sys.modules, Py_None is returned.
2527*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002528static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002529get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 static PyObject *namestr = NULL;
2532 static PyObject *pathstr = NULL;
2533 static PyObject *pkgstr = NULL;
2534 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2535 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (globals == NULL || !PyDict_Check(globals) || !level)
2538 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 if (namestr == NULL) {
2541 namestr = PyUnicode_InternFromString("__name__");
2542 if (namestr == NULL)
2543 return NULL;
2544 }
2545 if (pathstr == NULL) {
2546 pathstr = PyUnicode_InternFromString("__path__");
2547 if (pathstr == NULL)
2548 return NULL;
2549 }
2550 if (pkgstr == NULL) {
2551 pkgstr = PyUnicode_InternFromString("__package__");
2552 if (pkgstr == NULL)
2553 return NULL;
2554 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 *buf = '\0';
2557 *p_buflen = 0;
2558 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 if ((pkgname != NULL) && (pkgname != Py_None)) {
2561 /* __package__ is set, so use it */
2562 char *pkgname_str;
2563 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (!PyUnicode_Check(pkgname)) {
2566 PyErr_SetString(PyExc_ValueError,
2567 "__package__ set to non-string");
2568 return NULL;
2569 }
2570 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2571 if (len == 0) {
2572 if (level > 0) {
2573 PyErr_SetString(PyExc_ValueError,
2574 "Attempted relative import in non-package");
2575 return NULL;
2576 }
2577 return Py_None;
2578 }
2579 if (len > MAXPATHLEN) {
2580 PyErr_SetString(PyExc_ValueError,
2581 "Package name too long");
2582 return NULL;
2583 }
2584 strcpy(buf, pkgname_str);
2585 } else {
2586 /* __package__ not set, so figure it out and set it */
2587 modname = PyDict_GetItem(globals, namestr);
2588 if (modname == NULL || !PyUnicode_Check(modname))
2589 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 modpath = PyDict_GetItem(globals, pathstr);
2592 if (modpath != NULL) {
2593 /* __path__ is set, so modname is already the package name */
2594 char *modname_str;
2595 Py_ssize_t len;
2596 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2599 if (len > MAXPATHLEN) {
2600 PyErr_SetString(PyExc_ValueError,
2601 "Module name too long");
2602 return NULL;
2603 }
2604 strcpy(buf, modname_str);
2605 error = PyDict_SetItem(globals, pkgstr, modname);
2606 if (error) {
2607 PyErr_SetString(PyExc_ValueError,
2608 "Could not set __package__");
2609 return NULL;
2610 }
2611 } else {
2612 /* Normal module, so work out the package name if any */
2613 char *start = _PyUnicode_AsString(modname);
2614 char *lastdot = strrchr(start, '.');
2615 size_t len;
2616 int error;
2617 if (lastdot == NULL && level > 0) {
2618 PyErr_SetString(PyExc_ValueError,
2619 "Attempted relative import in non-package");
2620 return NULL;
2621 }
2622 if (lastdot == NULL) {
2623 error = PyDict_SetItem(globals, pkgstr, Py_None);
2624 if (error) {
2625 PyErr_SetString(PyExc_ValueError,
2626 "Could not set __package__");
2627 return NULL;
2628 }
2629 return Py_None;
2630 }
2631 len = lastdot - start;
2632 if (len >= MAXPATHLEN) {
2633 PyErr_SetString(PyExc_ValueError,
2634 "Module name too long");
2635 return NULL;
2636 }
2637 strncpy(buf, start, len);
2638 buf[len] = '\0';
2639 pkgname = PyUnicode_FromString(buf);
2640 if (pkgname == NULL) {
2641 return NULL;
2642 }
2643 error = PyDict_SetItem(globals, pkgstr, pkgname);
2644 Py_DECREF(pkgname);
2645 if (error) {
2646 PyErr_SetString(PyExc_ValueError,
2647 "Could not set __package__");
2648 return NULL;
2649 }
2650 }
2651 }
2652 while (--level > 0) {
2653 char *dot = strrchr(buf, '.');
2654 if (dot == NULL) {
2655 PyErr_SetString(PyExc_ValueError,
2656 "Attempted relative import beyond "
2657 "toplevel package");
2658 return NULL;
2659 }
2660 *dot = '\0';
2661 }
2662 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 modules = PyImport_GetModuleDict();
2665 parent = PyDict_GetItemString(modules, buf);
2666 if (parent == NULL) {
2667 if (orig_level < 1) {
2668 PyObject *err_msg = PyBytes_FromFormat(
2669 "Parent module '%.200s' not found "
2670 "while handling absolute import", buf);
2671 if (err_msg == NULL) {
2672 return NULL;
2673 }
2674 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2675 PyBytes_AsString(err_msg), 1)) {
2676 *buf = '\0';
2677 *p_buflen = 0;
2678 parent = Py_None;
2679 }
2680 Py_DECREF(err_msg);
2681 } else {
2682 PyErr_Format(PyExc_SystemError,
2683 "Parent module '%.200s' not loaded, "
2684 "cannot perform relative import", buf);
2685 }
2686 }
2687 return parent;
2688 /* We expect, but can't guarantee, if parent != None, that:
2689 - parent.__name__ == buf
2690 - parent.__dict__ is globals
2691 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002692}
2693
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002694/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002695static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002696load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 char *name = *p_name;
2700 char *dot = strchr(name, '.');
2701 size_t len;
2702 char *p;
2703 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 if (strlen(name) == 0) {
2706 /* completely empty module name should only happen in
2707 'from . import' (or '__import__("")')*/
2708 Py_INCREF(mod);
2709 *p_name = NULL;
2710 return mod;
2711 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 if (dot == NULL) {
2714 *p_name = NULL;
2715 len = strlen(name);
2716 }
2717 else {
2718 *p_name = dot+1;
2719 len = dot-name;
2720 }
2721 if (len == 0) {
2722 PyErr_SetString(PyExc_ValueError,
2723 "Empty module name");
2724 return NULL;
2725 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 p = buf + *p_buflen;
2728 if (p != buf)
2729 *p++ = '.';
2730 if (p+len-buf >= MAXPATHLEN) {
2731 PyErr_SetString(PyExc_ValueError,
2732 "Module name too long");
2733 return NULL;
2734 }
2735 strncpy(p, name, len);
2736 p[len] = '\0';
2737 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 result = import_submodule(mod, p, buf);
2740 if (result == Py_None && altmod != mod) {
2741 Py_DECREF(result);
2742 /* Here, altmod must be None and mod must not be None */
2743 result = import_submodule(altmod, p, p);
2744 if (result != NULL && result != Py_None) {
2745 if (mark_miss(buf) != 0) {
2746 Py_DECREF(result);
2747 return NULL;
2748 }
2749 strncpy(buf, name, len);
2750 buf[len] = '\0';
2751 *p_buflen = len;
2752 }
2753 }
2754 if (result == NULL)
2755 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 if (result == Py_None) {
2758 Py_DECREF(result);
2759 PyErr_Format(PyExc_ImportError,
2760 "No module named %.200s", name);
2761 return NULL;
2762 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002765}
2766
2767static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002768mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 PyObject *modules = PyImport_GetModuleDict();
2771 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002772}
2773
2774static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002775ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 if (!PyObject_HasAttrString(mod, "__path__"))
2781 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 for (i = 0; ; i++) {
2784 PyObject *item = PySequence_GetItem(fromlist, i);
2785 int hasit;
2786 if (item == NULL) {
2787 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2788 PyErr_Clear();
2789 return 1;
2790 }
2791 return 0;
2792 }
2793 if (!PyUnicode_Check(item)) {
2794 PyErr_SetString(PyExc_TypeError,
2795 "Item in ``from list'' not a string");
2796 Py_DECREF(item);
2797 return 0;
2798 }
2799 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2800 PyObject *all;
2801 Py_DECREF(item);
2802 /* See if the package defines __all__ */
2803 if (recursive)
2804 continue; /* Avoid endless recursion */
2805 all = PyObject_GetAttrString(mod, "__all__");
2806 if (all == NULL)
2807 PyErr_Clear();
2808 else {
2809 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2810 Py_DECREF(all);
2811 if (!ret)
2812 return 0;
2813 }
2814 continue;
2815 }
2816 hasit = PyObject_HasAttr(mod, item);
2817 if (!hasit) {
2818 PyObject *item8;
2819 char *subname;
2820 PyObject *submod;
2821 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002822 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 if (!item8) {
2824 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2825 return 0;
2826 }
2827 subname = PyBytes_AS_STRING(item8);
2828 if (buflen + strlen(subname) >= MAXPATHLEN) {
2829 PyErr_SetString(PyExc_ValueError,
2830 "Module name too long");
2831 Py_DECREF(item);
2832 return 0;
2833 }
2834 p = buf + buflen;
2835 *p++ = '.';
2836 strcpy(p, subname);
2837 submod = import_submodule(mod, subname, buf);
2838 Py_DECREF(item8);
2839 Py_XDECREF(submod);
2840 if (submod == NULL) {
2841 Py_DECREF(item);
2842 return 0;
2843 }
2844 }
2845 Py_DECREF(item);
2846 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002849}
2850
Neil Schemenauer00b09662003-06-16 21:03:07 +00002851static int
2852add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 if (mod == Py_None)
2856 return 1;
2857 /* Irrespective of the success of this load, make a
2858 reference to it in the parent package module. A copy gets
2859 saved in the modules dictionary under the full name, so get a
2860 reference from there, if need be. (The exception is when the
2861 load failed with a SyntaxError -- then there's no trace in
2862 sys.modules. In that case, of course, do nothing extra.) */
2863 if (submod == NULL) {
2864 submod = PyDict_GetItemString(modules, fullname);
2865 if (submod == NULL)
2866 return 1;
2867 }
2868 if (PyModule_Check(mod)) {
2869 /* We can't use setattr here since it can give a
2870 * spurious warning if the submodule name shadows a
2871 * builtin name */
2872 PyObject *dict = PyModule_GetDict(mod);
2873 if (!dict)
2874 return 0;
2875 if (PyDict_SetItemString(dict, subname, submod) < 0)
2876 return 0;
2877 }
2878 else {
2879 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2880 return 0;
2881 }
2882 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002883}
2884
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002885static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002886import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 PyObject *modules = PyImport_GetModuleDict();
2889 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 /* Require:
2892 if mod == None: subname == fullname
2893 else: mod.__name__ + "." + subname == fullname
2894 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2897 Py_INCREF(m);
2898 }
2899 else {
2900 PyObject *path, *loader = NULL;
2901 char buf[MAXPATHLEN+1];
2902 struct filedescr *fdp;
2903 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 if (mod == Py_None)
2906 path = NULL;
2907 else {
2908 path = PyObject_GetAttrString(mod, "__path__");
2909 if (path == NULL) {
2910 PyErr_Clear();
2911 Py_INCREF(Py_None);
2912 return Py_None;
2913 }
2914 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 buf[0] = '\0';
2917 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2918 &fp, &loader);
2919 Py_XDECREF(path);
2920 if (fdp == NULL) {
2921 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2922 return NULL;
2923 PyErr_Clear();
2924 Py_INCREF(Py_None);
2925 return Py_None;
2926 }
2927 m = load_module(fullname, fp, buf, fdp->type, loader);
2928 Py_XDECREF(loader);
2929 if (fp)
2930 fclose(fp);
2931 if (!add_submodule(mod, m, fullname, subname, modules)) {
2932 Py_XDECREF(m);
2933 m = NULL;
2934 }
2935 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002938}
2939
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002940
2941/* Re-import a module of any kind and return its module object, WITH
2942 INCREMENTED REFERENCE COUNT */
2943
Guido van Rossum79f25d91997-04-29 20:08:16 +00002944PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002945PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 PyInterpreterState *interp = PyThreadState_Get()->interp;
2948 PyObject *modules_reloading = interp->modules_reloading;
2949 PyObject *modules = PyImport_GetModuleDict();
2950 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2951 char *name, *subname;
2952 char buf[MAXPATHLEN+1];
2953 struct filedescr *fdp;
2954 FILE *fp = NULL;
2955 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 if (modules_reloading == NULL) {
2958 Py_FatalError("PyImport_ReloadModule: "
2959 "no modules_reloading dictionary!");
2960 return NULL;
2961 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 if (m == NULL || !PyModule_Check(m)) {
2964 PyErr_SetString(PyExc_TypeError,
2965 "reload() argument must be module");
2966 return NULL;
2967 }
2968 name = (char*)PyModule_GetName(m);
2969 if (name == NULL)
2970 return NULL;
2971 if (m != PyDict_GetItemString(modules, name)) {
2972 PyErr_Format(PyExc_ImportError,
2973 "reload(): module %.200s not in sys.modules",
2974 name);
2975 return NULL;
2976 }
2977 existing_m = PyDict_GetItemString(modules_reloading, name);
2978 if (existing_m != NULL) {
2979 /* Due to a recursive reload, this module is already
2980 being reloaded. */
2981 Py_INCREF(existing_m);
2982 return existing_m;
2983 }
2984 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2985 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 subname = strrchr(name, '.');
2988 if (subname == NULL)
2989 subname = name;
2990 else {
2991 PyObject *parentname, *parent;
2992 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2993 if (parentname == NULL) {
2994 imp_modules_reloading_clear();
2995 return NULL;
2996 }
2997 parent = PyDict_GetItem(modules, parentname);
2998 if (parent == NULL) {
2999 PyErr_Format(PyExc_ImportError,
3000 "reload(): parent %U not in sys.modules",
3001 parentname);
3002 Py_DECREF(parentname);
3003 imp_modules_reloading_clear();
3004 return NULL;
3005 }
3006 Py_DECREF(parentname);
3007 subname++;
3008 path = PyObject_GetAttrString(parent, "__path__");
3009 if (path == NULL)
3010 PyErr_Clear();
3011 }
3012 buf[0] = '\0';
3013 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3014 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 if (fdp == NULL) {
3017 Py_XDECREF(loader);
3018 imp_modules_reloading_clear();
3019 return NULL;
3020 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 newm = load_module(name, fp, buf, fdp->type, loader);
3023 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 if (fp)
3026 fclose(fp);
3027 if (newm == NULL) {
3028 /* load_module probably removed name from modules because of
3029 * the error. Put back the original module object. We're
3030 * going to return NULL in this case regardless of whether
3031 * replacing name succeeds, so the return value is ignored.
3032 */
3033 PyDict_SetItemString(modules, name, m);
3034 }
3035 imp_modules_reloading_clear();
3036 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003037}
3038
3039
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003040/* Higher-level import emulator which emulates the "import" statement
3041 more accurately -- it invokes the __import__() function from the
3042 builtins of the current globals. This means that the import is
3043 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00003044 environment, e.g. by "rexec".
3045 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003046 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003047 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003048
3049PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003050PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 static PyObject *silly_list = NULL;
3053 static PyObject *builtins_str = NULL;
3054 static PyObject *import_str = NULL;
3055 PyObject *globals = NULL;
3056 PyObject *import = NULL;
3057 PyObject *builtins = NULL;
3058 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 /* Initialize constant string objects */
3061 if (silly_list == NULL) {
3062 import_str = PyUnicode_InternFromString("__import__");
3063 if (import_str == NULL)
3064 return NULL;
3065 builtins_str = PyUnicode_InternFromString("__builtins__");
3066 if (builtins_str == NULL)
3067 return NULL;
3068 silly_list = Py_BuildValue("[s]", "__doc__");
3069 if (silly_list == NULL)
3070 return NULL;
3071 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 /* Get the builtins from current globals */
3074 globals = PyEval_GetGlobals();
3075 if (globals != NULL) {
3076 Py_INCREF(globals);
3077 builtins = PyObject_GetItem(globals, builtins_str);
3078 if (builtins == NULL)
3079 goto err;
3080 }
3081 else {
3082 /* No globals -- use standard builtins, and fake globals */
3083 builtins = PyImport_ImportModuleLevel("builtins",
3084 NULL, NULL, NULL, 0);
3085 if (builtins == NULL)
3086 return NULL;
3087 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3088 if (globals == NULL)
3089 goto err;
3090 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 /* Get the __import__ function from the builtins */
3093 if (PyDict_Check(builtins)) {
3094 import = PyObject_GetItem(builtins, import_str);
3095 if (import == NULL)
3096 PyErr_SetObject(PyExc_KeyError, import_str);
3097 }
3098 else
3099 import = PyObject_GetAttr(builtins, import_str);
3100 if (import == NULL)
3101 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 /* Call the __import__ function with the proper argument list
3104 * Always use absolute import here. */
3105 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3106 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003107
3108 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 Py_XDECREF(globals);
3110 Py_XDECREF(builtins);
3111 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003114}
3115
3116
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003117/* Module 'imp' provides Python access to the primitives used for
3118 importing modules.
3119*/
3120
Guido van Rossum79f25d91997-04-29 20:08:16 +00003121static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003122imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 buf[0] = (char) ((magic >> 0) & 0xff);
3127 buf[1] = (char) ((magic >> 8) & 0xff);
3128 buf[2] = (char) ((magic >> 16) & 0xff);
3129 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 return PyBytes_FromStringAndSize(buf, 4);
3132};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003133
3134static PyObject *
3135imp_get_magic(PyObject *self, PyObject *noargs)
3136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003138}
3139
3140static PyObject *
3141imp_get_tag(PyObject *self, PyObject *noargs)
3142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003144}
3145
Guido van Rossum79f25d91997-04-29 20:08:16 +00003146static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003147imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 PyObject *list;
3150 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 list = PyList_New(0);
3153 if (list == NULL)
3154 return NULL;
3155 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3156 PyObject *item = Py_BuildValue("ssi",
3157 fdp->suffix, fdp->mode, fdp->type);
3158 if (item == NULL) {
3159 Py_DECREF(list);
3160 return NULL;
3161 }
3162 if (PyList_Append(list, item) < 0) {
3163 Py_DECREF(list);
3164 Py_DECREF(item);
3165 return NULL;
3166 }
3167 Py_DECREF(item);
3168 }
3169 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003170}
3171
Guido van Rossum79f25d91997-04-29 20:08:16 +00003172static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003173call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 extern int fclose(FILE *);
3176 PyObject *fob, *ret;
3177 PyObject *pathobj;
3178 struct filedescr *fdp;
3179 char pathname[MAXPATHLEN+1];
3180 FILE *fp = NULL;
3181 int fd = -1;
3182 char *found_encoding = NULL;
3183 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 pathname[0] = '\0';
3186 if (path == Py_None)
3187 path = NULL;
3188 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3189 if (fdp == NULL)
3190 return NULL;
3191 if (fp != NULL) {
3192 fd = fileno(fp);
3193 if (fd != -1)
3194 fd = dup(fd);
3195 fclose(fp);
3196 fp = NULL;
3197 }
3198 if (fd != -1) {
3199 if (strchr(fdp->mode, 'b') == NULL) {
3200 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3201 memory. */
3202 found_encoding = PyTokenizer_FindEncoding(fd);
3203 lseek(fd, 0, 0); /* Reset position */
3204 if (found_encoding == NULL && PyErr_Occurred())
3205 return NULL;
3206 encoding = (found_encoding != NULL) ? found_encoding :
3207 (char*)PyUnicode_GetDefaultEncoding();
3208 }
3209 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3210 (char*)encoding, NULL, NULL, 1);
3211 if (fob == NULL) {
3212 close(fd);
3213 PyMem_FREE(found_encoding);
3214 return NULL;
3215 }
3216 }
3217 else {
3218 fob = Py_None;
3219 Py_INCREF(fob);
3220 }
3221 pathobj = PyUnicode_DecodeFSDefault(pathname);
3222 ret = Py_BuildValue("NN(ssi)",
3223 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3224 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003227}
3228
Guido van Rossum79f25d91997-04-29 20:08:16 +00003229static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003230imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 char *name;
3233 PyObject *ret, *path = NULL;
3234 if (!PyArg_ParseTuple(args, "es|O:find_module",
3235 Py_FileSystemDefaultEncoding, &name,
3236 &path))
3237 return NULL;
3238 ret = call_find_module(name, path);
3239 PyMem_Free(name);
3240 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003241}
3242
3243static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003244imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 char *name;
3247 int ret;
3248 PyObject *m;
3249 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3250 return NULL;
3251 ret = init_builtin(name);
3252 if (ret < 0)
3253 return NULL;
3254 if (ret == 0) {
3255 Py_INCREF(Py_None);
3256 return Py_None;
3257 }
3258 m = PyImport_AddModule(name);
3259 Py_XINCREF(m);
3260 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003261}
3262
Guido van Rossum79f25d91997-04-29 20:08:16 +00003263static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003264imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 char *name;
3267 int ret;
3268 PyObject *m;
3269 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3270 return NULL;
3271 ret = PyImport_ImportFrozenModule(name);
3272 if (ret < 0)
3273 return NULL;
3274 if (ret == 0) {
3275 Py_INCREF(Py_None);
3276 return Py_None;
3277 }
3278 m = PyImport_AddModule(name);
3279 Py_XINCREF(m);
3280 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003281}
3282
Guido van Rossum79f25d91997-04-29 20:08:16 +00003283static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003284imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3289 return NULL;
3290 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003291}
3292
Guido van Rossum79f25d91997-04-29 20:08:16 +00003293static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003294imp_is_frozen_package(PyObject *self, PyObject *args)
3295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3299 return NULL;
3300 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003301}
3302
3303static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003304imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 char *name;
3307 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3308 return NULL;
3309 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003310}
3311
Guido van Rossum79f25d91997-04-29 20:08:16 +00003312static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003313imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 char *name;
3316 struct _frozen *p;
3317 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3318 return NULL;
3319 p = find_frozen(name);
3320 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003321}
3322
3323static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003324get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 FILE *fp;
3327 if (mode[0] == 'U')
3328 mode = "r" PY_STDIOTEXTMODE;
3329 if (fob == NULL) {
3330 fp = fopen(pathname, mode);
3331 }
3332 else {
3333 int fd = PyObject_AsFileDescriptor(fob);
3334 if (fd == -1)
3335 return NULL;
3336 if (!_PyVerify_fd(fd))
3337 goto error;
3338 /* the FILE struct gets a new fd, so that it can be closed
3339 * independently of the file descriptor given
3340 */
3341 fd = dup(fd);
3342 if (fd == -1)
3343 goto error;
3344 fp = fdopen(fd, mode);
3345 }
3346 if (fp)
3347 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003348error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 PyErr_SetFromErrno(PyExc_IOError);
3350 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003351}
3352
Guido van Rossum79f25d91997-04-29 20:08:16 +00003353static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003354imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 char *name;
3357 char *pathname;
3358 PyObject *fob = NULL;
3359 PyObject *m;
3360 FILE *fp;
3361 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3362 &name,
3363 Py_FileSystemDefaultEncoding, &pathname,
3364 &fob))
3365 return NULL;
3366 fp = get_file(pathname, fob, "rb");
3367 if (fp == NULL) {
3368 PyMem_Free(pathname);
3369 return NULL;
3370 }
3371 m = load_compiled_module(name, pathname, fp);
3372 fclose(fp);
3373 PyMem_Free(pathname);
3374 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003375}
3376
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003377#ifdef HAVE_DYNAMIC_LOADING
3378
Guido van Rossum79f25d91997-04-29 20:08:16 +00003379static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003380imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 char *name;
3383 char *pathname;
3384 PyObject *fob = NULL;
3385 PyObject *m;
3386 FILE *fp = NULL;
3387 if (!PyArg_ParseTuple(args, "ses|O:load_dynamic",
3388 &name,
3389 Py_FileSystemDefaultEncoding, &pathname,
3390 &fob))
3391 return NULL;
3392 if (fob) {
3393 fp = get_file(pathname, fob, "r");
3394 if (fp == NULL) {
3395 PyMem_Free(pathname);
3396 return NULL;
3397 }
3398 }
3399 m = _PyImport_LoadDynamicModule(name, pathname, fp);
3400 PyMem_Free(pathname);
3401 if (fp)
3402 fclose(fp);
3403 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003404}
3405
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003406#endif /* HAVE_DYNAMIC_LOADING */
3407
Guido van Rossum79f25d91997-04-29 20:08:16 +00003408static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003409imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 char *name;
3412 char *pathname;
3413 PyObject *fob = NULL;
3414 PyObject *m;
3415 FILE *fp;
3416 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3417 &name,
3418 Py_FileSystemDefaultEncoding, &pathname,
3419 &fob))
3420 return NULL;
3421 fp = get_file(pathname, fob, "r");
3422 if (fp == NULL) {
3423 PyMem_Free(pathname);
3424 return NULL;
3425 }
3426 m = load_source_module(name, pathname, fp);
3427 PyMem_Free(pathname);
3428 fclose(fp);
3429 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003430}
3431
Guido van Rossum79f25d91997-04-29 20:08:16 +00003432static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003433imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 char *name;
3436 PyObject *fob;
3437 char *pathname;
3438 PyObject * ret;
3439 char *suffix; /* Unused */
3440 char *mode;
3441 int type;
3442 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
3445 &name, &fob,
3446 Py_FileSystemDefaultEncoding, &pathname,
3447 &suffix, &mode, &type))
3448 return NULL;
3449 if (*mode) {
3450 /* Mode must start with 'r' or 'U' and must not contain '+'.
3451 Implicit in this test is the assumption that the mode
3452 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3455 PyErr_Format(PyExc_ValueError,
3456 "invalid file open mode %.200s", mode);
3457 PyMem_Free(pathname);
3458 return NULL;
3459 }
3460 }
3461 if (fob == Py_None)
3462 fp = NULL;
3463 else {
3464 fp = get_file(NULL, fob, mode);
3465 if (fp == NULL) {
3466 PyMem_Free(pathname);
3467 return NULL;
3468 }
3469 }
3470 ret = load_module(name, fp, pathname, type, NULL);
3471 PyMem_Free(pathname);
3472 if (fp)
3473 fclose(fp);
3474 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003475}
3476
3477static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003478imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 char *name;
3481 char *pathname;
3482 PyObject * ret;
3483 if (!PyArg_ParseTuple(args, "ses:load_package",
3484 &name, Py_FileSystemDefaultEncoding, &pathname))
3485 return NULL;
3486 ret = load_package(name, pathname);
3487 PyMem_Free(pathname);
3488 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003489}
3490
3491static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003492imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 char *name;
3495 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3496 return NULL;
3497 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003498}
3499
Christian Heimes13a7a212008-01-07 17:13:09 +00003500static PyObject *
3501imp_reload(PyObject *self, PyObject *v)
3502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003504}
3505
3506PyDoc_STRVAR(doc_reload,
3507"reload(module) -> module\n\
3508\n\
3509Reload the module. The module must have been successfully imported before.");
3510
Barry Warsaw28a691b2010-04-17 00:19:56 +00003511static PyObject *
3512imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 char buf[MAXPATHLEN+1];
3517 char *pathname, *cpathname;
3518 PyObject *debug_override = Py_None;
3519 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 if (!PyArg_ParseTupleAndKeywords(
3522 args, kws, "es|O", kwlist,
3523 Py_FileSystemDefaultEncoding, &pathname, &debug_override))
3524 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 if (debug_override != Py_None)
3527 if ((debug = PyObject_IsTrue(debug_override)) < 0)
3528 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug);
3531 PyMem_Free(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 if (cpathname == NULL) {
3534 PyErr_Format(PyExc_SystemError, "path buffer too short");
3535 return NULL;
3536 }
3537 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003538}
3539
3540PyDoc_STRVAR(doc_cache_from_source,
3541"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3542\n\
3543The .py file does not need to exist; this simply returns the path to the\n\
3544.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3545will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3546\n\
3547If debug_override is not None, then it must be a boolean and is taken as\n\
3548the value of __debug__ instead.");
3549
3550static PyObject *
3551imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 char *pathname;
3556 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 if (!PyArg_ParseTupleAndKeywords(
3559 args, kws, "es", kwlist,
3560 Py_FileSystemDefaultEncoding, &pathname))
3561 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 if (make_source_pathname(pathname, buf) == NULL) {
3564 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3565 pathname);
3566 PyMem_Free(pathname);
3567 return NULL;
3568 }
3569 PyMem_Free(pathname);
3570 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003571}
3572
3573PyDoc_STRVAR(doc_source_from_cache,
3574"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3575\n\
3576The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3577the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3578does not conform to PEP 3147 format, ValueError will be raised.");
3579
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003580/* Doc strings */
3581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003582PyDoc_STRVAR(doc_imp,
3583"This module provides the components needed to build your own\n\
3584__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003585
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003586PyDoc_STRVAR(doc_find_module,
3587"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003588Search for a module. If path is omitted or None, search for a\n\
3589built-in, frozen or special module and continue search in sys.path.\n\
3590The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003591package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003593PyDoc_STRVAR(doc_load_module,
3594"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003595Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003596The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003598PyDoc_STRVAR(doc_get_magic,
3599"get_magic() -> string\n\
3600Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003601
Barry Warsaw28a691b2010-04-17 00:19:56 +00003602PyDoc_STRVAR(doc_get_tag,
3603"get_tag() -> string\n\
3604Return the magic tag for .pyc or .pyo files.");
3605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003606PyDoc_STRVAR(doc_get_suffixes,
3607"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003608Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003609that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003610
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003611PyDoc_STRVAR(doc_new_module,
3612"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003613Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003614The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003616PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003617"lock_held() -> boolean\n\
3618Return True if the import lock is currently held, else False.\n\
3619On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003620
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003621PyDoc_STRVAR(doc_acquire_lock,
3622"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003623Acquires the interpreter's import lock for the current thread.\n\
3624This lock should be used by import hooks to ensure thread-safety\n\
3625when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003626On platforms without threads, this function does nothing.");
3627
3628PyDoc_STRVAR(doc_release_lock,
3629"release_lock() -> None\n\
3630Release the interpreter's import lock.\n\
3631On platforms without threads, this function does nothing.");
3632
Guido van Rossum79f25d91997-04-29 20:08:16 +00003633static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3635 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3636 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3637 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3638 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3639 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3640 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3641 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3642 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3643 {"reload", imp_reload, METH_O, doc_reload},
3644 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3645 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3646 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3647 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3648 /* The rest are obsolete */
3649 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3650 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3651 {"init_builtin", imp_init_builtin, METH_VARARGS},
3652 {"init_frozen", imp_init_frozen, METH_VARARGS},
3653 {"is_builtin", imp_is_builtin, METH_VARARGS},
3654 {"is_frozen", imp_is_frozen, METH_VARARGS},
3655 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003656#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003658#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 {"load_package", imp_load_package, METH_VARARGS},
3660 {"load_source", imp_load_source, METH_VARARGS},
3661 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003662};
3663
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003664static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003665setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 PyObject *v;
3668 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 v = PyLong_FromLong((long)value);
3671 err = PyDict_SetItemString(d, name, v);
3672 Py_XDECREF(v);
3673 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003674}
3675
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003676typedef struct {
3677 PyObject_HEAD
3678} NullImporter;
3679
3680static int
3681NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3682{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003683#ifndef MS_WINDOWS
3684 PyObject *path;
3685 struct stat statbuf;
3686 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3689 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003690
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003691 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3692 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003694
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003695 if (PyBytes_GET_SIZE(path) == 0) {
3696 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 PyErr_SetString(PyExc_ImportError, "empty pathname");
3698 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003700
3701 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3702 Py_DECREF(path);
3703 if (rv == 0) {
3704 /* it exists */
3705 if (S_ISDIR(statbuf.st_mode)) {
3706 /* it's a directory */
3707 PyErr_SetString(PyExc_ImportError, "existing directory");
3708 return -1;
3709 }
3710 }
3711#else /* MS_WINDOWS */
3712 PyObject *pathobj;
3713 DWORD rv;
3714 wchar_t path[MAXPATHLEN+1];
3715 Py_ssize_t len;
3716
3717 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3718 return -1;
3719
3720 if (!PyArg_ParseTuple(args, "U:NullImporter",
3721 &pathobj))
3722 return -1;
3723
3724 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3725 PyErr_SetString(PyExc_ImportError, "empty pathname");
3726 return -1;
3727 }
3728
3729 len = PyUnicode_AsWideChar((PyUnicodeObject*)pathobj,
3730 path, sizeof(path) / sizeof(path[0]));
3731 if (len == -1)
3732 return -1;
3733 /* see issue1293 and issue3677:
3734 * stat() on Windows doesn't recognise paths like
3735 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3736 */
3737 rv = GetFileAttributesW(path);
3738 if (rv != INVALID_FILE_ATTRIBUTES) {
3739 /* it exists */
3740 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3741 /* it's a directory */
3742 PyErr_SetString(PyExc_ImportError, "existing directory");
3743 return -1;
3744 }
3745 }
3746#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003748}
3749
3750static PyObject *
3751NullImporter_find_module(NullImporter *self, PyObject *args)
3752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003754}
3755
3756static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3758 "Always return None"
3759 },
3760 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003761};
3762
3763
Christian Heimes9cd17752007-11-18 19:35:23 +00003764PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 PyVarObject_HEAD_INIT(NULL, 0)
3766 "imp.NullImporter", /*tp_name*/
3767 sizeof(NullImporter), /*tp_basicsize*/
3768 0, /*tp_itemsize*/
3769 0, /*tp_dealloc*/
3770 0, /*tp_print*/
3771 0, /*tp_getattr*/
3772 0, /*tp_setattr*/
3773 0, /*tp_reserved*/
3774 0, /*tp_repr*/
3775 0, /*tp_as_number*/
3776 0, /*tp_as_sequence*/
3777 0, /*tp_as_mapping*/
3778 0, /*tp_hash */
3779 0, /*tp_call*/
3780 0, /*tp_str*/
3781 0, /*tp_getattro*/
3782 0, /*tp_setattro*/
3783 0, /*tp_as_buffer*/
3784 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3785 "Null importer object", /* tp_doc */
3786 0, /* tp_traverse */
3787 0, /* tp_clear */
3788 0, /* tp_richcompare */
3789 0, /* tp_weaklistoffset */
3790 0, /* tp_iter */
3791 0, /* tp_iternext */
3792 NullImporter_methods, /* tp_methods */
3793 0, /* tp_members */
3794 0, /* tp_getset */
3795 0, /* tp_base */
3796 0, /* tp_dict */
3797 0, /* tp_descr_get */
3798 0, /* tp_descr_set */
3799 0, /* tp_dictoffset */
3800 (initproc)NullImporter_init, /* tp_init */
3801 0, /* tp_alloc */
3802 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003803};
3804
Martin v. Löwis1a214512008-06-11 05:26:20 +00003805static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 PyModuleDef_HEAD_INIT,
3807 "imp",
3808 doc_imp,
3809 0,
3810 imp_methods,
3811 NULL,
3812 NULL,
3813 NULL,
3814 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003815};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003816
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003817PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003818PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 if (PyType_Ready(&PyNullImporter_Type) < 0)
3823 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 m = PyModule_Create(&impmodule);
3826 if (m == NULL)
3827 goto failure;
3828 d = PyModule_GetDict(m);
3829 if (d == NULL)
3830 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3833 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3834 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3835 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3836 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3837 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3838 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3839 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3840 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3841 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 Py_INCREF(&PyNullImporter_Type);
3844 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3845 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003846 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 Py_XDECREF(m);
3848 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003849}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003850
3851
Guido van Rossumb18618d2000-05-03 23:44:39 +00003852/* API for embedding applications that want to add their own entries
3853 to the table of built-in modules. This should normally be called
3854 *before* Py_Initialize(). When the table resize fails, -1 is
3855 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003856
3857 After a similar function by Just van Rossum. */
3858
3859int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003860PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 static struct _inittab *our_copy = NULL;
3863 struct _inittab *p;
3864 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 /* Count the number of entries in both tables */
3867 for (n = 0; newtab[n].name != NULL; n++)
3868 ;
3869 if (n == 0)
3870 return 0; /* Nothing to do */
3871 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3872 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 /* Allocate new memory for the combined table */
3875 p = our_copy;
3876 PyMem_RESIZE(p, struct _inittab, i+n+1);
3877 if (p == NULL)
3878 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 /* Copy the tables into the new memory */
3881 if (our_copy != PyImport_Inittab)
3882 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3883 PyImport_Inittab = our_copy = p;
3884 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003887}
3888
3889/* Shorthand to add a single entry given a name and a function */
3890
3891int
Brett Cannona826f322009-04-02 03:41:46 +00003892PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 newtab[0].name = (char *)name;
3899 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003902}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003903
3904#ifdef __cplusplus
3905}
3906#endif