blob: d79fc522610f896ca4471425394bda740d746109 [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
Tim Peters36515e22001-11-18 04:06:29 +0000108*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000109
Barry Warsaw28a691b2010-04-17 00:19:56 +0000110/* If you change MAGIC, you must change TAG and you must insert the old value
111 into _PyMagicNumberTags below.
112*/
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000113#define MAGIC (3170 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114#define TAG "cpython-32"
115#define CACHEDIR "__pycache__"
116/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000117static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120/* See _PyImport_FixupExtension() below */
121static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000122
Guido van Rossum771c6c81997-10-31 18:37:24 +0000123/* This table is defined in config.c: */
124extern struct _inittab _PyImport_Inittab[];
125
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000126/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000127extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000128
Guido van Rossum771c6c81997-10-31 18:37:24 +0000129struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000130
Guido van Rossumed1170e1999-12-20 21:23:41 +0000131/* these tables define the module suffixes that Python recognizes */
132struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000133
Guido van Rossumed1170e1999-12-20 21:23:41 +0000134static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000136#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 {".pyc", "rb", PY_COMPILED},
140 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000141};
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000144/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145
146void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000147_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 const struct filedescr *scan;
150 struct filedescr *filetab;
151 int countD = 0;
152 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 /* prepare _PyImport_Filetab: copy entries from
155 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
156 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000157#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
159 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
162 ++countS;
163 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
164 if (filetab == NULL)
165 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000166#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 memcpy(filetab, _PyImport_DynLoadFiletab,
168 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000169#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 memcpy(filetab + countD, _PyImport_StandardFiletab,
171 countS * sizeof(struct filedescr));
172 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (Py_OptimizeFlag) {
177 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
178 for (; filetab->suffix != NULL; filetab++) {
179 if (strcmp(filetab->suffix, ".pyc") == 0)
180 filetab->suffix = ".pyo";
181 }
182 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185void
Just van Rossum52e14d62002-12-30 22:08:05 +0000186_PyImportHooks_Init(void)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyObject *v, *path_hooks = NULL, *zimpimport;
189 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* adding sys.path_hooks and sys.path_importer_cache, setting up
192 zipimport */
193 if (PyType_Ready(&PyNullImporter_Type) < 0)
194 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (Py_VerboseFlag)
197 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 v = PyList_New(0);
200 if (v == NULL)
201 goto error;
202 err = PySys_SetObject("meta_path", v);
203 Py_DECREF(v);
204 if (err)
205 goto error;
206 v = PyDict_New();
207 if (v == NULL)
208 goto error;
209 err = PySys_SetObject("path_importer_cache", v);
210 Py_DECREF(v);
211 if (err)
212 goto error;
213 path_hooks = PyList_New(0);
214 if (path_hooks == NULL)
215 goto error;
216 err = PySys_SetObject("path_hooks", path_hooks);
217 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000218 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 PyErr_Print();
220 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
221 "path_importer_cache, or NullImporter failed"
222 );
223 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 zimpimport = PyImport_ImportModule("zipimport");
226 if (zimpimport == NULL) {
227 PyErr_Clear(); /* No zip import module -- okay */
228 if (Py_VerboseFlag)
229 PySys_WriteStderr("# can't import zipimport\n");
230 }
231 else {
232 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
233 "zipimporter");
234 Py_DECREF(zimpimport);
235 if (zipimporter == NULL) {
236 PyErr_Clear(); /* No zipimporter object -- okay */
237 if (Py_VerboseFlag)
238 PySys_WriteStderr(
239 "# can't import zipimport.zipimporter\n");
240 }
241 else {
242 /* sys.path_hooks.append(zipimporter) */
243 err = PyList_Append(path_hooks, zipimporter);
244 Py_DECREF(zipimporter);
245 if (err)
246 goto error;
247 if (Py_VerboseFlag)
248 PySys_WriteStderr(
249 "# installed zipimport hook\n");
250 }
251 }
252 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000253}
254
255void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000256_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 Py_XDECREF(extensions);
259 extensions = NULL;
260 PyMem_DEL(_PyImport_Filetab);
261 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000262}
263
264
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000265/* Locking primitives to prevent parallel imports of the same module
266 in different threads to return with a partially loaded module.
267 These calls are serialized by the global interpreter lock. */
268
269#ifdef WITH_THREAD
270
Guido van Rossum49b56061998-10-01 20:42:43 +0000271#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272
Guido van Rossum65d5b571998-12-21 19:32:43 +0000273static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000274static long import_lock_thread = -1;
275static int import_lock_level = 0;
276
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000277void
278_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 long me = PyThread_get_thread_ident();
281 if (me == -1)
282 return; /* Too bad */
283 if (import_lock == NULL) {
284 import_lock = PyThread_allocate_lock();
285 if (import_lock == NULL)
286 return; /* Nothing much we can do. */
287 }
288 if (import_lock_thread == me) {
289 import_lock_level++;
290 return;
291 }
292 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
293 {
294 PyThreadState *tstate = PyEval_SaveThread();
295 PyThread_acquire_lock(import_lock, 1);
296 PyEval_RestoreThread(tstate);
297 }
298 import_lock_thread = me;
299 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300}
301
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000302int
303_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 long me = PyThread_get_thread_ident();
306 if (me == -1 || import_lock == NULL)
307 return 0; /* Too bad */
308 if (import_lock_thread != me)
309 return -1;
310 import_lock_level--;
311 if (import_lock_level == 0) {
312 import_lock_thread = -1;
313 PyThread_release_lock(import_lock);
314 }
315 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000316}
317
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000318/* This function is called from PyOS_AfterFork to ensure that newly
319 created child processes do not share locks with the parent.
320 We now acquire the import lock around fork() calls but on some platforms
321 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000322
323void
324_PyImport_ReInitLock(void)
325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (import_lock != NULL)
327 import_lock = PyThread_allocate_lock();
328 import_lock_thread = -1;
329 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000330}
331
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000332#endif
333
Tim Peters69232342001-08-30 05:16:13 +0000334static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000335imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000336{
Tim Peters69232342001-08-30 05:16:13 +0000337#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000339#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000341#endif
342}
343
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000344static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000345imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000346{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000347#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000349#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 Py_INCREF(Py_None);
351 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352}
353
354static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000355imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000356{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000357#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (_PyImport_ReleaseLock() < 0) {
359 PyErr_SetString(PyExc_RuntimeError,
360 "not holding the import lock");
361 return NULL;
362 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000363#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 Py_INCREF(Py_None);
365 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000366}
367
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368static void
369imp_modules_reloading_clear(void)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyInterpreterState *interp = PyThreadState_Get()->interp;
372 if (interp->modules_reloading != NULL)
373 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000374}
375
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376/* Helper for sys */
377
378PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000379PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyInterpreterState *interp = PyThreadState_GET()->interp;
382 if (interp->modules == NULL)
383 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
384 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385}
386
Guido van Rossum3f5da241990-12-20 15:06:42 +0000387
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000388/* List of names to clear in sys */
389static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 "path", "argv", "ps1", "ps2",
391 "last_type", "last_value", "last_traceback",
392 "path_hooks", "path_importer_cache", "meta_path",
393 /* misc stuff */
394 "flags", "float_info",
395 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000396};
397
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000398static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 "stdin", "__stdin__",
400 "stdout", "__stdout__",
401 "stderr", "__stderr__",
402 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000403};
404
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000406/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000407
Guido van Rossum3f5da241990-12-20 15:06:42 +0000408void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_ssize_t pos, ndone;
412 char *name;
413 PyObject *key, *value, *dict;
414 PyInterpreterState *interp = PyThreadState_GET()->interp;
415 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (modules == NULL)
418 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* Delete some special variables first. These are common
421 places where user values hide and people complain when their
422 destructors fail. Since the modules containing them are
423 deleted *last* of all, they would come too late in the normal
424 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 value = PyDict_GetItemString(modules, "builtins");
427 if (value != NULL && PyModule_Check(value)) {
428 dict = PyModule_GetDict(value);
429 if (Py_VerboseFlag)
430 PySys_WriteStderr("# clear builtins._\n");
431 PyDict_SetItemString(dict, "_", Py_None);
432 }
433 value = PyDict_GetItemString(modules, "sys");
434 if (value != NULL && PyModule_Check(value)) {
435 char **p;
436 PyObject *v;
437 dict = PyModule_GetDict(value);
438 for (p = sys_deletes; *p != NULL; p++) {
439 if (Py_VerboseFlag)
440 PySys_WriteStderr("# clear sys.%s\n", *p);
441 PyDict_SetItemString(dict, *p, Py_None);
442 }
443 for (p = sys_files; *p != NULL; p+=2) {
444 if (Py_VerboseFlag)
445 PySys_WriteStderr("# restore sys.%s\n", *p);
446 v = PyDict_GetItemString(dict, *(p+1));
447 if (v == NULL)
448 v = Py_None;
449 PyDict_SetItemString(dict, *p, v);
450 }
451 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* First, delete __main__ */
454 value = PyDict_GetItemString(modules, "__main__");
455 if (value != NULL && PyModule_Check(value)) {
456 if (Py_VerboseFlag)
457 PySys_WriteStderr("# cleanup __main__\n");
458 _PyModule_Clear(value);
459 PyDict_SetItemString(modules, "__main__", Py_None);
460 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* The special treatment of "builtins" here is because even
463 when it's not referenced as a module, its dictionary is
464 referenced by almost every module's __builtins__. Since
465 deleting a module clears its dictionary (even if there are
466 references left to it), we need to delete the "builtins"
467 module last. Likewise, we don't delete sys until the very
468 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 Also note that we 'delete' modules by replacing their entry
471 in the modules dict with None, rather than really deleting
472 them; this avoids a rehash of the modules dictionary and
473 also marks them as "non existent" so they won't be
474 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Next, repeatedly delete modules with a reference count of
477 one (skipping builtins and sys) and delete them */
478 do {
479 ndone = 0;
480 pos = 0;
481 while (PyDict_Next(modules, &pos, &key, &value)) {
482 if (value->ob_refcnt != 1)
483 continue;
484 if (PyUnicode_Check(key) && PyModule_Check(value)) {
485 name = _PyUnicode_AsString(key);
486 if (strcmp(name, "builtins") == 0)
487 continue;
488 if (strcmp(name, "sys") == 0)
489 continue;
490 if (Py_VerboseFlag)
491 PySys_WriteStderr(
492 "# cleanup[1] %s\n", name);
493 _PyModule_Clear(value);
494 PyDict_SetItem(modules, key, Py_None);
495 ndone++;
496 }
497 }
498 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Next, delete all modules (still skipping builtins and sys) */
501 pos = 0;
502 while (PyDict_Next(modules, &pos, &key, &value)) {
503 if (PyUnicode_Check(key) && PyModule_Check(value)) {
504 name = _PyUnicode_AsString(key);
505 if (strcmp(name, "builtins") == 0)
506 continue;
507 if (strcmp(name, "sys") == 0)
508 continue;
509 if (Py_VerboseFlag)
510 PySys_WriteStderr("# cleanup[2] %s\n", name);
511 _PyModule_Clear(value);
512 PyDict_SetItem(modules, key, Py_None);
513 }
514 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Next, delete sys and builtins (in that order) */
517 value = PyDict_GetItemString(modules, "sys");
518 if (value != NULL && PyModule_Check(value)) {
519 if (Py_VerboseFlag)
520 PySys_WriteStderr("# cleanup sys\n");
521 _PyModule_Clear(value);
522 PyDict_SetItemString(modules, "sys", Py_None);
523 }
524 value = PyDict_GetItemString(modules, "builtins");
525 if (value != NULL && PyModule_Check(value)) {
526 if (Py_VerboseFlag)
527 PySys_WriteStderr("# cleanup builtins\n");
528 _PyModule_Clear(value);
529 PyDict_SetItemString(modules, "builtins", Py_None);
530 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 /* Finally, clear and delete the modules directory */
533 PyDict_Clear(modules);
534 interp->modules = NULL;
535 Py_DECREF(modules);
536 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000537}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000538
539
Barry Warsaw28a691b2010-04-17 00:19:56 +0000540/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000541
542long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000543PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000546}
547
548
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549const char *
550PyImport_GetMagicTag(void)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000553}
554
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555/* Magic for extension modules (built-in as well as dynamically
556 loaded). To prevent initializing an extension module more than
557 once, we keep a static dictionary 'extensions' keyed by module name
558 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000559 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560 dictionary is stored by calling _PyImport_FixupExtension()
561 immediately after the module initialization function succeeds. A
562 copy can be retrieved from there by calling
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000563 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000564
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000565 Modules which do support multiple initialization set their m_size
566 field to a non-negative number (indicating the size of the
567 module-specific state). They are still recorded in the extensions
568 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000569*/
570
571int
572_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyObject *modules, *dict;
575 struct PyModuleDef *def;
576 if (extensions == NULL) {
577 extensions = PyDict_New();
578 if (extensions == NULL)
579 return -1;
580 }
581 if (mod == NULL || !PyModule_Check(mod)) {
582 PyErr_BadInternalCall();
583 return -1;
584 }
585 def = PyModule_GetDef(mod);
586 if (!def) {
587 PyErr_BadInternalCall();
588 return -1;
589 }
590 modules = PyImport_GetModuleDict();
591 if (PyDict_SetItemString(modules, name, mod) < 0)
592 return -1;
593 if (_PyState_AddModule(mod, def) < 0) {
594 PyDict_DelItemString(modules, name);
595 return -1;
596 }
597 if (def->m_size == -1) {
598 if (def->m_base.m_copy) {
599 /* Somebody already imported the module,
600 likely under a different name.
601 XXX this should really not happen. */
602 Py_DECREF(def->m_base.m_copy);
603 def->m_base.m_copy = NULL;
604 }
605 dict = PyModule_GetDict(mod);
606 if (dict == NULL)
607 return -1;
608 def->m_base.m_copy = PyDict_Copy(dict);
609 if (def->m_base.m_copy == NULL)
610 return -1;
611 }
612 PyDict_SetItemString(extensions, filename, (PyObject*)def);
613 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614}
615
616PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000617_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyObject *mod, *mdict;
620 PyModuleDef* def;
621 if (extensions == NULL)
622 return NULL;
623 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
624 if (def == NULL)
625 return NULL;
626 if (def->m_size == -1) {
627 /* Module does not support repeated initialization */
628 if (def->m_base.m_copy == NULL)
629 return NULL;
630 mod = PyImport_AddModule(name);
631 if (mod == NULL)
632 return NULL;
633 mdict = PyModule_GetDict(mod);
634 if (mdict == NULL)
635 return NULL;
636 if (PyDict_Update(mdict, def->m_base.m_copy))
637 return NULL;
638 }
639 else {
640 if (def->m_base.m_init == NULL)
641 return NULL;
642 mod = def->m_base.m_init();
643 if (mod == NULL)
644 return NULL;
645 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
646 Py_DECREF(mod);
647 }
648 if (_PyState_AddModule(mod, def) < 0) {
649 PyDict_DelItemString(PyImport_GetModuleDict(), name);
650 Py_DECREF(mod);
651 return NULL;
652 }
653 if (Py_VerboseFlag)
654 PySys_WriteStderr("import %s # previously loaded (%s)\n",
655 name, filename);
656 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000657
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658}
659
660
661/* Get the module object corresponding to a module name.
662 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000663 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000664 Because the former action is most common, THIS DOES NOT RETURN A
665 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000666
Guido van Rossum79f25d91997-04-29 20:08:16 +0000667PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000668PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *modules = PyImport_GetModuleDict();
671 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
674 PyModule_Check(m))
675 return m;
676 m = PyModule_New(name);
677 if (m == NULL)
678 return NULL;
679 if (PyDict_SetItemString(modules, name, m) != 0) {
680 Py_DECREF(m);
681 return NULL;
682 }
683 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686}
687
Tim Peters1cd70172004-08-02 03:52:12 +0000688/* Remove name from sys.modules, if it's there. */
689static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000690remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject *modules = PyImport_GetModuleDict();
693 if (PyDict_GetItemString(modules, name) == NULL)
694 return;
695 if (PyDict_DelItemString(modules, name) < 0)
696 Py_FatalError("import: deleting existing key in"
697 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000698}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000699
Barry Warsaw28a691b2010-04-17 00:19:56 +0000700static PyObject * get_sourcefile(char *file);
701static char *make_source_pathname(char *pathname, char *buf);
702static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000704
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000705/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000706 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
707 * removed from sys.modules, to avoid leaving damaged module objects
708 * in sys.modules. The caller may wish to restore the original
709 * module object (if any) in this case; PyImport_ReloadModule is an
710 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000711 *
712 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
713 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000714 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000715PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000716PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return PyImport_ExecCodeModuleWithPathnames(
719 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000720}
721
722PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000723PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 return PyImport_ExecCodeModuleWithPathnames(
726 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000727}
728
729PyObject *
730PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 PyObject *modules = PyImport_GetModuleDict();
734 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 m = PyImport_AddModule(name);
737 if (m == NULL)
738 return NULL;
739 /* If the module is being reloaded, we get the old module back
740 and re-use its dict to exec the new code. */
741 d = PyModule_GetDict(m);
742 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
743 if (PyDict_SetItemString(d, "__builtins__",
744 PyEval_GetBuiltins()) != 0)
745 goto error;
746 }
747 /* Remember the filename as the __file__ attribute */
748 v = NULL;
749 if (pathname != NULL) {
750 v = get_sourcefile(pathname);
751 if (v == NULL)
752 PyErr_Clear();
753 }
754 if (v == NULL) {
755 v = ((PyCodeObject *)co)->co_filename;
756 Py_INCREF(v);
757 }
758 if (PyDict_SetItemString(d, "__file__", v) != 0)
759 PyErr_Clear(); /* Not important enough to report */
760 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 /* Remember the pyc path name as the __cached__ attribute. */
763 if (cpathname == NULL) {
764 v = Py_None;
765 Py_INCREF(v);
766 }
767 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
768 PyErr_Clear(); /* Not important enough to report */
769 v = Py_None;
770 Py_INCREF(v);
771 }
772 if (PyDict_SetItemString(d, "__cached__", v) != 0)
773 PyErr_Clear(); /* Not important enough to report */
774 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
777 if (v == NULL)
778 goto error;
779 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
782 PyErr_Format(PyExc_ImportError,
783 "Loaded module %.200s not found in sys.modules",
784 name);
785 return NULL;
786 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000791
792 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 remove_module(name);
794 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000795}
796
797
Barry Warsaw28a691b2010-04-17 00:19:56 +0000798/* Like strrchr(string, '/') but searches for the rightmost of either SEP
799 or ALTSEP, if the latter is defined.
800*/
801static char *
802rightmost_sep(char *s)
803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 char *found, c;
805 for (found = NULL; (c = *s); s++) {
806 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000807#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000809#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 )
811 {
812 found = s;
813 }
814 }
815 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000816}
817
818
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819/* Given a pathname for a Python source file, fill a buffer with the
820 pathname for the corresponding compiled file. Return the pathname
821 for the compiled file, or NULL if there's no space in the buffer.
822 Doesn't set an exception. */
823
824static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000825make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* foo.py -> __pycache__/foo.<tag>.pyc */
828 size_t len = strlen(pathname);
829 size_t i, save;
830 char *pos;
831 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 /* Sanity check that the buffer has roughly enough space to hold what
834 will eventually be the full path to the compiled file. The 5 extra
835 bytes include the slash afer __pycache__, the two extra dots, the
836 extra trailing character ('c' or 'o') and null. This isn't exact
837 because the contents of the buffer can affect how many actual
838 characters of the string get into the buffer. We'll do a final
839 sanity check before writing the extension to ensure we do not
840 overflow the buffer.
841 */
842 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
843 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 /* Find the last path separator and copy everything from the start of
846 the source string up to and including the separator.
847 */
848 if ((pos = rightmost_sep(pathname)) == NULL) {
849 i = 0;
850 }
851 else {
852 sep = *pos;
853 i = pos - pathname + 1;
854 strncpy(buf, pathname, i);
855 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 save = i;
858 buf[i++] = '\0';
859 /* Add __pycache__/ */
860 strcat(buf, CACHEDIR);
861 i += strlen(CACHEDIR) - 1;
862 buf[i++] = sep;
863 buf[i++] = '\0';
864 /* Add the base filename, but remove the .py or .pyw extension, since
865 the tag name must go before the extension.
866 */
867 strcat(buf, pathname + save);
868 if ((pos = strrchr(buf, '.')) != NULL)
869 *++pos = '\0';
870 strcat(buf, pyc_tag);
871 /* The length test above assumes that we're only adding one character
872 to the end of what would normally be the extension. What if there
873 is no extension, or the string ends in '.' or '.p', and otherwise
874 fills the buffer? By appending 4 more characters onto the string
875 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 As a simple example, let's say buflen=32 and the input string is
878 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 which is false and so the name mangling would continue. This would
883 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
888 We can even handle an input string of say 'xxxxx' above because
889 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
890 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 which is 32 characters including the nul, and thus fits in the
895 buffer. However, an input string of 'xxxxxx' would yield a result
896 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 which is 33 characters long (including the nul), thus overflowing
901 the buffer, even though the first test would fail, i.e.: the input
902 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 The reason the first test fails but we still overflow the buffer is
905 that the test above only expects to add one extra character to be
906 added to the extension, and here we're adding three (pyc). We
907 don't add the first dot, so that reclaims one of expected
908 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
909 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 The best we can do is ensure that we still have enough room in the
912 target buffer before we write the extension. Because it's always
913 only the extension that can cause the overflow, and never the other
914 path bytes we've written, it's sufficient to just do one more test
915 here. Still, the assertion that follows can't hurt.
916 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000917#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000919#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (strlen(buf) + 5 > buflen)
921 return NULL;
922 strcat(buf, debug ? ".pyc" : ".pyo");
923 assert(strlen(buf) < buflen);
924 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000925}
926
927
Barry Warsaw28a691b2010-04-17 00:19:56 +0000928/* Given a pathname to a Python byte compiled file, return the path to the
929 source file, if the path matches the PEP 3147 format. This does not check
930 for any file existence, however, if the pyc file name does not match PEP
931 3147 style, NULL is returned. buf must be at least as big as pathname;
932 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933
Barry Warsaw28a691b2010-04-17 00:19:56 +0000934static char *
935make_source_pathname(char *pathname, char *buf)
936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* __pycache__/foo.<tag>.pyc -> foo.py */
938 size_t i, j;
939 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Look back two slashes from the end. In between these two slashes
942 must be the string __pycache__ or this is not a PEP 3147 style
943 path. It's possible for there to be only one slash.
944 */
945 if ((right = rightmost_sep(pathname)) == NULL)
946 return NULL;
947 sep = *right;
948 *right = '\0';
949 left = rightmost_sep(pathname);
950 *right = sep;
951 if (left == NULL)
952 left = pathname;
953 else
954 left++;
955 if (right-left != strlen(CACHEDIR) ||
956 strncmp(left, CACHEDIR, right-left) != 0)
957 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Now verify that the path component to the right of the last slash
960 has two dots in it.
961 */
962 if ((dot0 = strchr(right + 1, '.')) == NULL)
963 return NULL;
964 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
965 return NULL;
966 /* Too many dots? */
967 if (strchr(dot1 + 1, '.') != NULL)
968 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* This is a PEP 3147 path. Start by copying everything from the
971 start of pathname up to and including the leftmost slash. Then
972 copy the file's basename, removing the magic tag and adding a .py
973 suffix.
974 */
975 strncpy(buf, pathname, (i=left-pathname));
976 strncpy(buf+i, right+1, (j=dot0-right));
977 strcpy(buf+i+j, "py");
978 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000979}
980
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000981/* Given a pathname for a Python source file, its time of last
982 modification, and a pathname for a compiled file, check whether the
983 compiled file represents the same version of the source. If so,
984 return a FILE pointer for the compiled file, positioned just after
985 the header; if not, return NULL.
986 Doesn't set an exception. */
987
988static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000989check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 FILE *fp;
992 long magic;
993 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 fp = fopen(cpathname, "rb");
996 if (fp == NULL)
997 return NULL;
998 magic = PyMarshal_ReadLongFromFile(fp);
999 if (magic != pyc_magic) {
1000 if (Py_VerboseFlag)
1001 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1002 fclose(fp);
1003 return NULL;
1004 }
1005 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1006 if (pyc_mtime != mtime) {
1007 if (Py_VerboseFlag)
1008 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1009 fclose(fp);
1010 return NULL;
1011 }
1012 if (Py_VerboseFlag)
1013 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1014 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001015}
1016
1017
1018/* Read a code object from a file and check it for validity */
1019
Guido van Rossum79f25d91997-04-29 20:08:16 +00001020static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001021read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 co = PyMarshal_ReadLastObjectFromFile(fp);
1026 if (co == NULL)
1027 return NULL;
1028 if (!PyCode_Check(co)) {
1029 PyErr_Format(PyExc_ImportError,
1030 "Non-code object in %.200s", cpathname);
1031 Py_DECREF(co);
1032 return NULL;
1033 }
1034 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001035}
1036
1037
1038/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001039 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001040
Guido van Rossum79f25d91997-04-29 20:08:16 +00001041static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001042load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 long magic;
1045 PyCodeObject *co;
1046 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 magic = PyMarshal_ReadLongFromFile(fp);
1049 if (magic != pyc_magic) {
1050 PyErr_Format(PyExc_ImportError,
1051 "Bad magic number in %.200s", cpathname);
1052 return NULL;
1053 }
1054 (void) PyMarshal_ReadLongFromFile(fp);
1055 co = read_compiled_module(cpathname, fp);
1056 if (co == NULL)
1057 return NULL;
1058 if (Py_VerboseFlag)
1059 PySys_WriteStderr("import %s # precompiled from %s\n",
1060 name, cpathname);
1061 m = PyImport_ExecCodeModuleWithPathnames(
1062 name, (PyObject *)co, cpathname, cpathname);
1063 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001066}
1067
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068/* Parse a source file and return the corresponding code object */
1069
Guido van Rossum79f25d91997-04-29 20:08:16 +00001070static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyCodeObject *co = NULL;
1074 mod_ty mod;
1075 PyCompilerFlags flags;
1076 PyArena *arena = PyArena_New();
1077 if (arena == NULL)
1078 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 flags.cf_flags = 0;
1081 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1082 Py_file_input, 0, 0, &flags,
1083 NULL, arena);
1084 if (mod) {
1085 co = PyAST_Compile(mod, pathname, NULL, arena);
1086 }
1087 PyArena_Free(arena);
1088 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001089}
1090
1091
Guido van Rossum55a83382000-09-20 20:31:38 +00001092/* Helper to open a bytecode file for writing in exclusive mode */
1093
1094static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001095open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001096{
1097#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 /* Use O_EXCL to avoid a race condition when another process tries to
1099 write the same file. When that happens, our open() call fails,
1100 which is just fine (since it's only a cache).
1101 XXX If the file exists and is writable but the directory is not
1102 writable, the file will never be written. Oh well.
1103 */
1104 int fd;
1105 (void) unlink(filename);
1106 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001107#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001109#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001110#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001112#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001114#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 );
1116 if (fd < 0)
1117 return NULL;
1118 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001119#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 /* Best we can do -- on Windows this can't happen anyway */
1121 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001122#endif
1123}
1124
1125
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001126/* Write a compiled module to a file, placing the time of last
1127 modification of its source into the header.
1128 Errors are ignored, if a write error occurs an attempt is made to
1129 remove the file. */
1130
1131static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001132write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 FILE *fp;
1135 char *dirpath;
1136 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001137#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001139#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1141 mode_t dirmode = (srcstat->st_mode |
1142 S_IXUSR | S_IXGRP | S_IXOTH |
1143 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001144#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 /* Ensure that the __pycache__ directory exists. */
1148 dirpath = rightmost_sep(cpathname);
1149 if (dirpath == NULL) {
1150 if (Py_VerboseFlag)
1151 PySys_WriteStderr(
1152 "# no %s path found %s\n",
1153 CACHEDIR, cpathname);
1154 return;
1155 }
1156 saved = *dirpath;
1157 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001158
1159#ifdef MS_WINDOWS
1160 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1161#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001163#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 *dirpath = saved;
1165 if (Py_VerboseFlag)
1166 PySys_WriteStderr(
1167 "# cannot create cache dir %s\n", cpathname);
1168 return;
1169 }
1170 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 fp = open_exclusive(cpathname, mode);
1173 if (fp == NULL) {
1174 if (Py_VerboseFlag)
1175 PySys_WriteStderr(
1176 "# can't create %s\n", cpathname);
1177 return;
1178 }
1179 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1180 /* First write a 0 for mtime */
1181 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1182 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1183 if (fflush(fp) != 0 || ferror(fp)) {
1184 if (Py_VerboseFlag)
1185 PySys_WriteStderr("# can't write %s\n", cpathname);
1186 /* Don't keep partial file */
1187 fclose(fp);
1188 (void) unlink(cpathname);
1189 return;
1190 }
1191 /* Now write the true mtime */
1192 fseek(fp, 4L, 0);
1193 assert(mtime < LONG_MAX);
1194 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1195 fflush(fp);
1196 fclose(fp);
1197 if (Py_VerboseFlag)
1198 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001199}
1200
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001201static void
1202update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 PyObject *constants, *tmp;
1205 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (PyUnicode_Compare(co->co_filename, oldname))
1208 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 tmp = co->co_filename;
1211 co->co_filename = newname;
1212 Py_INCREF(co->co_filename);
1213 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 constants = co->co_consts;
1216 n = PyTuple_GET_SIZE(constants);
1217 for (i = 0; i < n; i++) {
1218 tmp = PyTuple_GET_ITEM(constants, i);
1219 if (PyCode_Check(tmp))
1220 update_code_filenames((PyCodeObject *)tmp,
1221 oldname, newname);
1222 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001223}
1224
1225static int
1226update_compiled_module(PyCodeObject *co, char *pathname)
1227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 newname = PyUnicode_DecodeFSDefault(pathname);
1231 if (newname == NULL)
1232 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (!PyUnicode_Compare(co->co_filename, newname)) {
1235 Py_DECREF(newname);
1236 return 0;
1237 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 oldname = co->co_filename;
1240 Py_INCREF(oldname);
1241 update_code_filenames(co, oldname, newname);
1242 Py_DECREF(oldname);
1243 Py_DECREF(newname);
1244 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001245}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
1247/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001248 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1249 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001250
Guido van Rossum79f25d91997-04-29 20:08:16 +00001251static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001252load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 struct stat st;
1255 FILE *fpc;
1256 char buf[MAXPATHLEN+1];
1257 char *cpathname;
1258 PyCodeObject *co;
1259 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (fstat(fileno(fp), &st) != 0) {
1262 PyErr_Format(PyExc_RuntimeError,
1263 "unable to get file status from '%s'",
1264 pathname);
1265 return NULL;
1266 }
Fred Drake4c82b232000-06-30 16:18:57 +00001267#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* Python's .pyc timestamp handling presumes that the timestamp fits
1269 in 4 bytes. This will be fine until sometime in the year 2038,
1270 when a 4-byte signed time_t will overflow.
1271 */
1272 if (st.st_mtime >> 32) {
1273 PyErr_SetString(PyExc_OverflowError,
1274 "modification time overflows a 4 byte field");
1275 return NULL;
1276 }
Fred Drake4c82b232000-06-30 16:18:57 +00001277#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 cpathname = make_compiled_pathname(
1279 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1280 if (cpathname != NULL &&
1281 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1282 co = read_compiled_module(cpathname, fpc);
1283 fclose(fpc);
1284 if (co == NULL)
1285 return NULL;
1286 if (update_compiled_module(co, pathname) < 0)
1287 return NULL;
1288 if (Py_VerboseFlag)
1289 PySys_WriteStderr("import %s # precompiled from %s\n",
1290 name, cpathname);
1291 pathname = cpathname;
1292 }
1293 else {
1294 co = parse_source_module(pathname, fp);
1295 if (co == NULL)
1296 return NULL;
1297 if (Py_VerboseFlag)
1298 PySys_WriteStderr("import %s # from %s\n",
1299 name, pathname);
1300 if (cpathname) {
1301 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1302 if (ro == NULL || !PyObject_IsTrue(ro))
1303 write_compiled_module(co, cpathname, &st);
1304 }
1305 }
1306 m = PyImport_ExecCodeModuleWithPathnames(
1307 name, (PyObject *)co, pathname, cpathname);
1308 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001311}
1312
Christian Heimes3b06e532008-01-07 20:12:44 +00001313/* Get source file -> unicode or None
1314 * Returns the path to the py file if available, else the given path
1315 */
1316static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001317get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 char py[MAXPATHLEN + 1];
1320 Py_ssize_t len;
1321 PyObject *u;
1322 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (!file || !*file) {
1325 Py_RETURN_NONE;
1326 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 len = strlen(file);
1329 /* match '*.py?' */
1330 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1331 return PyUnicode_DecodeFSDefault(file);
1332 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 /* Start by trying to turn PEP 3147 path into source path. If that
1335 * fails, just chop off the trailing character, i.e. legacy pyc path
1336 * to py.
1337 */
1338 if (make_source_pathname(file, py) == NULL) {
1339 strncpy(py, file, len-1);
1340 py[len-1] = '\0';
1341 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (stat(py, &statbuf) == 0 &&
1344 S_ISREG(statbuf.st_mode)) {
1345 u = PyUnicode_DecodeFSDefault(py);
1346 }
1347 else {
1348 u = PyUnicode_DecodeFSDefault(file);
1349 }
1350 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001351}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001352
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001353/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001354static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1355static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001357static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001358
1359/* Load a package and return its module object WITH INCREMENTED
1360 REFERENCE COUNT */
1361
1362static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001363load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyObject *m, *d;
1366 PyObject *file = NULL;
1367 PyObject *path = NULL;
1368 int err;
1369 char buf[MAXPATHLEN+1];
1370 FILE *fp = NULL;
1371 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 m = PyImport_AddModule(name);
1374 if (m == NULL)
1375 return NULL;
1376 if (Py_VerboseFlag)
1377 PySys_WriteStderr("import %s # directory %s\n",
1378 name, pathname);
1379 d = PyModule_GetDict(m);
1380 file = get_sourcefile(pathname);
1381 if (file == NULL)
1382 goto error;
1383 path = Py_BuildValue("[O]", file);
1384 if (path == NULL)
1385 goto error;
1386 err = PyDict_SetItemString(d, "__file__", file);
1387 if (err == 0)
1388 err = PyDict_SetItemString(d, "__path__", path);
1389 if (err != 0)
1390 goto error;
1391 buf[0] = '\0';
1392 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1393 if (fdp == NULL) {
1394 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1395 PyErr_Clear();
1396 Py_INCREF(m);
1397 }
1398 else
1399 m = NULL;
1400 goto cleanup;
1401 }
1402 m = load_module(name, fp, buf, fdp->type, NULL);
1403 if (fp != NULL)
1404 fclose(fp);
1405 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001406
1407 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001409 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 Py_XDECREF(path);
1411 Py_XDECREF(file);
1412 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001413}
1414
1415
1416/* Helper to test for built-in module */
1417
1418static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001419is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 int i;
1422 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1423 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1424 if (PyImport_Inittab[i].initfunc == NULL)
1425 return -1;
1426 else
1427 return 1;
1428 }
1429 }
1430 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001431}
1432
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001433
Just van Rossum52e14d62002-12-30 22:08:05 +00001434/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1435 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001436 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001437 that can handle the path item. Return None if no hook could;
1438 this tells our caller it should fall back to the builtin
1439 import mechanism. Cache the result in path_importer_cache.
1440 Returns a borrowed reference. */
1441
1442static PyObject *
1443get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyObject *importer;
1447 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 /* These conditions are the caller's responsibility: */
1450 assert(PyList_Check(path_hooks));
1451 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 nhooks = PyList_Size(path_hooks);
1454 if (nhooks < 0)
1455 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 importer = PyDict_GetItem(path_importer_cache, p);
1458 if (importer != NULL)
1459 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* set path_importer_cache[p] to None to avoid recursion */
1462 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1463 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 for (j = 0; j < nhooks; j++) {
1466 PyObject *hook = PyList_GetItem(path_hooks, j);
1467 if (hook == NULL)
1468 return NULL;
1469 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1470 if (importer != NULL)
1471 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1474 return NULL;
1475 }
1476 PyErr_Clear();
1477 }
1478 if (importer == NULL) {
1479 importer = PyObject_CallFunctionObjArgs(
1480 (PyObject *)&PyNullImporter_Type, p, NULL
1481 );
1482 if (importer == NULL) {
1483 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1484 PyErr_Clear();
1485 return Py_None;
1486 }
1487 }
1488 }
1489 if (importer != NULL) {
1490 int err = PyDict_SetItem(path_importer_cache, p, importer);
1491 Py_DECREF(importer);
1492 if (err != 0)
1493 return NULL;
1494 }
1495 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001496}
1497
Christian Heimes9cd17752007-11-18 19:35:23 +00001498PyAPI_FUNC(PyObject *)
1499PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1503 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1504 importer = get_path_importer(path_importer_cache,
1505 path_hooks, path);
1506 }
1507 }
1508 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1509 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001510}
1511
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001512/* Search the path (default sys.path) for a module. Return the
1513 corresponding filedescr struct, and (via return arguments) the
1514 pathname and an open file. Return NULL if the module is not found. */
1515
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001516#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001517extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001519#endif
1520
Martin v. Löwis18e16552006-02-15 17:27:45 +00001521static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001522static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001523static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001524
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001525static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001526find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 Py_ssize_t i, npath;
1530 size_t len, namelen;
1531 struct filedescr *fdp = NULL;
1532 char *filemode;
1533 FILE *fp = NULL;
1534 PyObject *path_hooks, *path_importer_cache;
1535 struct stat statbuf;
1536 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1537 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1538 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1539 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001540#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 size_t saved_len;
1542 size_t saved_namelen;
1543 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001544#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (p_loader != NULL)
1546 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (strlen(subname) > MAXPATHLEN) {
1549 PyErr_SetString(PyExc_OverflowError,
1550 "module name is too long");
1551 return NULL;
1552 }
1553 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 /* sys.meta_path import hook */
1556 if (p_loader != NULL) {
1557 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 meta_path = PySys_GetObject("meta_path");
1560 if (meta_path == NULL || !PyList_Check(meta_path)) {
1561 PyErr_SetString(PyExc_ImportError,
1562 "sys.meta_path must be a list of "
1563 "import hooks");
1564 return NULL;
1565 }
1566 Py_INCREF(meta_path); /* zap guard */
1567 npath = PyList_Size(meta_path);
1568 for (i = 0; i < npath; i++) {
1569 PyObject *loader;
1570 PyObject *hook = PyList_GetItem(meta_path, i);
1571 loader = PyObject_CallMethod(hook, "find_module",
1572 "sO", fullname,
1573 path != NULL ?
1574 path : Py_None);
1575 if (loader == NULL) {
1576 Py_DECREF(meta_path);
1577 return NULL; /* true error */
1578 }
1579 if (loader != Py_None) {
1580 /* a loader was found */
1581 *p_loader = loader;
1582 Py_DECREF(meta_path);
1583 return &importhookdescr;
1584 }
1585 Py_DECREF(loader);
1586 }
1587 Py_DECREF(meta_path);
1588 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if (find_frozen(fullname) != NULL) {
1591 strcpy(buf, fullname);
1592 return &fd_frozen;
1593 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 if (path == NULL) {
1596 if (is_builtin(name)) {
1597 strcpy(buf, name);
1598 return &fd_builtin;
1599 }
Guido van Rossumac279101996-08-22 23:10:58 +00001600#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1602 if (fp != NULL) {
1603 *p_fp = fp;
1604 return fdp;
1605 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001606#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 path = PySys_GetObject("path");
1608 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (path == NULL || !PyList_Check(path)) {
1611 PyErr_SetString(PyExc_ImportError,
1612 "sys.path must be a list of directory names");
1613 return NULL;
1614 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 path_hooks = PySys_GetObject("path_hooks");
1617 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1618 PyErr_SetString(PyExc_ImportError,
1619 "sys.path_hooks must be a list of "
1620 "import hooks");
1621 return NULL;
1622 }
1623 path_importer_cache = PySys_GetObject("path_importer_cache");
1624 if (path_importer_cache == NULL ||
1625 !PyDict_Check(path_importer_cache)) {
1626 PyErr_SetString(PyExc_ImportError,
1627 "sys.path_importer_cache must be a dict");
1628 return NULL;
1629 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 npath = PyList_Size(path);
1632 namelen = strlen(name);
1633 for (i = 0; i < npath; i++) {
1634 PyObject *v = PyList_GetItem(path, i);
1635 PyObject *origv = v;
1636 const char *base;
1637 Py_ssize_t size;
1638 if (!v)
1639 return NULL;
1640 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001641 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (v == NULL)
1643 return NULL;
1644 }
1645 else if (!PyBytes_Check(v))
1646 continue;
1647 else
1648 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 base = PyBytes_AS_STRING(v);
1651 size = PyBytes_GET_SIZE(v);
1652 len = size;
1653 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1654 Py_DECREF(v);
1655 continue; /* Too long */
1656 }
1657 strcpy(buf, base);
1658 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 if (strlen(buf) != len) {
1661 continue; /* v contains '\0' */
1662 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 /* sys.path_hooks import hook */
1665 if (p_loader != NULL) {
1666 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 importer = get_path_importer(path_importer_cache,
1669 path_hooks, origv);
1670 if (importer == NULL) {
1671 return NULL;
1672 }
1673 /* Note: importer is a borrowed reference */
1674 if (importer != Py_None) {
1675 PyObject *loader;
1676 loader = PyObject_CallMethod(importer,
1677 "find_module",
1678 "s", fullname);
1679 if (loader == NULL)
1680 return NULL; /* error */
1681 if (loader != Py_None) {
1682 /* a loader was found */
1683 *p_loader = loader;
1684 return &importhookdescr;
1685 }
1686 Py_DECREF(loader);
1687 continue;
1688 }
1689 }
1690 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001693#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001695#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 )
1697 buf[len++] = SEP;
1698 strcpy(buf+len, name);
1699 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* Check for package import (buf holds a directory name,
1702 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001703#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 if (stat(buf, &statbuf) == 0 && /* it exists */
1705 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1706 case_ok(buf, len, namelen, name)) { /* case matches */
1707 if (find_init_module(buf)) { /* and has __init__.py */
1708 return &fd_package;
1709 }
1710 else {
1711 char warnstr[MAXPATHLEN+80];
1712 sprintf(warnstr, "Not importing directory "
1713 "'%.*s': missing __init__.py",
1714 MAXPATHLEN, buf);
1715 if (PyErr_WarnEx(PyExc_ImportWarning,
1716 warnstr, 1)) {
1717 return NULL;
1718 }
1719 }
1720 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001721#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001722#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 /* take a snapshot of the module spec for restoration
1724 * after the 8 character DLL hackery
1725 */
1726 saved_buf = strdup(buf);
1727 saved_len = len;
1728 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001729#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001731#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 /* OS/2 limits DLLs to 8 character names (w/o
1733 extension)
1734 * so if the name is longer than that and its a
1735 * dynamically loaded module we're going to try,
1736 * truncate the name before trying
1737 */
1738 if (strlen(subname) > 8) {
1739 /* is this an attempt to load a C extension? */
1740 const struct filedescr *scan;
1741 scan = _PyImport_DynLoadFiletab;
1742 while (scan->suffix != NULL) {
1743 if (!strcmp(scan->suffix, fdp->suffix))
1744 break;
1745 else
1746 scan++;
1747 }
1748 if (scan->suffix != NULL) {
1749 /* yes, so truncate the name */
1750 namelen = 8;
1751 len -= strlen(subname) - namelen;
1752 buf[len] = '\0';
1753 }
1754 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001755#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 strcpy(buf+len, fdp->suffix);
1757 if (Py_VerboseFlag > 1)
1758 PySys_WriteStderr("# trying %s\n", buf);
1759 filemode = fdp->mode;
1760 if (filemode[0] == 'U')
1761 filemode = "r" PY_STDIOTEXTMODE;
1762 fp = fopen(buf, filemode);
1763 if (fp != NULL) {
1764 if (case_ok(buf, len, namelen, name))
1765 break;
1766 else { /* continue search */
1767 fclose(fp);
1768 fp = NULL;
1769 }
1770 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001771#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* restore the saved snapshot */
1773 strcpy(buf, saved_buf);
1774 len = saved_len;
1775 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001776#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001778#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 /* don't need/want the module name snapshot anymore */
1780 if (saved_buf)
1781 {
1782 free(saved_buf);
1783 saved_buf = NULL;
1784 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001785#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 if (fp != NULL)
1787 break;
1788 }
1789 if (fp == NULL) {
1790 PyErr_Format(PyExc_ImportError,
1791 "No module named %.200s", name);
1792 return NULL;
1793 }
1794 *p_fp = fp;
1795 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001796}
1797
Martin v. Löwis18e16552006-02-15 17:27:45 +00001798/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001799 * The arguments here are tricky, best shown by example:
1800 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1801 * ^ ^ ^ ^
1802 * |--------------------- buf ---------------------|
1803 * |------------------- len ------------------|
1804 * |------ name -------|
1805 * |----- namelen -----|
1806 * buf is the full path, but len only counts up to (& exclusive of) the
1807 * extension. name is the module name, also exclusive of extension.
1808 *
1809 * We've already done a successful stat() or fopen() on buf, so know that
1810 * there's some match, possibly case-insensitive.
1811 *
Tim Peters50d8d372001-02-28 05:34:27 +00001812 * case_ok() is to return 1 if there's a case-sensitive match for
1813 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1814 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001815 *
Tim Peters50d8d372001-02-28 05:34:27 +00001816 * case_ok() is used to implement case-sensitive import semantics even
1817 * on platforms with case-insensitive filesystems. It's trivial to implement
1818 * for case-sensitive filesystems. It's pretty much a cross-platform
1819 * nightmare for systems with case-insensitive filesystems.
1820 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001821
Tim Peters50d8d372001-02-28 05:34:27 +00001822/* First we may need a pile of platform-specific header files; the sequence
1823 * of #if's here should match the sequence in the body of case_ok().
1824 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001825#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001826#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001827
Tim Peters50d8d372001-02-28 05:34:27 +00001828#elif defined(DJGPP)
1829#include <dir.h>
1830
Jason Tishler7961aa62005-05-20 00:56:54 +00001831#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001832#include <sys/types.h>
1833#include <dirent.h>
1834
Andrew MacIntyred9400542002-02-26 11:41:34 +00001835#elif defined(PYOS_OS2)
1836#define INCL_DOS
1837#define INCL_DOSERRORS
1838#define INCL_NOPMAPI
1839#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001840#endif
1841
Guido van Rossum0980bd91998-02-13 17:18:36 +00001842static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001843case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001844{
Tim Peters50d8d372001-02-28 05:34:27 +00001845/* Pick a platform-specific implementation; the sequence of #if's here should
1846 * match the sequence just above.
1847 */
1848
Jason Tishler7961aa62005-05-20 00:56:54 +00001849/* MS_WINDOWS */
1850#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 WIN32_FIND_DATA data;
1852 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (Py_GETENV("PYTHONCASEOK") != NULL)
1855 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 h = FindFirstFile(buf, &data);
1858 if (h == INVALID_HANDLE_VALUE) {
1859 PyErr_Format(PyExc_NameError,
1860 "Can't find file for module %.100s\n(filename %.300s)",
1861 name, buf);
1862 return 0;
1863 }
1864 FindClose(h);
1865 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001866
1867/* DJGPP */
1868#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 struct ffblk ffblk;
1870 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (Py_GETENV("PYTHONCASEOK") != NULL)
1873 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1876 if (done) {
1877 PyErr_Format(PyExc_NameError,
1878 "Can't find file for module %.100s\n(filename %.300s)",
1879 name, buf);
1880 return 0;
1881 }
1882 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001883
Jason Tishler7961aa62005-05-20 00:56:54 +00001884/* new-fangled macintosh (macosx) or Cygwin */
1885#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 DIR *dirp;
1887 struct dirent *dp;
1888 char dirname[MAXPATHLEN + 1];
1889 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (Py_GETENV("PYTHONCASEOK") != NULL)
1892 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* Copy the dir component into dirname; substitute "." if empty */
1895 if (dirlen <= 0) {
1896 dirname[0] = '.';
1897 dirname[1] = '\0';
1898 }
1899 else {
1900 assert(dirlen <= MAXPATHLEN);
1901 memcpy(dirname, buf, dirlen);
1902 dirname[dirlen] = '\0';
1903 }
1904 /* Open the directory and search the entries for an exact match. */
1905 dirp = opendir(dirname);
1906 if (dirp) {
1907 char *nameWithExt = buf + len - namelen;
1908 while ((dp = readdir(dirp)) != NULL) {
1909 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001910#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001912#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001914#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 if (thislen >= namelen &&
1916 strcmp(dp->d_name, nameWithExt) == 0) {
1917 (void)closedir(dirp);
1918 return 1; /* Found */
1919 }
1920 }
1921 (void)closedir(dirp);
1922 }
1923 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001924
Andrew MacIntyred9400542002-02-26 11:41:34 +00001925/* OS/2 */
1926#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 HDIR hdir = 1;
1928 ULONG srchcnt = 1;
1929 FILEFINDBUF3 ffbuf;
1930 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 if (Py_GETENV("PYTHONCASEOK") != NULL)
1933 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 rc = DosFindFirst(buf,
1936 &hdir,
1937 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1938 &ffbuf, sizeof(ffbuf),
1939 &srchcnt,
1940 FIL_STANDARD);
1941 if (rc != NO_ERROR)
1942 return 0;
1943 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001944
Tim Peters50d8d372001-02-28 05:34:27 +00001945/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1946#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001948
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001949#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001950}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001951
Victor Stinnerf52b7052010-08-14 17:06:04 +00001952/* Call _wfopen() on Windows, or fopen() otherwise. Return the new file
1953 object on success, or NULL if the file cannot be open or (if
1954 PyErr_Occurred()) on unicode error */
1955
1956FILE*
1957_Py_fopen(PyObject *unicode, const char *mode)
1958{
1959#ifdef MS_WINDOWS
1960 wchar_t path[MAXPATHLEN+1];
1961 wchar_t wmode[10];
1962 Py_ssize_t len;
1963 int usize;
1964
1965 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
1966 if (len == -1)
1967 return NULL;
1968 path[len] = L'\0';
1969
1970 usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
1971 if (usize == 0)
1972 return NULL;
1973
1974 return _wfopen(path, wmode);
1975#else
1976 FILE *f;
1977 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
1978 if (bytes == NULL)
1979 return NULL;
1980 f = fopen(PyBytes_AS_STRING(bytes), mode);
1981 Py_DECREF(bytes);
1982 return f;
1983#endif
1984}
Guido van Rossum0980bd91998-02-13 17:18:36 +00001985
Guido van Rossum197346f1997-10-31 18:38:52 +00001986#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001987
1988/* Call _wstat() on Windows, or stat() otherwise. Only fill st_mode
1989 attribute on Windows. Return 0 on success, -1 on stat error or (if
1990 PyErr_Occurred()) unicode error. */
1991
1992int
1993_Py_stat(PyObject *unicode, struct stat *statbuf)
1994{
1995#ifdef MS_WINDOWS
1996 wchar_t path[MAXPATHLEN+1];
1997 Py_ssize_t len;
1998 int err;
1999 struct _stat wstatbuf;
2000
Victor Stinner8a79dcc2010-08-14 16:59:08 +00002001 len = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, path, MAXPATHLEN);
Victor Stinner4f4402c2010-08-14 14:50:26 +00002002 if (len == -1)
2003 return -1;
Victor Stinner8a79dcc2010-08-14 16:59:08 +00002004 path[len] = L'\0';
2005
Victor Stinner4f4402c2010-08-14 14:50:26 +00002006 err = _wstat(path, &wstatbuf);
2007 if (!err)
2008 statbuf->st_mode = wstatbuf.st_mode;
2009 return err;
2010#else
2011 int ret;
2012 PyObject *bytes = PyUnicode_EncodeFSDefault(unicode);
2013 if (bytes == NULL)
2014 return -1;
2015 ret = stat(PyBytes_AS_STRING(bytes), statbuf);
2016 Py_DECREF(bytes);
2017 return ret;
2018#endif
2019}
2020
Guido van Rossum197346f1997-10-31 18:38:52 +00002021/* Helper to look for __init__.py or __init__.py[co] in potential package */
2022static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002023find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 const size_t save_len = strlen(buf);
2026 size_t i = save_len;
2027 char *pname; /* pointer to start of __init__ */
2028 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030/* For calling case_ok(buf, len, namelen, name):
2031 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2032 * ^ ^ ^ ^
2033 * |--------------------- buf ---------------------|
2034 * |------------------- len ------------------|
2035 * |------ name -------|
2036 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002037 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (save_len + 13 >= MAXPATHLEN)
2039 return 0;
2040 buf[i++] = SEP;
2041 pname = buf + i;
2042 strcpy(pname, "__init__.py");
2043 if (stat(buf, &statbuf) == 0) {
2044 if (case_ok(buf,
2045 save_len + 9, /* len("/__init__") */
2046 8, /* len("__init__") */
2047 pname)) {
2048 buf[save_len] = '\0';
2049 return 1;
2050 }
2051 }
2052 i += strlen(pname);
2053 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2054 if (stat(buf, &statbuf) == 0) {
2055 if (case_ok(buf,
2056 save_len + 9, /* len("/__init__") */
2057 8, /* len("__init__") */
2058 pname)) {
2059 buf[save_len] = '\0';
2060 return 1;
2061 }
2062 }
2063 buf[save_len] = '\0';
2064 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002065}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002066
Guido van Rossum197346f1997-10-31 18:38:52 +00002067#endif /* HAVE_STAT */
2068
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002069
Tim Petersdbd9ba62000-07-09 03:09:57 +00002070static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002071
Victor Stinner44c6c152010-08-09 00:59:10 +00002072static PyObject*
2073load_builtin(char *name, char *pathname, int type)
2074{
2075 PyObject *m, *modules;
2076 int err;
2077
2078 if (pathname != NULL && pathname[0] != '\0')
2079 name = pathname;
2080
2081 if (type == C_BUILTIN)
2082 err = init_builtin(name);
2083 else
2084 err = PyImport_ImportFrozenModule(name);
2085 if (err < 0)
2086 return NULL;
2087 if (err == 0) {
2088 PyErr_Format(PyExc_ImportError,
2089 "Purported %s module %.200s not found",
2090 type == C_BUILTIN ?
2091 "builtin" : "frozen",
2092 name);
2093 return NULL;
2094 }
2095
2096 modules = PyImport_GetModuleDict();
2097 m = PyDict_GetItemString(modules, name);
2098 if (m == NULL) {
2099 PyErr_Format(
2100 PyExc_ImportError,
2101 "%s module %.200s not properly initialized",
2102 type == C_BUILTIN ?
2103 "builtin" : "frozen",
2104 name);
2105 return NULL;
2106 }
2107 Py_INCREF(m);
2108 return m;
2109}
2110
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002111/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002112 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002113
Guido van Rossum79f25d91997-04-29 20:08:16 +00002114static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002115load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 /* First check that there's an open file (if we need one) */
2120 switch (type) {
2121 case PY_SOURCE:
2122 case PY_COMPILED:
2123 if (fp == NULL) {
2124 PyErr_Format(PyExc_ValueError,
2125 "file object required for import (type code %d)",
2126 type);
2127 return NULL;
2128 }
2129 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 case PY_SOURCE:
2134 m = load_source_module(name, pathname, fp);
2135 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 case PY_COMPILED:
2138 m = load_compiled_module(name, pathname, fp);
2139 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002140
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002141#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 case C_EXTENSION:
2143 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2144 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002145#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 case PKG_DIRECTORY:
2148 m = load_package(name, pathname);
2149 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 case C_BUILTIN:
2152 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002153 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 case IMP_HOOK: {
2157 if (loader == NULL) {
2158 PyErr_SetString(PyExc_ImportError,
2159 "import hook without loader");
2160 return NULL;
2161 }
2162 m = PyObject_CallMethod(loader, "load_module", "s", name);
2163 break;
2164 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 default:
2167 PyErr_Format(PyExc_ImportError,
2168 "Don't know how to import %.200s (type code %d)",
2169 name, type);
2170 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002175}
2176
2177
2178/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002179 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002180 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002181
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002182static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002183init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (_PyImport_FindExtension(name, name) != NULL)
2188 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 for (p = PyImport_Inittab; p->name != NULL; p++) {
2191 PyObject *mod;
2192 if (strcmp(name, p->name) == 0) {
2193 if (p->initfunc == NULL) {
2194 PyErr_Format(PyExc_ImportError,
2195 "Cannot re-init internal module %.200s",
2196 name);
2197 return -1;
2198 }
2199 if (Py_VerboseFlag)
2200 PySys_WriteStderr("import %s # builtin\n", name);
2201 mod = (*p->initfunc)();
2202 if (mod == 0)
2203 return -1;
2204 if (_PyImport_FixupExtension(mod, name, name) < 0)
2205 return -1;
2206 /* FixupExtension has put the module into sys.modules,
2207 so we can release our own reference. */
2208 Py_DECREF(mod);
2209 return 1;
2210 }
2211 }
2212 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002213}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002214
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002215
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002216/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002217
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002218static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002219find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 if (!name)
2224 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 for (p = PyImport_FrozenModules; ; p++) {
2227 if (p->name == NULL)
2228 return NULL;
2229 if (strcmp(p->name, name) == 0)
2230 break;
2231 }
2232 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002233}
2234
Guido van Rossum79f25d91997-04-29 20:08:16 +00002235static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002236get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 struct _frozen *p = find_frozen(name);
2239 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (p == NULL) {
2242 PyErr_Format(PyExc_ImportError,
2243 "No such frozen object named %.200s",
2244 name);
2245 return NULL;
2246 }
2247 if (p->code == NULL) {
2248 PyErr_Format(PyExc_ImportError,
2249 "Excluded frozen object named %.200s",
2250 name);
2251 return NULL;
2252 }
2253 size = p->size;
2254 if (size < 0)
2255 size = -size;
2256 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002257}
2258
Brett Cannon8d110132009-03-15 02:20:16 +00002259static PyObject *
2260is_frozen_package(char *name)
2261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 struct _frozen *p = find_frozen(name);
2263 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (p == NULL) {
2266 PyErr_Format(PyExc_ImportError,
2267 "No such frozen object named %.200s",
2268 name);
2269 return NULL;
2270 }
Brett Cannon8d110132009-03-15 02:20:16 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 if (size < 0)
2275 Py_RETURN_TRUE;
2276 else
2277 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002278}
2279
2280
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002281/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002282 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002283 an exception set if the initialization failed.
2284 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002285
2286int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002287PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 struct _frozen *p = find_frozen(name);
2290 PyObject *co;
2291 PyObject *m;
2292 int ispackage;
2293 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (p == NULL)
2296 return 0;
2297 if (p->code == NULL) {
2298 PyErr_Format(PyExc_ImportError,
2299 "Excluded frozen object named %.200s",
2300 name);
2301 return -1;
2302 }
2303 size = p->size;
2304 ispackage = (size < 0);
2305 if (ispackage)
2306 size = -size;
2307 if (Py_VerboseFlag)
2308 PySys_WriteStderr("import %s # frozen%s\n",
2309 name, ispackage ? " package" : "");
2310 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2311 if (co == NULL)
2312 return -1;
2313 if (!PyCode_Check(co)) {
2314 PyErr_Format(PyExc_TypeError,
2315 "frozen object %.200s is not a code object",
2316 name);
2317 goto err_return;
2318 }
2319 if (ispackage) {
2320 /* Set __path__ to the package name */
2321 PyObject *d, *s, *l;
2322 int err;
2323 m = PyImport_AddModule(name);
2324 if (m == NULL)
2325 goto err_return;
2326 d = PyModule_GetDict(m);
2327 s = PyUnicode_InternFromString(name);
2328 if (s == NULL)
2329 goto err_return;
2330 l = PyList_New(1);
2331 if (l == NULL) {
2332 Py_DECREF(s);
2333 goto err_return;
2334 }
2335 PyList_SET_ITEM(l, 0, s);
2336 err = PyDict_SetItemString(d, "__path__", l);
2337 Py_DECREF(l);
2338 if (err != 0)
2339 goto err_return;
2340 }
2341 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2342 if (m == NULL)
2343 goto err_return;
2344 Py_DECREF(co);
2345 Py_DECREF(m);
2346 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002347err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 Py_DECREF(co);
2349 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002350}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002351
2352
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002353/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002354 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002355
Guido van Rossum79f25d91997-04-29 20:08:16 +00002356PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002357PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 PyObject *pname;
2360 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 pname = PyUnicode_FromString(name);
2363 if (pname == NULL)
2364 return NULL;
2365 result = PyImport_Import(pname);
2366 Py_DECREF(pname);
2367 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002368}
2369
Christian Heimes072c0f12008-01-03 23:01:04 +00002370/* Import a module without blocking
2371 *
2372 * At first it tries to fetch the module from sys.modules. If the module was
2373 * never loaded before it loads it with PyImport_ImportModule() unless another
2374 * thread holds the import lock. In the latter case the function raises an
2375 * ImportError instead of blocking.
2376 *
2377 * Returns the module object with incremented ref count.
2378 */
2379PyObject *
2380PyImport_ImportModuleNoBlock(const char *name)
2381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 PyObject *result;
2383 PyObject *modules;
2384 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* Try to get the module from sys.modules[name] */
2387 modules = PyImport_GetModuleDict();
2388 if (modules == NULL)
2389 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 result = PyDict_GetItemString(modules, name);
2392 if (result != NULL) {
2393 Py_INCREF(result);
2394 return result;
2395 }
2396 else {
2397 PyErr_Clear();
2398 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002399#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* check the import lock
2401 * me might be -1 but I ignore the error here, the lock function
2402 * takes care of the problem */
2403 me = PyThread_get_thread_ident();
2404 if (import_lock_thread == -1 || import_lock_thread == me) {
2405 /* no thread or me is holding the lock */
2406 return PyImport_ImportModule(name);
2407 }
2408 else {
2409 PyErr_Format(PyExc_ImportError,
2410 "Failed to import %.200s because the import lock"
2411 "is held by another thread.",
2412 name);
2413 return NULL;
2414 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002415#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002417#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002418}
2419
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002420/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002421static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002423static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002425static int mark_miss(char *name);
2426static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002428static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002429
2430/* The Magnum Opus of dotted-name import :-) */
2431
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002432static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002433import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 char buf[MAXPATHLEN+1];
2437 Py_ssize_t buflen = 0;
2438 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002441#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002443#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 ) {
2445 PyErr_SetString(PyExc_ImportError,
2446 "Import by filename is not supported.");
2447 return NULL;
2448 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 parent = get_parent(globals, buf, &buflen, level);
2451 if (parent == NULL)
2452 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002453
Benjamin Peterson556d8002010-06-27 22:37:28 +00002454 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2455 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 if (head == NULL)
2457 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 tail = head;
2460 Py_INCREF(tail);
2461 while (name) {
2462 next = load_next(tail, tail, &name, buf, &buflen);
2463 Py_DECREF(tail);
2464 if (next == NULL) {
2465 Py_DECREF(head);
2466 return NULL;
2467 }
2468 tail = next;
2469 }
2470 if (tail == Py_None) {
2471 /* If tail is Py_None, both get_parent and load_next found
2472 an empty module name: someone called __import__("") or
2473 doctored faulty bytecode */
2474 Py_DECREF(tail);
2475 Py_DECREF(head);
2476 PyErr_SetString(PyExc_ValueError,
2477 "Empty module name");
2478 return NULL;
2479 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (fromlist != NULL) {
2482 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2483 fromlist = NULL;
2484 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (fromlist == NULL) {
2487 Py_DECREF(tail);
2488 return head;
2489 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 Py_DECREF(head);
2492 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2493 Py_DECREF(tail);
2494 return NULL;
2495 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002498}
2499
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002500PyObject *
2501PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 PyObject *result;
2505 _PyImport_AcquireLock();
2506 result = import_module_level(name, globals, locals, fromlist, level);
2507 if (_PyImport_ReleaseLock() < 0) {
2508 Py_XDECREF(result);
2509 PyErr_SetString(PyExc_RuntimeError,
2510 "not holding the import lock");
2511 return NULL;
2512 }
2513 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002514}
2515
Fred Drake87590902004-05-28 20:21:36 +00002516/* Return the package that an import is being performed in. If globals comes
2517 from the module foo.bar.bat (not itself a package), this returns the
2518 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002519 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002520
2521 The *name* of the returned package is returned in buf, with the length of
2522 the name in *p_buflen.
2523
2524 If globals doesn't come from a package or a module in a package, or a
2525 corresponding entry is not found in sys.modules, Py_None is returned.
2526*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002527static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002528get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 static PyObject *namestr = NULL;
2531 static PyObject *pathstr = NULL;
2532 static PyObject *pkgstr = NULL;
2533 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2534 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (globals == NULL || !PyDict_Check(globals) || !level)
2537 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (namestr == NULL) {
2540 namestr = PyUnicode_InternFromString("__name__");
2541 if (namestr == NULL)
2542 return NULL;
2543 }
2544 if (pathstr == NULL) {
2545 pathstr = PyUnicode_InternFromString("__path__");
2546 if (pathstr == NULL)
2547 return NULL;
2548 }
2549 if (pkgstr == NULL) {
2550 pkgstr = PyUnicode_InternFromString("__package__");
2551 if (pkgstr == NULL)
2552 return NULL;
2553 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 *buf = '\0';
2556 *p_buflen = 0;
2557 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if ((pkgname != NULL) && (pkgname != Py_None)) {
2560 /* __package__ is set, so use it */
2561 char *pkgname_str;
2562 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (!PyUnicode_Check(pkgname)) {
2565 PyErr_SetString(PyExc_ValueError,
2566 "__package__ set to non-string");
2567 return NULL;
2568 }
2569 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2570 if (len == 0) {
2571 if (level > 0) {
2572 PyErr_SetString(PyExc_ValueError,
2573 "Attempted relative import in non-package");
2574 return NULL;
2575 }
2576 return Py_None;
2577 }
2578 if (len > MAXPATHLEN) {
2579 PyErr_SetString(PyExc_ValueError,
2580 "Package name too long");
2581 return NULL;
2582 }
2583 strcpy(buf, pkgname_str);
2584 } else {
2585 /* __package__ not set, so figure it out and set it */
2586 modname = PyDict_GetItem(globals, namestr);
2587 if (modname == NULL || !PyUnicode_Check(modname))
2588 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 modpath = PyDict_GetItem(globals, pathstr);
2591 if (modpath != NULL) {
2592 /* __path__ is set, so modname is already the package name */
2593 char *modname_str;
2594 Py_ssize_t len;
2595 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2598 if (len > MAXPATHLEN) {
2599 PyErr_SetString(PyExc_ValueError,
2600 "Module name too long");
2601 return NULL;
2602 }
2603 strcpy(buf, modname_str);
2604 error = PyDict_SetItem(globals, pkgstr, modname);
2605 if (error) {
2606 PyErr_SetString(PyExc_ValueError,
2607 "Could not set __package__");
2608 return NULL;
2609 }
2610 } else {
2611 /* Normal module, so work out the package name if any */
2612 char *start = _PyUnicode_AsString(modname);
2613 char *lastdot = strrchr(start, '.');
2614 size_t len;
2615 int error;
2616 if (lastdot == NULL && level > 0) {
2617 PyErr_SetString(PyExc_ValueError,
2618 "Attempted relative import in non-package");
2619 return NULL;
2620 }
2621 if (lastdot == NULL) {
2622 error = PyDict_SetItem(globals, pkgstr, Py_None);
2623 if (error) {
2624 PyErr_SetString(PyExc_ValueError,
2625 "Could not set __package__");
2626 return NULL;
2627 }
2628 return Py_None;
2629 }
2630 len = lastdot - start;
2631 if (len >= MAXPATHLEN) {
2632 PyErr_SetString(PyExc_ValueError,
2633 "Module name too long");
2634 return NULL;
2635 }
2636 strncpy(buf, start, len);
2637 buf[len] = '\0';
2638 pkgname = PyUnicode_FromString(buf);
2639 if (pkgname == NULL) {
2640 return NULL;
2641 }
2642 error = PyDict_SetItem(globals, pkgstr, pkgname);
2643 Py_DECREF(pkgname);
2644 if (error) {
2645 PyErr_SetString(PyExc_ValueError,
2646 "Could not set __package__");
2647 return NULL;
2648 }
2649 }
2650 }
2651 while (--level > 0) {
2652 char *dot = strrchr(buf, '.');
2653 if (dot == NULL) {
2654 PyErr_SetString(PyExc_ValueError,
2655 "Attempted relative import beyond "
2656 "toplevel package");
2657 return NULL;
2658 }
2659 *dot = '\0';
2660 }
2661 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 modules = PyImport_GetModuleDict();
2664 parent = PyDict_GetItemString(modules, buf);
2665 if (parent == NULL) {
2666 if (orig_level < 1) {
2667 PyObject *err_msg = PyBytes_FromFormat(
2668 "Parent module '%.200s' not found "
2669 "while handling absolute import", buf);
2670 if (err_msg == NULL) {
2671 return NULL;
2672 }
2673 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2674 PyBytes_AsString(err_msg), 1)) {
2675 *buf = '\0';
2676 *p_buflen = 0;
2677 parent = Py_None;
2678 }
2679 Py_DECREF(err_msg);
2680 } else {
2681 PyErr_Format(PyExc_SystemError,
2682 "Parent module '%.200s' not loaded, "
2683 "cannot perform relative import", buf);
2684 }
2685 }
2686 return parent;
2687 /* We expect, but can't guarantee, if parent != None, that:
2688 - parent.__name__ == buf
2689 - parent.__dict__ is globals
2690 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002691}
2692
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002693/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002694static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002695load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 char *name = *p_name;
2699 char *dot = strchr(name, '.');
2700 size_t len;
2701 char *p;
2702 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (strlen(name) == 0) {
2705 /* completely empty module name should only happen in
2706 'from . import' (or '__import__("")')*/
2707 Py_INCREF(mod);
2708 *p_name = NULL;
2709 return mod;
2710 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 if (dot == NULL) {
2713 *p_name = NULL;
2714 len = strlen(name);
2715 }
2716 else {
2717 *p_name = dot+1;
2718 len = dot-name;
2719 }
2720 if (len == 0) {
2721 PyErr_SetString(PyExc_ValueError,
2722 "Empty module name");
2723 return NULL;
2724 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 p = buf + *p_buflen;
2727 if (p != buf)
2728 *p++ = '.';
2729 if (p+len-buf >= MAXPATHLEN) {
2730 PyErr_SetString(PyExc_ValueError,
2731 "Module name too long");
2732 return NULL;
2733 }
2734 strncpy(p, name, len);
2735 p[len] = '\0';
2736 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 result = import_submodule(mod, p, buf);
2739 if (result == Py_None && altmod != mod) {
2740 Py_DECREF(result);
2741 /* Here, altmod must be None and mod must not be None */
2742 result = import_submodule(altmod, p, p);
2743 if (result != NULL && result != Py_None) {
2744 if (mark_miss(buf) != 0) {
2745 Py_DECREF(result);
2746 return NULL;
2747 }
2748 strncpy(buf, name, len);
2749 buf[len] = '\0';
2750 *p_buflen = len;
2751 }
2752 }
2753 if (result == NULL)
2754 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 if (result == Py_None) {
2757 Py_DECREF(result);
2758 PyErr_Format(PyExc_ImportError,
2759 "No module named %.200s", name);
2760 return NULL;
2761 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002764}
2765
2766static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002767mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 PyObject *modules = PyImport_GetModuleDict();
2770 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002771}
2772
2773static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002774ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 if (!PyObject_HasAttrString(mod, "__path__"))
2780 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 for (i = 0; ; i++) {
2783 PyObject *item = PySequence_GetItem(fromlist, i);
2784 int hasit;
2785 if (item == NULL) {
2786 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2787 PyErr_Clear();
2788 return 1;
2789 }
2790 return 0;
2791 }
2792 if (!PyUnicode_Check(item)) {
2793 PyErr_SetString(PyExc_TypeError,
2794 "Item in ``from list'' not a string");
2795 Py_DECREF(item);
2796 return 0;
2797 }
2798 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2799 PyObject *all;
2800 Py_DECREF(item);
2801 /* See if the package defines __all__ */
2802 if (recursive)
2803 continue; /* Avoid endless recursion */
2804 all = PyObject_GetAttrString(mod, "__all__");
2805 if (all == NULL)
2806 PyErr_Clear();
2807 else {
2808 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2809 Py_DECREF(all);
2810 if (!ret)
2811 return 0;
2812 }
2813 continue;
2814 }
2815 hasit = PyObject_HasAttr(mod, item);
2816 if (!hasit) {
2817 PyObject *item8;
2818 char *subname;
2819 PyObject *submod;
2820 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002821 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 if (!item8) {
2823 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2824 return 0;
2825 }
2826 subname = PyBytes_AS_STRING(item8);
2827 if (buflen + strlen(subname) >= MAXPATHLEN) {
2828 PyErr_SetString(PyExc_ValueError,
2829 "Module name too long");
2830 Py_DECREF(item);
2831 return 0;
2832 }
2833 p = buf + buflen;
2834 *p++ = '.';
2835 strcpy(p, subname);
2836 submod = import_submodule(mod, subname, buf);
2837 Py_DECREF(item8);
2838 Py_XDECREF(submod);
2839 if (submod == NULL) {
2840 Py_DECREF(item);
2841 return 0;
2842 }
2843 }
2844 Py_DECREF(item);
2845 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002848}
2849
Neil Schemenauer00b09662003-06-16 21:03:07 +00002850static int
2851add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (mod == Py_None)
2855 return 1;
2856 /* Irrespective of the success of this load, make a
2857 reference to it in the parent package module. A copy gets
2858 saved in the modules dictionary under the full name, so get a
2859 reference from there, if need be. (The exception is when the
2860 load failed with a SyntaxError -- then there's no trace in
2861 sys.modules. In that case, of course, do nothing extra.) */
2862 if (submod == NULL) {
2863 submod = PyDict_GetItemString(modules, fullname);
2864 if (submod == NULL)
2865 return 1;
2866 }
2867 if (PyModule_Check(mod)) {
2868 /* We can't use setattr here since it can give a
2869 * spurious warning if the submodule name shadows a
2870 * builtin name */
2871 PyObject *dict = PyModule_GetDict(mod);
2872 if (!dict)
2873 return 0;
2874 if (PyDict_SetItemString(dict, subname, submod) < 0)
2875 return 0;
2876 }
2877 else {
2878 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2879 return 0;
2880 }
2881 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002882}
2883
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002884static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002885import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyObject *modules = PyImport_GetModuleDict();
2888 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 /* Require:
2891 if mod == None: subname == fullname
2892 else: mod.__name__ + "." + subname == fullname
2893 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2896 Py_INCREF(m);
2897 }
2898 else {
2899 PyObject *path, *loader = NULL;
2900 char buf[MAXPATHLEN+1];
2901 struct filedescr *fdp;
2902 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 if (mod == Py_None)
2905 path = NULL;
2906 else {
2907 path = PyObject_GetAttrString(mod, "__path__");
2908 if (path == NULL) {
2909 PyErr_Clear();
2910 Py_INCREF(Py_None);
2911 return Py_None;
2912 }
2913 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 buf[0] = '\0';
2916 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2917 &fp, &loader);
2918 Py_XDECREF(path);
2919 if (fdp == NULL) {
2920 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2921 return NULL;
2922 PyErr_Clear();
2923 Py_INCREF(Py_None);
2924 return Py_None;
2925 }
2926 m = load_module(fullname, fp, buf, fdp->type, loader);
2927 Py_XDECREF(loader);
2928 if (fp)
2929 fclose(fp);
2930 if (!add_submodule(mod, m, fullname, subname, modules)) {
2931 Py_XDECREF(m);
2932 m = NULL;
2933 }
2934 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002937}
2938
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002939
2940/* Re-import a module of any kind and return its module object, WITH
2941 INCREMENTED REFERENCE COUNT */
2942
Guido van Rossum79f25d91997-04-29 20:08:16 +00002943PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002944PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 PyInterpreterState *interp = PyThreadState_Get()->interp;
2947 PyObject *modules_reloading = interp->modules_reloading;
2948 PyObject *modules = PyImport_GetModuleDict();
2949 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2950 char *name, *subname;
2951 char buf[MAXPATHLEN+1];
2952 struct filedescr *fdp;
2953 FILE *fp = NULL;
2954 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 if (modules_reloading == NULL) {
2957 Py_FatalError("PyImport_ReloadModule: "
2958 "no modules_reloading dictionary!");
2959 return NULL;
2960 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 if (m == NULL || !PyModule_Check(m)) {
2963 PyErr_SetString(PyExc_TypeError,
2964 "reload() argument must be module");
2965 return NULL;
2966 }
2967 name = (char*)PyModule_GetName(m);
2968 if (name == NULL)
2969 return NULL;
2970 if (m != PyDict_GetItemString(modules, name)) {
2971 PyErr_Format(PyExc_ImportError,
2972 "reload(): module %.200s not in sys.modules",
2973 name);
2974 return NULL;
2975 }
2976 existing_m = PyDict_GetItemString(modules_reloading, name);
2977 if (existing_m != NULL) {
2978 /* Due to a recursive reload, this module is already
2979 being reloaded. */
2980 Py_INCREF(existing_m);
2981 return existing_m;
2982 }
2983 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2984 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 subname = strrchr(name, '.');
2987 if (subname == NULL)
2988 subname = name;
2989 else {
2990 PyObject *parentname, *parent;
2991 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2992 if (parentname == NULL) {
2993 imp_modules_reloading_clear();
2994 return NULL;
2995 }
2996 parent = PyDict_GetItem(modules, parentname);
2997 if (parent == NULL) {
2998 PyErr_Format(PyExc_ImportError,
2999 "reload(): parent %U not in sys.modules",
3000 parentname);
3001 Py_DECREF(parentname);
3002 imp_modules_reloading_clear();
3003 return NULL;
3004 }
3005 Py_DECREF(parentname);
3006 subname++;
3007 path = PyObject_GetAttrString(parent, "__path__");
3008 if (path == NULL)
3009 PyErr_Clear();
3010 }
3011 buf[0] = '\0';
3012 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3013 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 if (fdp == NULL) {
3016 Py_XDECREF(loader);
3017 imp_modules_reloading_clear();
3018 return NULL;
3019 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 newm = load_module(name, fp, buf, fdp->type, loader);
3022 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 if (fp)
3025 fclose(fp);
3026 if (newm == NULL) {
3027 /* load_module probably removed name from modules because of
3028 * the error. Put back the original module object. We're
3029 * going to return NULL in this case regardless of whether
3030 * replacing name succeeds, so the return value is ignored.
3031 */
3032 PyDict_SetItemString(modules, name, m);
3033 }
3034 imp_modules_reloading_clear();
3035 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003036}
3037
3038
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003039/* Higher-level import emulator which emulates the "import" statement
3040 more accurately -- it invokes the __import__() function from the
3041 builtins of the current globals. This means that the import is
3042 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00003043 environment, e.g. by "rexec".
3044 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003045 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003046 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003047
3048PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003049PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 static PyObject *silly_list = NULL;
3052 static PyObject *builtins_str = NULL;
3053 static PyObject *import_str = NULL;
3054 PyObject *globals = NULL;
3055 PyObject *import = NULL;
3056 PyObject *builtins = NULL;
3057 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 /* Initialize constant string objects */
3060 if (silly_list == NULL) {
3061 import_str = PyUnicode_InternFromString("__import__");
3062 if (import_str == NULL)
3063 return NULL;
3064 builtins_str = PyUnicode_InternFromString("__builtins__");
3065 if (builtins_str == NULL)
3066 return NULL;
3067 silly_list = Py_BuildValue("[s]", "__doc__");
3068 if (silly_list == NULL)
3069 return NULL;
3070 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 /* Get the builtins from current globals */
3073 globals = PyEval_GetGlobals();
3074 if (globals != NULL) {
3075 Py_INCREF(globals);
3076 builtins = PyObject_GetItem(globals, builtins_str);
3077 if (builtins == NULL)
3078 goto err;
3079 }
3080 else {
3081 /* No globals -- use standard builtins, and fake globals */
3082 builtins = PyImport_ImportModuleLevel("builtins",
3083 NULL, NULL, NULL, 0);
3084 if (builtins == NULL)
3085 return NULL;
3086 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3087 if (globals == NULL)
3088 goto err;
3089 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 /* Get the __import__ function from the builtins */
3092 if (PyDict_Check(builtins)) {
3093 import = PyObject_GetItem(builtins, import_str);
3094 if (import == NULL)
3095 PyErr_SetObject(PyExc_KeyError, import_str);
3096 }
3097 else
3098 import = PyObject_GetAttr(builtins, import_str);
3099 if (import == NULL)
3100 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 /* Call the __import__ function with the proper argument list
3103 * Always use absolute import here. */
3104 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3105 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003106
3107 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 Py_XDECREF(globals);
3109 Py_XDECREF(builtins);
3110 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003113}
3114
3115
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003116/* Module 'imp' provides Python access to the primitives used for
3117 importing modules.
3118*/
3119
Guido van Rossum79f25d91997-04-29 20:08:16 +00003120static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003121imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 buf[0] = (char) ((magic >> 0) & 0xff);
3126 buf[1] = (char) ((magic >> 8) & 0xff);
3127 buf[2] = (char) ((magic >> 16) & 0xff);
3128 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 return PyBytes_FromStringAndSize(buf, 4);
3131};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003132
3133static PyObject *
3134imp_get_magic(PyObject *self, PyObject *noargs)
3135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003137}
3138
3139static PyObject *
3140imp_get_tag(PyObject *self, PyObject *noargs)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003143}
3144
Guido van Rossum79f25d91997-04-29 20:08:16 +00003145static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003146imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 PyObject *list;
3149 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 list = PyList_New(0);
3152 if (list == NULL)
3153 return NULL;
3154 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3155 PyObject *item = Py_BuildValue("ssi",
3156 fdp->suffix, fdp->mode, fdp->type);
3157 if (item == NULL) {
3158 Py_DECREF(list);
3159 return NULL;
3160 }
3161 if (PyList_Append(list, item) < 0) {
3162 Py_DECREF(list);
3163 Py_DECREF(item);
3164 return NULL;
3165 }
3166 Py_DECREF(item);
3167 }
3168 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003169}
3170
Guido van Rossum79f25d91997-04-29 20:08:16 +00003171static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003172call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 extern int fclose(FILE *);
3175 PyObject *fob, *ret;
3176 PyObject *pathobj;
3177 struct filedescr *fdp;
3178 char pathname[MAXPATHLEN+1];
3179 FILE *fp = NULL;
3180 int fd = -1;
3181 char *found_encoding = NULL;
3182 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 pathname[0] = '\0';
3185 if (path == Py_None)
3186 path = NULL;
3187 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3188 if (fdp == NULL)
3189 return NULL;
3190 if (fp != NULL) {
3191 fd = fileno(fp);
3192 if (fd != -1)
3193 fd = dup(fd);
3194 fclose(fp);
3195 fp = NULL;
3196 }
3197 if (fd != -1) {
3198 if (strchr(fdp->mode, 'b') == NULL) {
3199 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3200 memory. */
3201 found_encoding = PyTokenizer_FindEncoding(fd);
3202 lseek(fd, 0, 0); /* Reset position */
3203 if (found_encoding == NULL && PyErr_Occurred())
3204 return NULL;
3205 encoding = (found_encoding != NULL) ? found_encoding :
3206 (char*)PyUnicode_GetDefaultEncoding();
3207 }
3208 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3209 (char*)encoding, NULL, NULL, 1);
3210 if (fob == NULL) {
3211 close(fd);
3212 PyMem_FREE(found_encoding);
3213 return NULL;
3214 }
3215 }
3216 else {
3217 fob = Py_None;
3218 Py_INCREF(fob);
3219 }
3220 pathobj = PyUnicode_DecodeFSDefault(pathname);
3221 ret = Py_BuildValue("NN(ssi)",
3222 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3223 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003226}
3227
Guido van Rossum79f25d91997-04-29 20:08:16 +00003228static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003229imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 char *name;
3232 PyObject *ret, *path = NULL;
3233 if (!PyArg_ParseTuple(args, "es|O:find_module",
3234 Py_FileSystemDefaultEncoding, &name,
3235 &path))
3236 return NULL;
3237 ret = call_find_module(name, path);
3238 PyMem_Free(name);
3239 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003240}
3241
3242static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003243imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 char *name;
3246 int ret;
3247 PyObject *m;
3248 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3249 return NULL;
3250 ret = init_builtin(name);
3251 if (ret < 0)
3252 return NULL;
3253 if (ret == 0) {
3254 Py_INCREF(Py_None);
3255 return Py_None;
3256 }
3257 m = PyImport_AddModule(name);
3258 Py_XINCREF(m);
3259 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003260}
3261
Guido van Rossum79f25d91997-04-29 20:08:16 +00003262static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003263imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 char *name;
3266 int ret;
3267 PyObject *m;
3268 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3269 return NULL;
3270 ret = PyImport_ImportFrozenModule(name);
3271 if (ret < 0)
3272 return NULL;
3273 if (ret == 0) {
3274 Py_INCREF(Py_None);
3275 return Py_None;
3276 }
3277 m = PyImport_AddModule(name);
3278 Py_XINCREF(m);
3279 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003280}
3281
Guido van Rossum79f25d91997-04-29 20:08:16 +00003282static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003283imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3288 return NULL;
3289 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003290}
3291
Guido van Rossum79f25d91997-04-29 20:08:16 +00003292static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003293imp_is_frozen_package(PyObject *self, PyObject *args)
3294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3298 return NULL;
3299 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003300}
3301
3302static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003303imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 char *name;
3306 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3307 return NULL;
3308 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003309}
3310
Guido van Rossum79f25d91997-04-29 20:08:16 +00003311static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003312imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 char *name;
3315 struct _frozen *p;
3316 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3317 return NULL;
3318 p = find_frozen(name);
3319 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003320}
3321
3322static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003323get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 FILE *fp;
3326 if (mode[0] == 'U')
3327 mode = "r" PY_STDIOTEXTMODE;
3328 if (fob == NULL) {
3329 fp = fopen(pathname, mode);
3330 }
3331 else {
3332 int fd = PyObject_AsFileDescriptor(fob);
3333 if (fd == -1)
3334 return NULL;
3335 if (!_PyVerify_fd(fd))
3336 goto error;
3337 /* the FILE struct gets a new fd, so that it can be closed
3338 * independently of the file descriptor given
3339 */
3340 fd = dup(fd);
3341 if (fd == -1)
3342 goto error;
3343 fp = fdopen(fd, mode);
3344 }
3345 if (fp)
3346 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003347error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 PyErr_SetFromErrno(PyExc_IOError);
3349 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003350}
3351
Guido van Rossum79f25d91997-04-29 20:08:16 +00003352static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003353imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 char *name;
3356 char *pathname;
3357 PyObject *fob = NULL;
3358 PyObject *m;
3359 FILE *fp;
3360 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3361 &name,
3362 Py_FileSystemDefaultEncoding, &pathname,
3363 &fob))
3364 return NULL;
3365 fp = get_file(pathname, fob, "rb");
3366 if (fp == NULL) {
3367 PyMem_Free(pathname);
3368 return NULL;
3369 }
3370 m = load_compiled_module(name, pathname, fp);
3371 fclose(fp);
3372 PyMem_Free(pathname);
3373 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003374}
3375
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003376#ifdef HAVE_DYNAMIC_LOADING
3377
Guido van Rossum79f25d91997-04-29 20:08:16 +00003378static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003379imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 char *name;
3382 char *pathname;
3383 PyObject *fob = NULL;
3384 PyObject *m;
3385 FILE *fp = NULL;
3386 if (!PyArg_ParseTuple(args, "ses|O:load_dynamic",
3387 &name,
3388 Py_FileSystemDefaultEncoding, &pathname,
3389 &fob))
3390 return NULL;
3391 if (fob) {
3392 fp = get_file(pathname, fob, "r");
3393 if (fp == NULL) {
3394 PyMem_Free(pathname);
3395 return NULL;
3396 }
3397 }
3398 m = _PyImport_LoadDynamicModule(name, pathname, fp);
3399 PyMem_Free(pathname);
3400 if (fp)
3401 fclose(fp);
3402 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003403}
3404
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003405#endif /* HAVE_DYNAMIC_LOADING */
3406
Guido van Rossum79f25d91997-04-29 20:08:16 +00003407static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003408imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 char *name;
3411 char *pathname;
3412 PyObject *fob = NULL;
3413 PyObject *m;
3414 FILE *fp;
3415 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3416 &name,
3417 Py_FileSystemDefaultEncoding, &pathname,
3418 &fob))
3419 return NULL;
3420 fp = get_file(pathname, fob, "r");
3421 if (fp == NULL) {
3422 PyMem_Free(pathname);
3423 return NULL;
3424 }
3425 m = load_source_module(name, pathname, fp);
3426 PyMem_Free(pathname);
3427 fclose(fp);
3428 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003429}
3430
Guido van Rossum79f25d91997-04-29 20:08:16 +00003431static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003432imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 char *name;
3435 PyObject *fob;
3436 char *pathname;
3437 PyObject * ret;
3438 char *suffix; /* Unused */
3439 char *mode;
3440 int type;
3441 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
3444 &name, &fob,
3445 Py_FileSystemDefaultEncoding, &pathname,
3446 &suffix, &mode, &type))
3447 return NULL;
3448 if (*mode) {
3449 /* Mode must start with 'r' or 'U' and must not contain '+'.
3450 Implicit in this test is the assumption that the mode
3451 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3454 PyErr_Format(PyExc_ValueError,
3455 "invalid file open mode %.200s", mode);
3456 PyMem_Free(pathname);
3457 return NULL;
3458 }
3459 }
3460 if (fob == Py_None)
3461 fp = NULL;
3462 else {
3463 fp = get_file(NULL, fob, mode);
3464 if (fp == NULL) {
3465 PyMem_Free(pathname);
3466 return NULL;
3467 }
3468 }
3469 ret = load_module(name, fp, pathname, type, NULL);
3470 PyMem_Free(pathname);
3471 if (fp)
3472 fclose(fp);
3473 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003474}
3475
3476static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003477imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 char *name;
3480 char *pathname;
3481 PyObject * ret;
3482 if (!PyArg_ParseTuple(args, "ses:load_package",
3483 &name, Py_FileSystemDefaultEncoding, &pathname))
3484 return NULL;
3485 ret = load_package(name, pathname);
3486 PyMem_Free(pathname);
3487 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003488}
3489
3490static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003491imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 char *name;
3494 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3495 return NULL;
3496 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003497}
3498
Christian Heimes13a7a212008-01-07 17:13:09 +00003499static PyObject *
3500imp_reload(PyObject *self, PyObject *v)
3501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003503}
3504
3505PyDoc_STRVAR(doc_reload,
3506"reload(module) -> module\n\
3507\n\
3508Reload the module. The module must have been successfully imported before.");
3509
Barry Warsaw28a691b2010-04-17 00:19:56 +00003510static PyObject *
3511imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 char buf[MAXPATHLEN+1];
3516 char *pathname, *cpathname;
3517 PyObject *debug_override = Py_None;
3518 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 if (!PyArg_ParseTupleAndKeywords(
3521 args, kws, "es|O", kwlist,
3522 Py_FileSystemDefaultEncoding, &pathname, &debug_override))
3523 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 if (debug_override != Py_None)
3526 if ((debug = PyObject_IsTrue(debug_override)) < 0)
3527 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1, debug);
3530 PyMem_Free(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 if (cpathname == NULL) {
3533 PyErr_Format(PyExc_SystemError, "path buffer too short");
3534 return NULL;
3535 }
3536 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003537}
3538
3539PyDoc_STRVAR(doc_cache_from_source,
3540"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3541\n\
3542The .py file does not need to exist; this simply returns the path to the\n\
3543.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3544will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3545\n\
3546If debug_override is not None, then it must be a boolean and is taken as\n\
3547the value of __debug__ instead.");
3548
3549static PyObject *
3550imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 char *pathname;
3555 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 if (!PyArg_ParseTupleAndKeywords(
3558 args, kws, "es", kwlist,
3559 Py_FileSystemDefaultEncoding, &pathname))
3560 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 if (make_source_pathname(pathname, buf) == NULL) {
3563 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3564 pathname);
3565 PyMem_Free(pathname);
3566 return NULL;
3567 }
3568 PyMem_Free(pathname);
3569 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003570}
3571
3572PyDoc_STRVAR(doc_source_from_cache,
3573"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3574\n\
3575The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3576the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3577does not conform to PEP 3147 format, ValueError will be raised.");
3578
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003579/* Doc strings */
3580
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003581PyDoc_STRVAR(doc_imp,
3582"This module provides the components needed to build your own\n\
3583__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003585PyDoc_STRVAR(doc_find_module,
3586"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003587Search for a module. If path is omitted or None, search for a\n\
3588built-in, frozen or special module and continue search in sys.path.\n\
3589The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003590package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003592PyDoc_STRVAR(doc_load_module,
3593"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003594Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003595The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003597PyDoc_STRVAR(doc_get_magic,
3598"get_magic() -> string\n\
3599Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003600
Barry Warsaw28a691b2010-04-17 00:19:56 +00003601PyDoc_STRVAR(doc_get_tag,
3602"get_tag() -> string\n\
3603Return the magic tag for .pyc or .pyo files.");
3604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003605PyDoc_STRVAR(doc_get_suffixes,
3606"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003607Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003608that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003610PyDoc_STRVAR(doc_new_module,
3611"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003612Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003613The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003615PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003616"lock_held() -> boolean\n\
3617Return True if the import lock is currently held, else False.\n\
3618On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003619
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003620PyDoc_STRVAR(doc_acquire_lock,
3621"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003622Acquires the interpreter's import lock for the current thread.\n\
3623This lock should be used by import hooks to ensure thread-safety\n\
3624when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003625On platforms without threads, this function does nothing.");
3626
3627PyDoc_STRVAR(doc_release_lock,
3628"release_lock() -> None\n\
3629Release the interpreter's import lock.\n\
3630On platforms without threads, this function does nothing.");
3631
Guido van Rossum79f25d91997-04-29 20:08:16 +00003632static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3634 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3635 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3636 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3637 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3638 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3639 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3640 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3641 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3642 {"reload", imp_reload, METH_O, doc_reload},
3643 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3644 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3645 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3646 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3647 /* The rest are obsolete */
3648 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3649 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3650 {"init_builtin", imp_init_builtin, METH_VARARGS},
3651 {"init_frozen", imp_init_frozen, METH_VARARGS},
3652 {"is_builtin", imp_is_builtin, METH_VARARGS},
3653 {"is_frozen", imp_is_frozen, METH_VARARGS},
3654 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003655#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003657#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 {"load_package", imp_load_package, METH_VARARGS},
3659 {"load_source", imp_load_source, METH_VARARGS},
3660 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003661};
3662
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003663static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003664setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 PyObject *v;
3667 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 v = PyLong_FromLong((long)value);
3670 err = PyDict_SetItemString(d, name, v);
3671 Py_XDECREF(v);
3672 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003673}
3674
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003675typedef struct {
3676 PyObject_HEAD
3677} NullImporter;
3678
3679static int
3680NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3681{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003682#ifndef MS_WINDOWS
3683 PyObject *path;
3684 struct stat statbuf;
3685 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3688 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003689
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003690 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3691 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003693
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003694 if (PyBytes_GET_SIZE(path) == 0) {
3695 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 PyErr_SetString(PyExc_ImportError, "empty pathname");
3697 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003699
3700 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3701 Py_DECREF(path);
3702 if (rv == 0) {
3703 /* it exists */
3704 if (S_ISDIR(statbuf.st_mode)) {
3705 /* it's a directory */
3706 PyErr_SetString(PyExc_ImportError, "existing directory");
3707 return -1;
3708 }
3709 }
3710#else /* MS_WINDOWS */
3711 PyObject *pathobj;
3712 DWORD rv;
3713 wchar_t path[MAXPATHLEN+1];
3714 Py_ssize_t len;
3715
3716 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3717 return -1;
3718
3719 if (!PyArg_ParseTuple(args, "U:NullImporter",
3720 &pathobj))
3721 return -1;
3722
3723 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3724 PyErr_SetString(PyExc_ImportError, "empty pathname");
3725 return -1;
3726 }
3727
3728 len = PyUnicode_AsWideChar((PyUnicodeObject*)pathobj,
3729 path, sizeof(path) / sizeof(path[0]));
3730 if (len == -1)
3731 return -1;
3732 /* see issue1293 and issue3677:
3733 * stat() on Windows doesn't recognise paths like
3734 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3735 */
3736 rv = GetFileAttributesW(path);
3737 if (rv != INVALID_FILE_ATTRIBUTES) {
3738 /* it exists */
3739 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3740 /* it's a directory */
3741 PyErr_SetString(PyExc_ImportError, "existing directory");
3742 return -1;
3743 }
3744 }
3745#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003747}
3748
3749static PyObject *
3750NullImporter_find_module(NullImporter *self, PyObject *args)
3751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003753}
3754
3755static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3757 "Always return None"
3758 },
3759 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003760};
3761
3762
Christian Heimes9cd17752007-11-18 19:35:23 +00003763PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 PyVarObject_HEAD_INIT(NULL, 0)
3765 "imp.NullImporter", /*tp_name*/
3766 sizeof(NullImporter), /*tp_basicsize*/
3767 0, /*tp_itemsize*/
3768 0, /*tp_dealloc*/
3769 0, /*tp_print*/
3770 0, /*tp_getattr*/
3771 0, /*tp_setattr*/
3772 0, /*tp_reserved*/
3773 0, /*tp_repr*/
3774 0, /*tp_as_number*/
3775 0, /*tp_as_sequence*/
3776 0, /*tp_as_mapping*/
3777 0, /*tp_hash */
3778 0, /*tp_call*/
3779 0, /*tp_str*/
3780 0, /*tp_getattro*/
3781 0, /*tp_setattro*/
3782 0, /*tp_as_buffer*/
3783 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3784 "Null importer object", /* tp_doc */
3785 0, /* tp_traverse */
3786 0, /* tp_clear */
3787 0, /* tp_richcompare */
3788 0, /* tp_weaklistoffset */
3789 0, /* tp_iter */
3790 0, /* tp_iternext */
3791 NullImporter_methods, /* tp_methods */
3792 0, /* tp_members */
3793 0, /* tp_getset */
3794 0, /* tp_base */
3795 0, /* tp_dict */
3796 0, /* tp_descr_get */
3797 0, /* tp_descr_set */
3798 0, /* tp_dictoffset */
3799 (initproc)NullImporter_init, /* tp_init */
3800 0, /* tp_alloc */
3801 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003802};
3803
Martin v. Löwis1a214512008-06-11 05:26:20 +00003804static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 PyModuleDef_HEAD_INIT,
3806 "imp",
3807 doc_imp,
3808 0,
3809 imp_methods,
3810 NULL,
3811 NULL,
3812 NULL,
3813 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003814};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003815
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003816PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003817PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 if (PyType_Ready(&PyNullImporter_Type) < 0)
3822 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 m = PyModule_Create(&impmodule);
3825 if (m == NULL)
3826 goto failure;
3827 d = PyModule_GetDict(m);
3828 if (d == NULL)
3829 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3832 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3833 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3834 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3835 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3836 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3837 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3838 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3839 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3840 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 Py_INCREF(&PyNullImporter_Type);
3843 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3844 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003845 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 Py_XDECREF(m);
3847 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003848}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003849
3850
Guido van Rossumb18618d2000-05-03 23:44:39 +00003851/* API for embedding applications that want to add their own entries
3852 to the table of built-in modules. This should normally be called
3853 *before* Py_Initialize(). When the table resize fails, -1 is
3854 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003855
3856 After a similar function by Just van Rossum. */
3857
3858int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003859PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 static struct _inittab *our_copy = NULL;
3862 struct _inittab *p;
3863 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 /* Count the number of entries in both tables */
3866 for (n = 0; newtab[n].name != NULL; n++)
3867 ;
3868 if (n == 0)
3869 return 0; /* Nothing to do */
3870 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3871 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 /* Allocate new memory for the combined table */
3874 p = our_copy;
3875 PyMem_RESIZE(p, struct _inittab, i+n+1);
3876 if (p == NULL)
3877 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 /* Copy the tables into the new memory */
3880 if (our_copy != PyImport_Inittab)
3881 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3882 PyImport_Inittab = our_copy = p;
3883 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003886}
3887
3888/* Shorthand to add a single entry given a name and a function */
3889
3890int
Brett Cannona826f322009-04-02 03:41:46 +00003891PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 newtab[0].name = (char *)name;
3898 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003901}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003902
3903#ifdef __cplusplus
3904}
3905#endif