blob: 85ead86d1add8d772b8b2106e13fc0e2d53c06a4 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000022extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimesd3eb5a152008-02-24 00:38:49 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000028/* for _mkdir */
29#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000030#endif
31
Guido van Rossum21d335e1993-10-15 13:01:11 +000032
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000033/* Magic word to reject .pyc files generated by other Python versions.
34 It should change for each incompatible change to the bytecode.
35
36 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000037 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000038 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Guido van Rossum45aecf42006-03-15 04:58:47 +000040 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000041 -U interpeter flag will cause MAGIC+1 being used. They have been
42 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000044 There were a variety of old schemes for setting the magic number.
45 The current working scheme is to increment the previous value by
46 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000047
Barry Warsaw28a691b2010-04-17 00:19:56 +000048 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
49 number also includes a new "magic tag", i.e. a human readable string used
50 to represent the magic number in __pycache__ directories. When you change
51 the magic number, you must also set a new unique magic tag. Generally this
52 can be named after the Python major version of the magic number bump, but
53 it can really be anything, as long as it's different than anything else
54 that's come before. The tags are included in the following table, starting
55 with Python 3.2a0.
56
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000057 Known values:
58 Python 1.5: 20121
59 Python 1.5.1: 20121
60 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000062 Python 2.0: 50823
63 Python 2.0.1: 50823
64 Python 2.1: 60202
65 Python 2.1.1: 60202
66 Python 2.1.2: 60202
67 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000068 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000069 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000070 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000071 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000072 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000073 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000074 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000075 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000076 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000077 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
79 Python 2.5b3: 62111 (fix wrong code: x += yield)
80 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000082 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000083 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000084 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000085 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 3010 (removed UNARY_CONVERT)
87 3020 (added BUILD_SET)
88 3030 (added keyword-only parameters)
89 3040 (added signature annotations)
90 3050 (print becomes a function)
91 3060 (PEP 3115 metaclass syntax)
92 3061 (string literals become unicode)
93 3071 (PEP 3109 raise changes)
94 3081 (PEP 3137 make __file__ and __name__ unicode)
95 3091 (kill str8 interning)
96 3101 (merge from 2.6a0, see 62151)
97 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
99 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
100 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +0000102 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000104 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000106 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
107 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000108 Python 3.2a2 3180 (add DELETE_DEREF)
Tim Peters36515e22001-11-18 04:06:29 +0000109*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000110
Nick Coghlancd419ab2010-09-11 00:39:25 +0000111/* MAGIC must change whenever the bytecode emitted by the compiler may no
112 longer be understood by older implementations of the eval loop (usually
113 due to the addition of new opcodes)
114 TAG must change for each major Python release. The magic number will take
115 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116*/
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000117#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118#define TAG "cpython-32"
119#define CACHEDIR "__pycache__"
120/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000121static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000123
Victor Stinner49d3f252010-10-17 01:24:53 +0000124/* See _PyImport_FixupExtensionUnicode() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000126
Guido van Rossum771c6c81997-10-31 18:37:24 +0000127/* This table is defined in config.c: */
128extern struct _inittab _PyImport_Inittab[];
129
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000130/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000131extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000132
Guido van Rossum771c6c81997-10-31 18:37:24 +0000133struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000134
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135/* these tables define the module suffixes that Python recognizes */
136struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000137
Guido van Rossumed1170e1999-12-20 21:23:41 +0000138static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000140#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000142#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 {".pyc", "rb", PY_COMPILED},
144 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000145};
146
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000147
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000148/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149
150void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000151_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 const struct filedescr *scan;
154 struct filedescr *filetab;
155 int countD = 0;
156 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 /* prepare _PyImport_Filetab: copy entries from
159 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
160 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000161#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
163 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000164#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
166 ++countS;
167 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
168 if (filetab == NULL)
169 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000170#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 memcpy(filetab, _PyImport_DynLoadFiletab,
172 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000173#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 memcpy(filetab + countD, _PyImport_StandardFiletab,
175 countS * sizeof(struct filedescr));
176 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (Py_OptimizeFlag) {
181 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
182 for (; filetab->suffix != NULL; filetab++) {
183 if (strcmp(filetab->suffix, ".pyc") == 0)
184 filetab->suffix = ".pyo";
185 }
186 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187}
188
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189void
Just van Rossum52e14d62002-12-30 22:08:05 +0000190_PyImportHooks_Init(void)
191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyObject *v, *path_hooks = NULL, *zimpimport;
193 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* adding sys.path_hooks and sys.path_importer_cache, setting up
196 zipimport */
197 if (PyType_Ready(&PyNullImporter_Type) < 0)
198 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 if (Py_VerboseFlag)
201 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 v = PyList_New(0);
204 if (v == NULL)
205 goto error;
206 err = PySys_SetObject("meta_path", v);
207 Py_DECREF(v);
208 if (err)
209 goto error;
210 v = PyDict_New();
211 if (v == NULL)
212 goto error;
213 err = PySys_SetObject("path_importer_cache", v);
214 Py_DECREF(v);
215 if (err)
216 goto error;
217 path_hooks = PyList_New(0);
218 if (path_hooks == NULL)
219 goto error;
220 err = PySys_SetObject("path_hooks", path_hooks);
221 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000222 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyErr_Print();
224 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
225 "path_importer_cache, or NullImporter failed"
226 );
227 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 zimpimport = PyImport_ImportModule("zipimport");
230 if (zimpimport == NULL) {
231 PyErr_Clear(); /* No zip import module -- okay */
232 if (Py_VerboseFlag)
233 PySys_WriteStderr("# can't import zipimport\n");
234 }
235 else {
236 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
237 "zipimporter");
238 Py_DECREF(zimpimport);
239 if (zipimporter == NULL) {
240 PyErr_Clear(); /* No zipimporter object -- okay */
241 if (Py_VerboseFlag)
242 PySys_WriteStderr(
243 "# can't import zipimport.zipimporter\n");
244 }
245 else {
246 /* sys.path_hooks.append(zipimporter) */
247 err = PyList_Append(path_hooks, zipimporter);
248 Py_DECREF(zipimporter);
249 if (err)
250 goto error;
251 if (Py_VerboseFlag)
252 PySys_WriteStderr(
253 "# installed zipimport hook\n");
254 }
255 }
256 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000257}
258
259void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000260_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 Py_XDECREF(extensions);
263 extensions = NULL;
264 PyMem_DEL(_PyImport_Filetab);
265 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000266}
267
268
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269/* Locking primitives to prevent parallel imports of the same module
270 in different threads to return with a partially loaded module.
271 These calls are serialized by the global interpreter lock. */
272
273#ifdef WITH_THREAD
274
Guido van Rossum49b56061998-10-01 20:42:43 +0000275#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000276
Guido van Rossum65d5b571998-12-21 19:32:43 +0000277static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000278static long import_lock_thread = -1;
279static int import_lock_level = 0;
280
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000281void
282_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 long me = PyThread_get_thread_ident();
285 if (me == -1)
286 return; /* Too bad */
287 if (import_lock == NULL) {
288 import_lock = PyThread_allocate_lock();
289 if (import_lock == NULL)
290 return; /* Nothing much we can do. */
291 }
292 if (import_lock_thread == me) {
293 import_lock_level++;
294 return;
295 }
296 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
297 {
298 PyThreadState *tstate = PyEval_SaveThread();
299 PyThread_acquire_lock(import_lock, 1);
300 PyEval_RestoreThread(tstate);
301 }
302 import_lock_thread = me;
303 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304}
305
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000306int
307_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 long me = PyThread_get_thread_ident();
310 if (me == -1 || import_lock == NULL)
311 return 0; /* Too bad */
312 if (import_lock_thread != me)
313 return -1;
314 import_lock_level--;
315 if (import_lock_level == 0) {
316 import_lock_thread = -1;
317 PyThread_release_lock(import_lock);
318 }
319 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000320}
321
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000322/* This function is called from PyOS_AfterFork to ensure that newly
323 created child processes do not share locks with the parent.
324 We now acquire the import lock around fork() calls but on some platforms
325 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000326
327void
328_PyImport_ReInitLock(void)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (import_lock != NULL)
331 import_lock = PyThread_allocate_lock();
332 import_lock_thread = -1;
333 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000334}
335
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000336#endif
337
Tim Peters69232342001-08-30 05:16:13 +0000338static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000339imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000340{
Tim Peters69232342001-08-30 05:16:13 +0000341#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000343#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000345#endif
346}
347
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000349imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000350{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000351#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 Py_INCREF(Py_None);
355 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000356}
357
358static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000359imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000360{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (_PyImport_ReleaseLock() < 0) {
363 PyErr_SetString(PyExc_RuntimeError,
364 "not holding the import lock");
365 return NULL;
366 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000367#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 Py_INCREF(Py_None);
369 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000370}
371
Guido van Rossumd8faa362007-04-27 19:54:29 +0000372static void
373imp_modules_reloading_clear(void)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyInterpreterState *interp = PyThreadState_Get()->interp;
376 if (interp->modules_reloading != NULL)
377 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000378}
379
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380/* Helper for sys */
381
382PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000383PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyInterpreterState *interp = PyThreadState_GET()->interp;
386 if (interp->modules == NULL)
387 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
388 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389}
390
Guido van Rossum3f5da241990-12-20 15:06:42 +0000391
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392/* List of names to clear in sys */
393static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 "path", "argv", "ps1", "ps2",
395 "last_type", "last_value", "last_traceback",
396 "path_hooks", "path_importer_cache", "meta_path",
397 /* misc stuff */
398 "flags", "float_info",
399 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000400};
401
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000402static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 "stdin", "__stdin__",
404 "stdout", "__stdout__",
405 "stderr", "__stderr__",
406 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000407};
408
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000409
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000410/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000411
Guido van Rossum3f5da241990-12-20 15:06:42 +0000412void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000413PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 Py_ssize_t pos, ndone;
416 char *name;
417 PyObject *key, *value, *dict;
418 PyInterpreterState *interp = PyThreadState_GET()->interp;
419 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (modules == NULL)
422 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* Delete some special variables first. These are common
425 places where user values hide and people complain when their
426 destructors fail. Since the modules containing them are
427 deleted *last* of all, they would come too late in the normal
428 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 value = PyDict_GetItemString(modules, "builtins");
431 if (value != NULL && PyModule_Check(value)) {
432 dict = PyModule_GetDict(value);
433 if (Py_VerboseFlag)
434 PySys_WriteStderr("# clear builtins._\n");
435 PyDict_SetItemString(dict, "_", Py_None);
436 }
437 value = PyDict_GetItemString(modules, "sys");
438 if (value != NULL && PyModule_Check(value)) {
439 char **p;
440 PyObject *v;
441 dict = PyModule_GetDict(value);
442 for (p = sys_deletes; *p != NULL; p++) {
443 if (Py_VerboseFlag)
444 PySys_WriteStderr("# clear sys.%s\n", *p);
445 PyDict_SetItemString(dict, *p, Py_None);
446 }
447 for (p = sys_files; *p != NULL; p+=2) {
448 if (Py_VerboseFlag)
449 PySys_WriteStderr("# restore sys.%s\n", *p);
450 v = PyDict_GetItemString(dict, *(p+1));
451 if (v == NULL)
452 v = Py_None;
453 PyDict_SetItemString(dict, *p, v);
454 }
455 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* First, delete __main__ */
458 value = PyDict_GetItemString(modules, "__main__");
459 if (value != NULL && PyModule_Check(value)) {
460 if (Py_VerboseFlag)
461 PySys_WriteStderr("# cleanup __main__\n");
462 _PyModule_Clear(value);
463 PyDict_SetItemString(modules, "__main__", Py_None);
464 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 /* The special treatment of "builtins" here is because even
467 when it's not referenced as a module, its dictionary is
468 referenced by almost every module's __builtins__. Since
469 deleting a module clears its dictionary (even if there are
470 references left to it), we need to delete the "builtins"
471 module last. Likewise, we don't delete sys until the very
472 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 Also note that we 'delete' modules by replacing their entry
475 in the modules dict with None, rather than really deleting
476 them; this avoids a rehash of the modules dictionary and
477 also marks them as "non existent" so they won't be
478 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* Next, repeatedly delete modules with a reference count of
481 one (skipping builtins and sys) and delete them */
482 do {
483 ndone = 0;
484 pos = 0;
485 while (PyDict_Next(modules, &pos, &key, &value)) {
486 if (value->ob_refcnt != 1)
487 continue;
488 if (PyUnicode_Check(key) && PyModule_Check(value)) {
489 name = _PyUnicode_AsString(key);
490 if (strcmp(name, "builtins") == 0)
491 continue;
492 if (strcmp(name, "sys") == 0)
493 continue;
494 if (Py_VerboseFlag)
495 PySys_WriteStderr(
496 "# cleanup[1] %s\n", name);
497 _PyModule_Clear(value);
498 PyDict_SetItem(modules, key, Py_None);
499 ndone++;
500 }
501 }
502 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Next, delete all modules (still skipping builtins and sys) */
505 pos = 0;
506 while (PyDict_Next(modules, &pos, &key, &value)) {
507 if (PyUnicode_Check(key) && PyModule_Check(value)) {
508 name = _PyUnicode_AsString(key);
509 if (strcmp(name, "builtins") == 0)
510 continue;
511 if (strcmp(name, "sys") == 0)
512 continue;
513 if (Py_VerboseFlag)
514 PySys_WriteStderr("# cleanup[2] %s\n", name);
515 _PyModule_Clear(value);
516 PyDict_SetItem(modules, key, Py_None);
517 }
518 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 /* Next, delete sys and builtins (in that order) */
521 value = PyDict_GetItemString(modules, "sys");
522 if (value != NULL && PyModule_Check(value)) {
523 if (Py_VerboseFlag)
524 PySys_WriteStderr("# cleanup sys\n");
525 _PyModule_Clear(value);
526 PyDict_SetItemString(modules, "sys", Py_None);
527 }
528 value = PyDict_GetItemString(modules, "builtins");
529 if (value != NULL && PyModule_Check(value)) {
530 if (Py_VerboseFlag)
531 PySys_WriteStderr("# cleanup builtins\n");
532 _PyModule_Clear(value);
533 PyDict_SetItemString(modules, "builtins", Py_None);
534 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Finally, clear and delete the modules directory */
537 PyDict_Clear(modules);
538 interp->modules = NULL;
539 Py_DECREF(modules);
540 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000541}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000542
543
Barry Warsaw28a691b2010-04-17 00:19:56 +0000544/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545
546long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550}
551
552
Barry Warsaw28a691b2010-04-17 00:19:56 +0000553const char *
554PyImport_GetMagicTag(void)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000557}
558
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559/* Magic for extension modules (built-in as well as dynamically
560 loaded). To prevent initializing an extension module more than
561 once, we keep a static dictionary 'extensions' keyed by module name
562 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000563 modules), containing these modules. A copy of the module's
Victor Stinner49d3f252010-10-17 01:24:53 +0000564 dictionary is stored by calling _PyImport_FixupExtensionUnicode()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565 immediately after the module initialization function succeeds. A
566 copy can be retrieved from there by calling
Victor Stinner49d3f252010-10-17 01:24:53 +0000567 _PyImport_FindExtensionUnicode().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000568
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000569 Modules which do support multiple initialization set their m_size
570 field to a non-negative number (indicating the size of the
571 module-specific state). They are still recorded in the extensions
572 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000573*/
574
575int
Victor Stinner49d3f252010-10-17 01:24:53 +0000576_PyImport_FixupExtensionUnicode(PyObject *mod, char *name, PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 PyObject *modules, *dict;
579 struct PyModuleDef *def;
580 if (extensions == NULL) {
581 extensions = PyDict_New();
582 if (extensions == NULL)
583 return -1;
584 }
585 if (mod == NULL || !PyModule_Check(mod)) {
586 PyErr_BadInternalCall();
587 return -1;
588 }
589 def = PyModule_GetDef(mod);
590 if (!def) {
591 PyErr_BadInternalCall();
592 return -1;
593 }
594 modules = PyImport_GetModuleDict();
595 if (PyDict_SetItemString(modules, name, mod) < 0)
596 return -1;
597 if (_PyState_AddModule(mod, def) < 0) {
598 PyDict_DelItemString(modules, name);
599 return -1;
600 }
601 if (def->m_size == -1) {
602 if (def->m_base.m_copy) {
603 /* Somebody already imported the module,
604 likely under a different name.
605 XXX this should really not happen. */
606 Py_DECREF(def->m_base.m_copy);
607 def->m_base.m_copy = NULL;
608 }
609 dict = PyModule_GetDict(mod);
610 if (dict == NULL)
611 return -1;
612 def->m_base.m_copy = PyDict_Copy(dict);
613 if (def->m_base.m_copy == NULL)
614 return -1;
615 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000616 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618}
619
Victor Stinner49d3f252010-10-17 01:24:53 +0000620int
621_PyImport_FixupBuiltin(PyObject *mod, char *name)
622{
623 int res;
624 PyObject *filename;
625 filename = PyUnicode_FromString(name);
626 if (filename == NULL)
627 return -1;
628 res = _PyImport_FixupExtensionUnicode(mod, name, filename);
629 Py_DECREF(filename);
630 return res;
631}
632
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633PyObject *
Victor Stinner49d3f252010-10-17 01:24:53 +0000634_PyImport_FindExtensionUnicode(char *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyObject *mod, *mdict;
637 PyModuleDef* def;
638 if (extensions == NULL)
639 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000640 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (def == NULL)
642 return NULL;
643 if (def->m_size == -1) {
644 /* Module does not support repeated initialization */
645 if (def->m_base.m_copy == NULL)
646 return NULL;
647 mod = PyImport_AddModule(name);
648 if (mod == NULL)
649 return NULL;
650 mdict = PyModule_GetDict(mod);
651 if (mdict == NULL)
652 return NULL;
653 if (PyDict_Update(mdict, def->m_base.m_copy))
654 return NULL;
655 }
656 else {
657 if (def->m_base.m_init == NULL)
658 return NULL;
659 mod = def->m_base.m_init();
660 if (mod == NULL)
661 return NULL;
662 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
663 Py_DECREF(mod);
664 }
665 if (_PyState_AddModule(mod, def) < 0) {
666 PyDict_DelItemString(PyImport_GetModuleDict(), name);
667 Py_DECREF(mod);
668 return NULL;
669 }
670 if (Py_VerboseFlag)
Victor Stinner49d3f252010-10-17 01:24:53 +0000671 PySys_FormatStderr("import %s # previously loaded (%U)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 name, filename);
673 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000674
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000675}
676
Victor Stinner49d3f252010-10-17 01:24:53 +0000677PyObject *
678_PyImport_FindBuiltin(char *name)
679{
680 PyObject *res, *filename;
681 filename = PyUnicode_FromString(name);
682 if (filename == NULL)
683 return NULL;
684 res = _PyImport_FindExtensionUnicode(name, filename);
685 Py_DECREF(filename);
686 return res;
687}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000688
689/* Get the module object corresponding to a module name.
690 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000691 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000692 Because the former action is most common, THIS DOES NOT RETURN A
693 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000694
Guido van Rossum79f25d91997-04-29 20:08:16 +0000695PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000696PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyObject *modules = PyImport_GetModuleDict();
699 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
702 PyModule_Check(m))
703 return m;
704 m = PyModule_New(name);
705 if (m == NULL)
706 return NULL;
707 if (PyDict_SetItemString(modules, name, m) != 0) {
708 Py_DECREF(m);
709 return NULL;
710 }
711 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714}
715
Tim Peters1cd70172004-08-02 03:52:12 +0000716/* Remove name from sys.modules, if it's there. */
717static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000718remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 PyObject *modules = PyImport_GetModuleDict();
721 if (PyDict_GetItemString(modules, name) == NULL)
722 return;
723 if (PyDict_DelItemString(modules, name) < 0)
724 Py_FatalError("import: deleting existing key in"
725 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000726}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000727
Barry Warsaw28a691b2010-04-17 00:19:56 +0000728static PyObject * get_sourcefile(char *file);
729static char *make_source_pathname(char *pathname, char *buf);
730static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000732
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000733/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000734 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
735 * removed from sys.modules, to avoid leaving damaged module objects
736 * in sys.modules. The caller may wish to restore the original
737 * module object (if any) in this case; PyImport_ReloadModule is an
738 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000739 *
740 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
741 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000742 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000743PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000744PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 return PyImport_ExecCodeModuleWithPathnames(
747 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000748}
749
750PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000751PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 return PyImport_ExecCodeModuleWithPathnames(
754 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000755}
756
757PyObject *
758PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyObject *modules = PyImport_GetModuleDict();
762 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 m = PyImport_AddModule(name);
765 if (m == NULL)
766 return NULL;
767 /* If the module is being reloaded, we get the old module back
768 and re-use its dict to exec the new code. */
769 d = PyModule_GetDict(m);
770 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
771 if (PyDict_SetItemString(d, "__builtins__",
772 PyEval_GetBuiltins()) != 0)
773 goto error;
774 }
775 /* Remember the filename as the __file__ attribute */
776 v = NULL;
777 if (pathname != NULL) {
778 v = get_sourcefile(pathname);
779 if (v == NULL)
780 PyErr_Clear();
781 }
782 if (v == NULL) {
783 v = ((PyCodeObject *)co)->co_filename;
784 Py_INCREF(v);
785 }
786 if (PyDict_SetItemString(d, "__file__", v) != 0)
787 PyErr_Clear(); /* Not important enough to report */
788 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 /* Remember the pyc path name as the __cached__ attribute. */
791 if (cpathname == NULL) {
792 v = Py_None;
793 Py_INCREF(v);
794 }
795 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
796 PyErr_Clear(); /* Not important enough to report */
797 v = Py_None;
798 Py_INCREF(v);
799 }
800 if (PyDict_SetItemString(d, "__cached__", v) != 0)
801 PyErr_Clear(); /* Not important enough to report */
802 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
805 if (v == NULL)
806 goto error;
807 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
810 PyErr_Format(PyExc_ImportError,
811 "Loaded module %.200s not found in sys.modules",
812 name);
813 return NULL;
814 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000819
820 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 remove_module(name);
822 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000823}
824
825
Barry Warsaw28a691b2010-04-17 00:19:56 +0000826/* Like strrchr(string, '/') but searches for the rightmost of either SEP
827 or ALTSEP, if the latter is defined.
828*/
829static char *
830rightmost_sep(char *s)
831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 char *found, c;
833 for (found = NULL; (c = *s); s++) {
834 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000835#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000837#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 )
839 {
840 found = s;
841 }
842 }
843 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000844}
845
846
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000847/* Given a pathname for a Python source file, fill a buffer with the
848 pathname for the corresponding compiled file. Return the pathname
849 for the compiled file, or NULL if there's no space in the buffer.
850 Doesn't set an exception. */
851
852static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000853make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* foo.py -> __pycache__/foo.<tag>.pyc */
856 size_t len = strlen(pathname);
857 size_t i, save;
858 char *pos;
859 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* Sanity check that the buffer has roughly enough space to hold what
862 will eventually be the full path to the compiled file. The 5 extra
863 bytes include the slash afer __pycache__, the two extra dots, the
864 extra trailing character ('c' or 'o') and null. This isn't exact
865 because the contents of the buffer can affect how many actual
866 characters of the string get into the buffer. We'll do a final
867 sanity check before writing the extension to ensure we do not
868 overflow the buffer.
869 */
870 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
871 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Find the last path separator and copy everything from the start of
874 the source string up to and including the separator.
875 */
876 if ((pos = rightmost_sep(pathname)) == NULL) {
877 i = 0;
878 }
879 else {
880 sep = *pos;
881 i = pos - pathname + 1;
882 strncpy(buf, pathname, i);
883 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 save = i;
886 buf[i++] = '\0';
887 /* Add __pycache__/ */
888 strcat(buf, CACHEDIR);
889 i += strlen(CACHEDIR) - 1;
890 buf[i++] = sep;
891 buf[i++] = '\0';
892 /* Add the base filename, but remove the .py or .pyw extension, since
893 the tag name must go before the extension.
894 */
895 strcat(buf, pathname + save);
896 if ((pos = strrchr(buf, '.')) != NULL)
897 *++pos = '\0';
898 strcat(buf, pyc_tag);
899 /* The length test above assumes that we're only adding one character
900 to the end of what would normally be the extension. What if there
901 is no extension, or the string ends in '.' or '.p', and otherwise
902 fills the buffer? By appending 4 more characters onto the string
903 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 As a simple example, let's say buflen=32 and the input string is
906 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 which is false and so the name mangling would continue. This would
911 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
916 We can even handle an input string of say 'xxxxx' above because
917 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
918 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 which is 32 characters including the nul, and thus fits in the
923 buffer. However, an input string of 'xxxxxx' would yield a result
924 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 which is 33 characters long (including the nul), thus overflowing
929 the buffer, even though the first test would fail, i.e.: the input
930 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 The reason the first test fails but we still overflow the buffer is
933 that the test above only expects to add one extra character to be
934 added to the extension, and here we're adding three (pyc). We
935 don't add the first dot, so that reclaims one of expected
936 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
937 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 The best we can do is ensure that we still have enough room in the
940 target buffer before we write the extension. Because it's always
941 only the extension that can cause the overflow, and never the other
942 path bytes we've written, it's sufficient to just do one more test
943 here. Still, the assertion that follows can't hurt.
944 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000945#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000947#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (strlen(buf) + 5 > buflen)
949 return NULL;
950 strcat(buf, debug ? ".pyc" : ".pyo");
951 assert(strlen(buf) < buflen);
952 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000953}
954
955
Barry Warsaw28a691b2010-04-17 00:19:56 +0000956/* Given a pathname to a Python byte compiled file, return the path to the
957 source file, if the path matches the PEP 3147 format. This does not check
958 for any file existence, however, if the pyc file name does not match PEP
959 3147 style, NULL is returned. buf must be at least as big as pathname;
960 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961
Barry Warsaw28a691b2010-04-17 00:19:56 +0000962static char *
963make_source_pathname(char *pathname, char *buf)
964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* __pycache__/foo.<tag>.pyc -> foo.py */
966 size_t i, j;
967 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* Look back two slashes from the end. In between these two slashes
970 must be the string __pycache__ or this is not a PEP 3147 style
971 path. It's possible for there to be only one slash.
972 */
973 if ((right = rightmost_sep(pathname)) == NULL)
974 return NULL;
975 sep = *right;
976 *right = '\0';
977 left = rightmost_sep(pathname);
978 *right = sep;
979 if (left == NULL)
980 left = pathname;
981 else
982 left++;
983 if (right-left != strlen(CACHEDIR) ||
984 strncmp(left, CACHEDIR, right-left) != 0)
985 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 /* Now verify that the path component to the right of the last slash
988 has two dots in it.
989 */
990 if ((dot0 = strchr(right + 1, '.')) == NULL)
991 return NULL;
992 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
993 return NULL;
994 /* Too many dots? */
995 if (strchr(dot1 + 1, '.') != NULL)
996 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* This is a PEP 3147 path. Start by copying everything from the
999 start of pathname up to and including the leftmost slash. Then
1000 copy the file's basename, removing the magic tag and adding a .py
1001 suffix.
1002 */
1003 strncpy(buf, pathname, (i=left-pathname));
1004 strncpy(buf+i, right+1, (j=dot0-right));
1005 strcpy(buf+i+j, "py");
1006 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001007}
1008
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001009/* Given a pathname for a Python source file, its time of last
1010 modification, and a pathname for a compiled file, check whether the
1011 compiled file represents the same version of the source. If so,
1012 return a FILE pointer for the compiled file, positioned just after
1013 the header; if not, return NULL.
1014 Doesn't set an exception. */
1015
1016static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001017check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 FILE *fp;
1020 long magic;
1021 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 fp = fopen(cpathname, "rb");
1024 if (fp == NULL)
1025 return NULL;
1026 magic = PyMarshal_ReadLongFromFile(fp);
1027 if (magic != pyc_magic) {
1028 if (Py_VerboseFlag)
1029 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1030 fclose(fp);
1031 return NULL;
1032 }
1033 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1034 if (pyc_mtime != mtime) {
1035 if (Py_VerboseFlag)
1036 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1037 fclose(fp);
1038 return NULL;
1039 }
1040 if (Py_VerboseFlag)
1041 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1042 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001043}
1044
1045
1046/* Read a code object from a file and check it for validity */
1047
Guido van Rossum79f25d91997-04-29 20:08:16 +00001048static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001049read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 co = PyMarshal_ReadLastObjectFromFile(fp);
1054 if (co == NULL)
1055 return NULL;
1056 if (!PyCode_Check(co)) {
1057 PyErr_Format(PyExc_ImportError,
1058 "Non-code object in %.200s", cpathname);
1059 Py_DECREF(co);
1060 return NULL;
1061 }
1062 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001063}
1064
1065
1066/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001067 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068
Guido van Rossum79f25d91997-04-29 20:08:16 +00001069static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001070load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 long magic;
1073 PyCodeObject *co;
1074 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 magic = PyMarshal_ReadLongFromFile(fp);
1077 if (magic != pyc_magic) {
1078 PyErr_Format(PyExc_ImportError,
1079 "Bad magic number in %.200s", cpathname);
1080 return NULL;
1081 }
1082 (void) PyMarshal_ReadLongFromFile(fp);
1083 co = read_compiled_module(cpathname, fp);
1084 if (co == NULL)
1085 return NULL;
1086 if (Py_VerboseFlag)
1087 PySys_WriteStderr("import %s # precompiled from %s\n",
1088 name, cpathname);
1089 m = PyImport_ExecCodeModuleWithPathnames(
1090 name, (PyObject *)co, cpathname, cpathname);
1091 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001094}
1095
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001096/* Parse a source file and return the corresponding code object */
1097
Guido van Rossum79f25d91997-04-29 20:08:16 +00001098static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001099parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyCodeObject *co = NULL;
1102 mod_ty mod;
1103 PyCompilerFlags flags;
1104 PyArena *arena = PyArena_New();
1105 if (arena == NULL)
1106 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 flags.cf_flags = 0;
1109 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1110 Py_file_input, 0, 0, &flags,
1111 NULL, arena);
1112 if (mod) {
1113 co = PyAST_Compile(mod, pathname, NULL, arena);
1114 }
1115 PyArena_Free(arena);
1116 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001117}
1118
1119
Guido van Rossum55a83382000-09-20 20:31:38 +00001120/* Helper to open a bytecode file for writing in exclusive mode */
1121
1122static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001123open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001124{
1125#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 /* Use O_EXCL to avoid a race condition when another process tries to
1127 write the same file. When that happens, our open() call fails,
1128 which is just fine (since it's only a cache).
1129 XXX If the file exists and is writable but the directory is not
1130 writable, the file will never be written. Oh well.
1131 */
1132 int fd;
1133 (void) unlink(filename);
1134 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001135#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001137#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001138#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001140#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001142#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 );
1144 if (fd < 0)
1145 return NULL;
1146 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001147#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 /* Best we can do -- on Windows this can't happen anyway */
1149 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001150#endif
1151}
1152
1153
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001154/* Write a compiled module to a file, placing the time of last
1155 modification of its source into the header.
1156 Errors are ignored, if a write error occurs an attempt is made to
1157 remove the file. */
1158
1159static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001160write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 FILE *fp;
1163 char *dirpath;
1164 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001165#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001167#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1169 mode_t dirmode = (srcstat->st_mode |
1170 S_IXUSR | S_IXGRP | S_IXOTH |
1171 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001172#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* Ensure that the __pycache__ directory exists. */
1176 dirpath = rightmost_sep(cpathname);
1177 if (dirpath == NULL) {
1178 if (Py_VerboseFlag)
1179 PySys_WriteStderr(
1180 "# no %s path found %s\n",
1181 CACHEDIR, cpathname);
1182 return;
1183 }
1184 saved = *dirpath;
1185 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001186
1187#ifdef MS_WINDOWS
1188 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1189#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001191#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 *dirpath = saved;
1193 if (Py_VerboseFlag)
1194 PySys_WriteStderr(
1195 "# cannot create cache dir %s\n", cpathname);
1196 return;
1197 }
1198 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 fp = open_exclusive(cpathname, mode);
1201 if (fp == NULL) {
1202 if (Py_VerboseFlag)
1203 PySys_WriteStderr(
1204 "# can't create %s\n", cpathname);
1205 return;
1206 }
1207 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1208 /* First write a 0 for mtime */
1209 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1210 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1211 if (fflush(fp) != 0 || ferror(fp)) {
1212 if (Py_VerboseFlag)
1213 PySys_WriteStderr("# can't write %s\n", cpathname);
1214 /* Don't keep partial file */
1215 fclose(fp);
1216 (void) unlink(cpathname);
1217 return;
1218 }
1219 /* Now write the true mtime */
1220 fseek(fp, 4L, 0);
1221 assert(mtime < LONG_MAX);
1222 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1223 fflush(fp);
1224 fclose(fp);
1225 if (Py_VerboseFlag)
1226 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001227}
1228
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001229static void
1230update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyObject *constants, *tmp;
1233 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (PyUnicode_Compare(co->co_filename, oldname))
1236 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 tmp = co->co_filename;
1239 co->co_filename = newname;
1240 Py_INCREF(co->co_filename);
1241 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 constants = co->co_consts;
1244 n = PyTuple_GET_SIZE(constants);
1245 for (i = 0; i < n; i++) {
1246 tmp = PyTuple_GET_ITEM(constants, i);
1247 if (PyCode_Check(tmp))
1248 update_code_filenames((PyCodeObject *)tmp,
1249 oldname, newname);
1250 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001251}
1252
1253static int
1254update_compiled_module(PyCodeObject *co, char *pathname)
1255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 newname = PyUnicode_DecodeFSDefault(pathname);
1259 if (newname == NULL)
1260 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (!PyUnicode_Compare(co->co_filename, newname)) {
1263 Py_DECREF(newname);
1264 return 0;
1265 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 oldname = co->co_filename;
1268 Py_INCREF(oldname);
1269 update_code_filenames(co, oldname, newname);
1270 Py_DECREF(oldname);
1271 Py_DECREF(newname);
1272 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001273}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001274
1275/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001276 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1277 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001278
Guido van Rossum79f25d91997-04-29 20:08:16 +00001279static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001280load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 struct stat st;
1283 FILE *fpc;
1284 char buf[MAXPATHLEN+1];
1285 char *cpathname;
1286 PyCodeObject *co;
1287 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (fstat(fileno(fp), &st) != 0) {
1290 PyErr_Format(PyExc_RuntimeError,
1291 "unable to get file status from '%s'",
1292 pathname);
1293 return NULL;
1294 }
Fred Drake4c82b232000-06-30 16:18:57 +00001295#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 /* Python's .pyc timestamp handling presumes that the timestamp fits
1297 in 4 bytes. This will be fine until sometime in the year 2038,
1298 when a 4-byte signed time_t will overflow.
1299 */
1300 if (st.st_mtime >> 32) {
1301 PyErr_SetString(PyExc_OverflowError,
1302 "modification time overflows a 4 byte field");
1303 return NULL;
1304 }
Fred Drake4c82b232000-06-30 16:18:57 +00001305#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 cpathname = make_compiled_pathname(
1307 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1308 if (cpathname != NULL &&
1309 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1310 co = read_compiled_module(cpathname, fpc);
1311 fclose(fpc);
1312 if (co == NULL)
1313 return NULL;
1314 if (update_compiled_module(co, pathname) < 0)
1315 return NULL;
1316 if (Py_VerboseFlag)
1317 PySys_WriteStderr("import %s # precompiled from %s\n",
1318 name, cpathname);
1319 pathname = cpathname;
1320 }
1321 else {
1322 co = parse_source_module(pathname, fp);
1323 if (co == NULL)
1324 return NULL;
1325 if (Py_VerboseFlag)
1326 PySys_WriteStderr("import %s # from %s\n",
1327 name, pathname);
1328 if (cpathname) {
1329 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1330 if (ro == NULL || !PyObject_IsTrue(ro))
1331 write_compiled_module(co, cpathname, &st);
1332 }
1333 }
1334 m = PyImport_ExecCodeModuleWithPathnames(
1335 name, (PyObject *)co, pathname, cpathname);
1336 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001339}
1340
Christian Heimes3b06e532008-01-07 20:12:44 +00001341/* Get source file -> unicode or None
1342 * Returns the path to the py file if available, else the given path
1343 */
1344static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001345get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 char py[MAXPATHLEN + 1];
1348 Py_ssize_t len;
1349 PyObject *u;
1350 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (!file || !*file) {
1353 Py_RETURN_NONE;
1354 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 len = strlen(file);
1357 /* match '*.py?' */
1358 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1359 return PyUnicode_DecodeFSDefault(file);
1360 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* Start by trying to turn PEP 3147 path into source path. If that
1363 * fails, just chop off the trailing character, i.e. legacy pyc path
1364 * to py.
1365 */
1366 if (make_source_pathname(file, py) == NULL) {
1367 strncpy(py, file, len-1);
1368 py[len-1] = '\0';
1369 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (stat(py, &statbuf) == 0 &&
1372 S_ISREG(statbuf.st_mode)) {
1373 u = PyUnicode_DecodeFSDefault(py);
1374 }
1375 else {
1376 u = PyUnicode_DecodeFSDefault(file);
1377 }
1378 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001379}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001380
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001381/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001382static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1383static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001385static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001386
1387/* Load a package and return its module object WITH INCREMENTED
1388 REFERENCE COUNT */
1389
1390static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001391load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyObject *m, *d;
1394 PyObject *file = NULL;
1395 PyObject *path = NULL;
1396 int err;
1397 char buf[MAXPATHLEN+1];
1398 FILE *fp = NULL;
1399 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 m = PyImport_AddModule(name);
1402 if (m == NULL)
1403 return NULL;
1404 if (Py_VerboseFlag)
1405 PySys_WriteStderr("import %s # directory %s\n",
1406 name, pathname);
1407 d = PyModule_GetDict(m);
1408 file = get_sourcefile(pathname);
1409 if (file == NULL)
1410 goto error;
1411 path = Py_BuildValue("[O]", file);
1412 if (path == NULL)
1413 goto error;
1414 err = PyDict_SetItemString(d, "__file__", file);
1415 if (err == 0)
1416 err = PyDict_SetItemString(d, "__path__", path);
1417 if (err != 0)
1418 goto error;
1419 buf[0] = '\0';
1420 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1421 if (fdp == NULL) {
1422 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1423 PyErr_Clear();
1424 Py_INCREF(m);
1425 }
1426 else
1427 m = NULL;
1428 goto cleanup;
1429 }
1430 m = load_module(name, fp, buf, fdp->type, NULL);
1431 if (fp != NULL)
1432 fclose(fp);
1433 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001434
1435 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001437 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 Py_XDECREF(path);
1439 Py_XDECREF(file);
1440 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001441}
1442
1443
1444/* Helper to test for built-in module */
1445
1446static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001447is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 int i;
1450 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1451 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1452 if (PyImport_Inittab[i].initfunc == NULL)
1453 return -1;
1454 else
1455 return 1;
1456 }
1457 }
1458 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001459}
1460
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001461
Just van Rossum52e14d62002-12-30 22:08:05 +00001462/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1463 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001464 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001465 that can handle the path item. Return None if no hook could;
1466 this tells our caller it should fall back to the builtin
1467 import mechanism. Cache the result in path_importer_cache.
1468 Returns a borrowed reference. */
1469
1470static PyObject *
1471get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 PyObject *importer;
1475 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 /* These conditions are the caller's responsibility: */
1478 assert(PyList_Check(path_hooks));
1479 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 nhooks = PyList_Size(path_hooks);
1482 if (nhooks < 0)
1483 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 importer = PyDict_GetItem(path_importer_cache, p);
1486 if (importer != NULL)
1487 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 /* set path_importer_cache[p] to None to avoid recursion */
1490 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1491 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 for (j = 0; j < nhooks; j++) {
1494 PyObject *hook = PyList_GetItem(path_hooks, j);
1495 if (hook == NULL)
1496 return NULL;
1497 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1498 if (importer != NULL)
1499 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1502 return NULL;
1503 }
1504 PyErr_Clear();
1505 }
1506 if (importer == NULL) {
1507 importer = PyObject_CallFunctionObjArgs(
1508 (PyObject *)&PyNullImporter_Type, p, NULL
1509 );
1510 if (importer == NULL) {
1511 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1512 PyErr_Clear();
1513 return Py_None;
1514 }
1515 }
1516 }
1517 if (importer != NULL) {
1518 int err = PyDict_SetItem(path_importer_cache, p, importer);
1519 Py_DECREF(importer);
1520 if (err != 0)
1521 return NULL;
1522 }
1523 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001524}
1525
Christian Heimes9cd17752007-11-18 19:35:23 +00001526PyAPI_FUNC(PyObject *)
1527PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1531 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1532 importer = get_path_importer(path_importer_cache,
1533 path_hooks, path);
1534 }
1535 }
1536 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1537 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001538}
1539
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001540/* Search the path (default sys.path) for a module. Return the
1541 corresponding filedescr struct, and (via return arguments) the
1542 pathname and an open file. Return NULL if the module is not found. */
1543
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001544#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001545extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001547#endif
1548
Martin v. Löwis18e16552006-02-15 17:27:45 +00001549static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001550static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001551static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001552
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001553static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001554find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 Py_ssize_t i, npath;
1558 size_t len, namelen;
1559 struct filedescr *fdp = NULL;
1560 char *filemode;
1561 FILE *fp = NULL;
1562 PyObject *path_hooks, *path_importer_cache;
1563 struct stat statbuf;
1564 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1565 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1566 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1567 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001568#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 size_t saved_len;
1570 size_t saved_namelen;
1571 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001572#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (p_loader != NULL)
1574 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (strlen(subname) > MAXPATHLEN) {
1577 PyErr_SetString(PyExc_OverflowError,
1578 "module name is too long");
1579 return NULL;
1580 }
1581 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* sys.meta_path import hook */
1584 if (p_loader != NULL) {
1585 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 meta_path = PySys_GetObject("meta_path");
1588 if (meta_path == NULL || !PyList_Check(meta_path)) {
1589 PyErr_SetString(PyExc_ImportError,
1590 "sys.meta_path must be a list of "
1591 "import hooks");
1592 return NULL;
1593 }
1594 Py_INCREF(meta_path); /* zap guard */
1595 npath = PyList_Size(meta_path);
1596 for (i = 0; i < npath; i++) {
1597 PyObject *loader;
1598 PyObject *hook = PyList_GetItem(meta_path, i);
1599 loader = PyObject_CallMethod(hook, "find_module",
1600 "sO", fullname,
1601 path != NULL ?
1602 path : Py_None);
1603 if (loader == NULL) {
1604 Py_DECREF(meta_path);
1605 return NULL; /* true error */
1606 }
1607 if (loader != Py_None) {
1608 /* a loader was found */
1609 *p_loader = loader;
1610 Py_DECREF(meta_path);
1611 return &importhookdescr;
1612 }
1613 Py_DECREF(loader);
1614 }
1615 Py_DECREF(meta_path);
1616 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (find_frozen(fullname) != NULL) {
1619 strcpy(buf, fullname);
1620 return &fd_frozen;
1621 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (path == NULL) {
1624 if (is_builtin(name)) {
1625 strcpy(buf, name);
1626 return &fd_builtin;
1627 }
Guido van Rossumac279101996-08-22 23:10:58 +00001628#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1630 if (fp != NULL) {
1631 *p_fp = fp;
1632 return fdp;
1633 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001634#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 path = PySys_GetObject("path");
1636 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (path == NULL || !PyList_Check(path)) {
1639 PyErr_SetString(PyExc_ImportError,
1640 "sys.path must be a list of directory names");
1641 return NULL;
1642 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 path_hooks = PySys_GetObject("path_hooks");
1645 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1646 PyErr_SetString(PyExc_ImportError,
1647 "sys.path_hooks must be a list of "
1648 "import hooks");
1649 return NULL;
1650 }
1651 path_importer_cache = PySys_GetObject("path_importer_cache");
1652 if (path_importer_cache == NULL ||
1653 !PyDict_Check(path_importer_cache)) {
1654 PyErr_SetString(PyExc_ImportError,
1655 "sys.path_importer_cache must be a dict");
1656 return NULL;
1657 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 npath = PyList_Size(path);
1660 namelen = strlen(name);
1661 for (i = 0; i < npath; i++) {
1662 PyObject *v = PyList_GetItem(path, i);
1663 PyObject *origv = v;
1664 const char *base;
1665 Py_ssize_t size;
1666 if (!v)
1667 return NULL;
1668 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001669 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (v == NULL)
1671 return NULL;
1672 }
1673 else if (!PyBytes_Check(v))
1674 continue;
1675 else
1676 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 base = PyBytes_AS_STRING(v);
1679 size = PyBytes_GET_SIZE(v);
1680 len = size;
1681 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1682 Py_DECREF(v);
1683 continue; /* Too long */
1684 }
1685 strcpy(buf, base);
1686 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (strlen(buf) != len) {
1689 continue; /* v contains '\0' */
1690 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* sys.path_hooks import hook */
1693 if (p_loader != NULL) {
1694 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 importer = get_path_importer(path_importer_cache,
1697 path_hooks, origv);
1698 if (importer == NULL) {
1699 return NULL;
1700 }
1701 /* Note: importer is a borrowed reference */
1702 if (importer != Py_None) {
1703 PyObject *loader;
1704 loader = PyObject_CallMethod(importer,
1705 "find_module",
1706 "s", fullname);
1707 if (loader == NULL)
1708 return NULL; /* error */
1709 if (loader != Py_None) {
1710 /* a loader was found */
1711 *p_loader = loader;
1712 return &importhookdescr;
1713 }
1714 Py_DECREF(loader);
1715 continue;
1716 }
1717 }
1718 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001721#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001723#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 )
1725 buf[len++] = SEP;
1726 strcpy(buf+len, name);
1727 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* Check for package import (buf holds a directory name,
1730 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001731#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 if (stat(buf, &statbuf) == 0 && /* it exists */
1733 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1734 case_ok(buf, len, namelen, name)) { /* case matches */
1735 if (find_init_module(buf)) { /* and has __init__.py */
1736 return &fd_package;
1737 }
1738 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001739 int err;
1740 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1741 if (unicode == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return NULL;
Victor Stinnered7916d2010-10-17 02:07:09 +00001743 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1744 "Not importing directory '%U': missing __init__.py",
1745 unicode);
1746 Py_DECREF(unicode);
1747 if (err)
1748 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 }
1750 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001751#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001752#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 /* take a snapshot of the module spec for restoration
1754 * after the 8 character DLL hackery
1755 */
1756 saved_buf = strdup(buf);
1757 saved_len = len;
1758 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001759#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001761#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 /* OS/2 limits DLLs to 8 character names (w/o
1763 extension)
1764 * so if the name is longer than that and its a
1765 * dynamically loaded module we're going to try,
1766 * truncate the name before trying
1767 */
1768 if (strlen(subname) > 8) {
1769 /* is this an attempt to load a C extension? */
1770 const struct filedescr *scan;
1771 scan = _PyImport_DynLoadFiletab;
1772 while (scan->suffix != NULL) {
1773 if (!strcmp(scan->suffix, fdp->suffix))
1774 break;
1775 else
1776 scan++;
1777 }
1778 if (scan->suffix != NULL) {
1779 /* yes, so truncate the name */
1780 namelen = 8;
1781 len -= strlen(subname) - namelen;
1782 buf[len] = '\0';
1783 }
1784 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001785#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 strcpy(buf+len, fdp->suffix);
1787 if (Py_VerboseFlag > 1)
1788 PySys_WriteStderr("# trying %s\n", buf);
1789 filemode = fdp->mode;
1790 if (filemode[0] == 'U')
1791 filemode = "r" PY_STDIOTEXTMODE;
1792 fp = fopen(buf, filemode);
1793 if (fp != NULL) {
1794 if (case_ok(buf, len, namelen, name))
1795 break;
1796 else { /* continue search */
1797 fclose(fp);
1798 fp = NULL;
1799 }
1800 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001801#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* restore the saved snapshot */
1803 strcpy(buf, saved_buf);
1804 len = saved_len;
1805 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001806#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001808#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* don't need/want the module name snapshot anymore */
1810 if (saved_buf)
1811 {
1812 free(saved_buf);
1813 saved_buf = NULL;
1814 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001815#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (fp != NULL)
1817 break;
1818 }
1819 if (fp == NULL) {
1820 PyErr_Format(PyExc_ImportError,
1821 "No module named %.200s", name);
1822 return NULL;
1823 }
1824 *p_fp = fp;
1825 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001826}
1827
Martin v. Löwis18e16552006-02-15 17:27:45 +00001828/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001829 * The arguments here are tricky, best shown by example:
1830 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1831 * ^ ^ ^ ^
1832 * |--------------------- buf ---------------------|
1833 * |------------------- len ------------------|
1834 * |------ name -------|
1835 * |----- namelen -----|
1836 * buf is the full path, but len only counts up to (& exclusive of) the
1837 * extension. name is the module name, also exclusive of extension.
1838 *
1839 * We've already done a successful stat() or fopen() on buf, so know that
1840 * there's some match, possibly case-insensitive.
1841 *
Tim Peters50d8d372001-02-28 05:34:27 +00001842 * case_ok() is to return 1 if there's a case-sensitive match for
1843 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1844 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001845 *
Tim Peters50d8d372001-02-28 05:34:27 +00001846 * case_ok() is used to implement case-sensitive import semantics even
1847 * on platforms with case-insensitive filesystems. It's trivial to implement
1848 * for case-sensitive filesystems. It's pretty much a cross-platform
1849 * nightmare for systems with case-insensitive filesystems.
1850 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001851
Tim Peters50d8d372001-02-28 05:34:27 +00001852/* First we may need a pile of platform-specific header files; the sequence
1853 * of #if's here should match the sequence in the body of case_ok().
1854 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001855#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001856#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001857
Tim Peters50d8d372001-02-28 05:34:27 +00001858#elif defined(DJGPP)
1859#include <dir.h>
1860
Jason Tishler7961aa62005-05-20 00:56:54 +00001861#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001862#include <sys/types.h>
1863#include <dirent.h>
1864
Andrew MacIntyred9400542002-02-26 11:41:34 +00001865#elif defined(PYOS_OS2)
1866#define INCL_DOS
1867#define INCL_DOSERRORS
1868#define INCL_NOPMAPI
1869#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001870#endif
1871
Guido van Rossum0980bd91998-02-13 17:18:36 +00001872static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001873case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001874{
Tim Peters50d8d372001-02-28 05:34:27 +00001875/* Pick a platform-specific implementation; the sequence of #if's here should
1876 * match the sequence just above.
1877 */
1878
Jason Tishler7961aa62005-05-20 00:56:54 +00001879/* MS_WINDOWS */
1880#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 WIN32_FIND_DATA data;
1882 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (Py_GETENV("PYTHONCASEOK") != NULL)
1885 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 h = FindFirstFile(buf, &data);
1888 if (h == INVALID_HANDLE_VALUE) {
1889 PyErr_Format(PyExc_NameError,
1890 "Can't find file for module %.100s\n(filename %.300s)",
1891 name, buf);
1892 return 0;
1893 }
1894 FindClose(h);
1895 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001896
1897/* DJGPP */
1898#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 struct ffblk ffblk;
1900 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 if (Py_GETENV("PYTHONCASEOK") != NULL)
1903 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1906 if (done) {
1907 PyErr_Format(PyExc_NameError,
1908 "Can't find file for module %.100s\n(filename %.300s)",
1909 name, buf);
1910 return 0;
1911 }
1912 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001913
Jason Tishler7961aa62005-05-20 00:56:54 +00001914/* new-fangled macintosh (macosx) or Cygwin */
1915#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 DIR *dirp;
1917 struct dirent *dp;
1918 char dirname[MAXPATHLEN + 1];
1919 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 if (Py_GETENV("PYTHONCASEOK") != NULL)
1922 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 /* Copy the dir component into dirname; substitute "." if empty */
1925 if (dirlen <= 0) {
1926 dirname[0] = '.';
1927 dirname[1] = '\0';
1928 }
1929 else {
1930 assert(dirlen <= MAXPATHLEN);
1931 memcpy(dirname, buf, dirlen);
1932 dirname[dirlen] = '\0';
1933 }
1934 /* Open the directory and search the entries for an exact match. */
1935 dirp = opendir(dirname);
1936 if (dirp) {
1937 char *nameWithExt = buf + len - namelen;
1938 while ((dp = readdir(dirp)) != NULL) {
1939 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001940#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001942#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001944#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (thislen >= namelen &&
1946 strcmp(dp->d_name, nameWithExt) == 0) {
1947 (void)closedir(dirp);
1948 return 1; /* Found */
1949 }
1950 }
1951 (void)closedir(dirp);
1952 }
1953 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001954
Andrew MacIntyred9400542002-02-26 11:41:34 +00001955/* OS/2 */
1956#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 HDIR hdir = 1;
1958 ULONG srchcnt = 1;
1959 FILEFINDBUF3 ffbuf;
1960 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (Py_GETENV("PYTHONCASEOK") != NULL)
1963 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 rc = DosFindFirst(buf,
1966 &hdir,
1967 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1968 &ffbuf, sizeof(ffbuf),
1969 &srchcnt,
1970 FIL_STANDARD);
1971 if (rc != NO_ERROR)
1972 return 0;
1973 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001974
Tim Peters50d8d372001-02-28 05:34:27 +00001975/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1976#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001978
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001979#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001980}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001981
Guido van Rossum197346f1997-10-31 18:38:52 +00001982#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001983
Guido van Rossum197346f1997-10-31 18:38:52 +00001984/* Helper to look for __init__.py or __init__.py[co] in potential package */
1985static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001986find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 const size_t save_len = strlen(buf);
1989 size_t i = save_len;
1990 char *pname; /* pointer to start of __init__ */
1991 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993/* For calling case_ok(buf, len, namelen, name):
1994 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1995 * ^ ^ ^ ^
1996 * |--------------------- buf ---------------------|
1997 * |------------------- len ------------------|
1998 * |------ name -------|
1999 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002000 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (save_len + 13 >= MAXPATHLEN)
2002 return 0;
2003 buf[i++] = SEP;
2004 pname = buf + i;
2005 strcpy(pname, "__init__.py");
2006 if (stat(buf, &statbuf) == 0) {
2007 if (case_ok(buf,
2008 save_len + 9, /* len("/__init__") */
2009 8, /* len("__init__") */
2010 pname)) {
2011 buf[save_len] = '\0';
2012 return 1;
2013 }
2014 }
2015 i += strlen(pname);
2016 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2017 if (stat(buf, &statbuf) == 0) {
2018 if (case_ok(buf,
2019 save_len + 9, /* len("/__init__") */
2020 8, /* len("__init__") */
2021 pname)) {
2022 buf[save_len] = '\0';
2023 return 1;
2024 }
2025 }
2026 buf[save_len] = '\0';
2027 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002028}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002029
Guido van Rossum197346f1997-10-31 18:38:52 +00002030#endif /* HAVE_STAT */
2031
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002032
Tim Petersdbd9ba62000-07-09 03:09:57 +00002033static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002034
Victor Stinner44c6c152010-08-09 00:59:10 +00002035static PyObject*
2036load_builtin(char *name, char *pathname, int type)
2037{
2038 PyObject *m, *modules;
2039 int err;
2040
2041 if (pathname != NULL && pathname[0] != '\0')
2042 name = pathname;
2043
2044 if (type == C_BUILTIN)
2045 err = init_builtin(name);
2046 else
2047 err = PyImport_ImportFrozenModule(name);
2048 if (err < 0)
2049 return NULL;
2050 if (err == 0) {
2051 PyErr_Format(PyExc_ImportError,
2052 "Purported %s module %.200s not found",
2053 type == C_BUILTIN ?
2054 "builtin" : "frozen",
2055 name);
2056 return NULL;
2057 }
2058
2059 modules = PyImport_GetModuleDict();
2060 m = PyDict_GetItemString(modules, name);
2061 if (m == NULL) {
2062 PyErr_Format(
2063 PyExc_ImportError,
2064 "%s module %.200s not properly initialized",
2065 type == C_BUILTIN ?
2066 "builtin" : "frozen",
2067 name);
2068 return NULL;
2069 }
2070 Py_INCREF(m);
2071 return m;
2072}
2073
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002074/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002075 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002076
Guido van Rossum79f25d91997-04-29 20:08:16 +00002077static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002078load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 /* First check that there's an open file (if we need one) */
2083 switch (type) {
2084 case PY_SOURCE:
2085 case PY_COMPILED:
2086 if (fp == NULL) {
2087 PyErr_Format(PyExc_ValueError,
2088 "file object required for import (type code %d)",
2089 type);
2090 return NULL;
2091 }
2092 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 case PY_SOURCE:
2097 m = load_source_module(name, pathname, fp);
2098 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 case PY_COMPILED:
2101 m = load_compiled_module(name, pathname, fp);
2102 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002103
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002104#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 case C_EXTENSION:
2106 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2107 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002108#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 case PKG_DIRECTORY:
2111 m = load_package(name, pathname);
2112 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 case C_BUILTIN:
2115 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002116 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 case IMP_HOOK: {
2120 if (loader == NULL) {
2121 PyErr_SetString(PyExc_ImportError,
2122 "import hook without loader");
2123 return NULL;
2124 }
2125 m = PyObject_CallMethod(loader, "load_module", "s", name);
2126 break;
2127 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 default:
2130 PyErr_Format(PyExc_ImportError,
2131 "Don't know how to import %.200s (type code %d)",
2132 name, type);
2133 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002138}
2139
2140
2141/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002142 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002143 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002144
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002145static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002146init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002149
Victor Stinner49d3f252010-10-17 01:24:53 +00002150 if (_PyImport_FindBuiltin(name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 for (p = PyImport_Inittab; p->name != NULL; p++) {
2154 PyObject *mod;
2155 if (strcmp(name, p->name) == 0) {
2156 if (p->initfunc == NULL) {
2157 PyErr_Format(PyExc_ImportError,
2158 "Cannot re-init internal module %.200s",
2159 name);
2160 return -1;
2161 }
2162 if (Py_VerboseFlag)
2163 PySys_WriteStderr("import %s # builtin\n", name);
2164 mod = (*p->initfunc)();
2165 if (mod == 0)
2166 return -1;
Victor Stinner49d3f252010-10-17 01:24:53 +00002167 if (_PyImport_FixupBuiltin(mod, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 return -1;
2169 /* FixupExtension has put the module into sys.modules,
2170 so we can release our own reference. */
2171 Py_DECREF(mod);
2172 return 1;
2173 }
2174 }
2175 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002176}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002177
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002178
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002179/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002180
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002181static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002182find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (!name)
2187 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 for (p = PyImport_FrozenModules; ; p++) {
2190 if (p->name == NULL)
2191 return NULL;
2192 if (strcmp(p->name, name) == 0)
2193 break;
2194 }
2195 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002196}
2197
Guido van Rossum79f25d91997-04-29 20:08:16 +00002198static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002199get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 struct _frozen *p = find_frozen(name);
2202 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (p == NULL) {
2205 PyErr_Format(PyExc_ImportError,
2206 "No such frozen object named %.200s",
2207 name);
2208 return NULL;
2209 }
2210 if (p->code == NULL) {
2211 PyErr_Format(PyExc_ImportError,
2212 "Excluded frozen object named %.200s",
2213 name);
2214 return NULL;
2215 }
2216 size = p->size;
2217 if (size < 0)
2218 size = -size;
2219 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002220}
2221
Brett Cannon8d110132009-03-15 02:20:16 +00002222static PyObject *
2223is_frozen_package(char *name)
2224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 struct _frozen *p = find_frozen(name);
2226 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 if (p == NULL) {
2229 PyErr_Format(PyExc_ImportError,
2230 "No such frozen object named %.200s",
2231 name);
2232 return NULL;
2233 }
Brett Cannon8d110132009-03-15 02:20:16 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (size < 0)
2238 Py_RETURN_TRUE;
2239 else
2240 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002241}
2242
2243
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002244/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002245 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002246 an exception set if the initialization failed.
2247 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002248
2249int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002250PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 struct _frozen *p = find_frozen(name);
2253 PyObject *co;
2254 PyObject *m;
2255 int ispackage;
2256 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if (p == NULL)
2259 return 0;
2260 if (p->code == NULL) {
2261 PyErr_Format(PyExc_ImportError,
2262 "Excluded frozen object named %.200s",
2263 name);
2264 return -1;
2265 }
2266 size = p->size;
2267 ispackage = (size < 0);
2268 if (ispackage)
2269 size = -size;
2270 if (Py_VerboseFlag)
2271 PySys_WriteStderr("import %s # frozen%s\n",
2272 name, ispackage ? " package" : "");
2273 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2274 if (co == NULL)
2275 return -1;
2276 if (!PyCode_Check(co)) {
2277 PyErr_Format(PyExc_TypeError,
2278 "frozen object %.200s is not a code object",
2279 name);
2280 goto err_return;
2281 }
2282 if (ispackage) {
2283 /* Set __path__ to the package name */
2284 PyObject *d, *s, *l;
2285 int err;
2286 m = PyImport_AddModule(name);
2287 if (m == NULL)
2288 goto err_return;
2289 d = PyModule_GetDict(m);
2290 s = PyUnicode_InternFromString(name);
2291 if (s == NULL)
2292 goto err_return;
2293 l = PyList_New(1);
2294 if (l == NULL) {
2295 Py_DECREF(s);
2296 goto err_return;
2297 }
2298 PyList_SET_ITEM(l, 0, s);
2299 err = PyDict_SetItemString(d, "__path__", l);
2300 Py_DECREF(l);
2301 if (err != 0)
2302 goto err_return;
2303 }
2304 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2305 if (m == NULL)
2306 goto err_return;
2307 Py_DECREF(co);
2308 Py_DECREF(m);
2309 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002310err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 Py_DECREF(co);
2312 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002313}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002314
2315
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002316/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002317 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002318
Guido van Rossum79f25d91997-04-29 20:08:16 +00002319PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002320PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 PyObject *pname;
2323 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 pname = PyUnicode_FromString(name);
2326 if (pname == NULL)
2327 return NULL;
2328 result = PyImport_Import(pname);
2329 Py_DECREF(pname);
2330 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002331}
2332
Christian Heimes072c0f12008-01-03 23:01:04 +00002333/* Import a module without blocking
2334 *
2335 * At first it tries to fetch the module from sys.modules. If the module was
2336 * never loaded before it loads it with PyImport_ImportModule() unless another
2337 * thread holds the import lock. In the latter case the function raises an
2338 * ImportError instead of blocking.
2339 *
2340 * Returns the module object with incremented ref count.
2341 */
2342PyObject *
2343PyImport_ImportModuleNoBlock(const char *name)
2344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyObject *result;
2346 PyObject *modules;
2347 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Try to get the module from sys.modules[name] */
2350 modules = PyImport_GetModuleDict();
2351 if (modules == NULL)
2352 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 result = PyDict_GetItemString(modules, name);
2355 if (result != NULL) {
2356 Py_INCREF(result);
2357 return result;
2358 }
2359 else {
2360 PyErr_Clear();
2361 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002362#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* check the import lock
2364 * me might be -1 but I ignore the error here, the lock function
2365 * takes care of the problem */
2366 me = PyThread_get_thread_ident();
2367 if (import_lock_thread == -1 || import_lock_thread == me) {
2368 /* no thread or me is holding the lock */
2369 return PyImport_ImportModule(name);
2370 }
2371 else {
2372 PyErr_Format(PyExc_ImportError,
2373 "Failed to import %.200s because the import lock"
2374 "is held by another thread.",
2375 name);
2376 return NULL;
2377 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002378#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002380#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002381}
2382
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002383/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002384static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002386static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002388static int mark_miss(char *name);
2389static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002391static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002392
2393/* The Magnum Opus of dotted-name import :-) */
2394
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002395static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002396import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 char buf[MAXPATHLEN+1];
2400 Py_ssize_t buflen = 0;
2401 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002404#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002406#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 ) {
2408 PyErr_SetString(PyExc_ImportError,
2409 "Import by filename is not supported.");
2410 return NULL;
2411 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 parent = get_parent(globals, buf, &buflen, level);
2414 if (parent == NULL)
2415 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002416
Benjamin Peterson556d8002010-06-27 22:37:28 +00002417 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2418 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 if (head == NULL)
2420 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 tail = head;
2423 Py_INCREF(tail);
2424 while (name) {
2425 next = load_next(tail, tail, &name, buf, &buflen);
2426 Py_DECREF(tail);
2427 if (next == NULL) {
2428 Py_DECREF(head);
2429 return NULL;
2430 }
2431 tail = next;
2432 }
2433 if (tail == Py_None) {
2434 /* If tail is Py_None, both get_parent and load_next found
2435 an empty module name: someone called __import__("") or
2436 doctored faulty bytecode */
2437 Py_DECREF(tail);
2438 Py_DECREF(head);
2439 PyErr_SetString(PyExc_ValueError,
2440 "Empty module name");
2441 return NULL;
2442 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (fromlist != NULL) {
2445 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2446 fromlist = NULL;
2447 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 if (fromlist == NULL) {
2450 Py_DECREF(tail);
2451 return head;
2452 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 Py_DECREF(head);
2455 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2456 Py_DECREF(tail);
2457 return NULL;
2458 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002461}
2462
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002463PyObject *
2464PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyObject *result;
2468 _PyImport_AcquireLock();
2469 result = import_module_level(name, globals, locals, fromlist, level);
2470 if (_PyImport_ReleaseLock() < 0) {
2471 Py_XDECREF(result);
2472 PyErr_SetString(PyExc_RuntimeError,
2473 "not holding the import lock");
2474 return NULL;
2475 }
2476 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002477}
2478
Fred Drake87590902004-05-28 20:21:36 +00002479/* Return the package that an import is being performed in. If globals comes
2480 from the module foo.bar.bat (not itself a package), this returns the
2481 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002482 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002483
2484 The *name* of the returned package is returned in buf, with the length of
2485 the name in *p_buflen.
2486
2487 If globals doesn't come from a package or a module in a package, or a
2488 corresponding entry is not found in sys.modules, Py_None is returned.
2489*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002490static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002491get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 static PyObject *namestr = NULL;
2494 static PyObject *pathstr = NULL;
2495 static PyObject *pkgstr = NULL;
2496 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2497 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (globals == NULL || !PyDict_Check(globals) || !level)
2500 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 if (namestr == NULL) {
2503 namestr = PyUnicode_InternFromString("__name__");
2504 if (namestr == NULL)
2505 return NULL;
2506 }
2507 if (pathstr == NULL) {
2508 pathstr = PyUnicode_InternFromString("__path__");
2509 if (pathstr == NULL)
2510 return NULL;
2511 }
2512 if (pkgstr == NULL) {
2513 pkgstr = PyUnicode_InternFromString("__package__");
2514 if (pkgstr == NULL)
2515 return NULL;
2516 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 *buf = '\0';
2519 *p_buflen = 0;
2520 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if ((pkgname != NULL) && (pkgname != Py_None)) {
2523 /* __package__ is set, so use it */
2524 char *pkgname_str;
2525 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 if (!PyUnicode_Check(pkgname)) {
2528 PyErr_SetString(PyExc_ValueError,
2529 "__package__ set to non-string");
2530 return NULL;
2531 }
2532 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2533 if (len == 0) {
2534 if (level > 0) {
2535 PyErr_SetString(PyExc_ValueError,
2536 "Attempted relative import in non-package");
2537 return NULL;
2538 }
2539 return Py_None;
2540 }
2541 if (len > MAXPATHLEN) {
2542 PyErr_SetString(PyExc_ValueError,
2543 "Package name too long");
2544 return NULL;
2545 }
2546 strcpy(buf, pkgname_str);
2547 } else {
2548 /* __package__ not set, so figure it out and set it */
2549 modname = PyDict_GetItem(globals, namestr);
2550 if (modname == NULL || !PyUnicode_Check(modname))
2551 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 modpath = PyDict_GetItem(globals, pathstr);
2554 if (modpath != NULL) {
2555 /* __path__ is set, so modname is already the package name */
2556 char *modname_str;
2557 Py_ssize_t len;
2558 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2561 if (len > MAXPATHLEN) {
2562 PyErr_SetString(PyExc_ValueError,
2563 "Module name too long");
2564 return NULL;
2565 }
2566 strcpy(buf, modname_str);
2567 error = PyDict_SetItem(globals, pkgstr, modname);
2568 if (error) {
2569 PyErr_SetString(PyExc_ValueError,
2570 "Could not set __package__");
2571 return NULL;
2572 }
2573 } else {
2574 /* Normal module, so work out the package name if any */
2575 char *start = _PyUnicode_AsString(modname);
2576 char *lastdot = strrchr(start, '.');
2577 size_t len;
2578 int error;
2579 if (lastdot == NULL && level > 0) {
2580 PyErr_SetString(PyExc_ValueError,
2581 "Attempted relative import in non-package");
2582 return NULL;
2583 }
2584 if (lastdot == NULL) {
2585 error = PyDict_SetItem(globals, pkgstr, Py_None);
2586 if (error) {
2587 PyErr_SetString(PyExc_ValueError,
2588 "Could not set __package__");
2589 return NULL;
2590 }
2591 return Py_None;
2592 }
2593 len = lastdot - start;
2594 if (len >= MAXPATHLEN) {
2595 PyErr_SetString(PyExc_ValueError,
2596 "Module name too long");
2597 return NULL;
2598 }
2599 strncpy(buf, start, len);
2600 buf[len] = '\0';
2601 pkgname = PyUnicode_FromString(buf);
2602 if (pkgname == NULL) {
2603 return NULL;
2604 }
2605 error = PyDict_SetItem(globals, pkgstr, pkgname);
2606 Py_DECREF(pkgname);
2607 if (error) {
2608 PyErr_SetString(PyExc_ValueError,
2609 "Could not set __package__");
2610 return NULL;
2611 }
2612 }
2613 }
2614 while (--level > 0) {
2615 char *dot = strrchr(buf, '.');
2616 if (dot == NULL) {
2617 PyErr_SetString(PyExc_ValueError,
2618 "Attempted relative import beyond "
2619 "toplevel package");
2620 return NULL;
2621 }
2622 *dot = '\0';
2623 }
2624 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 modules = PyImport_GetModuleDict();
2627 parent = PyDict_GetItemString(modules, buf);
2628 if (parent == NULL) {
2629 if (orig_level < 1) {
2630 PyObject *err_msg = PyBytes_FromFormat(
2631 "Parent module '%.200s' not found "
2632 "while handling absolute import", buf);
2633 if (err_msg == NULL) {
2634 return NULL;
2635 }
2636 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2637 PyBytes_AsString(err_msg), 1)) {
2638 *buf = '\0';
2639 *p_buflen = 0;
2640 parent = Py_None;
2641 }
2642 Py_DECREF(err_msg);
2643 } else {
2644 PyErr_Format(PyExc_SystemError,
2645 "Parent module '%.200s' not loaded, "
2646 "cannot perform relative import", buf);
2647 }
2648 }
2649 return parent;
2650 /* We expect, but can't guarantee, if parent != None, that:
2651 - parent.__name__ == buf
2652 - parent.__dict__ is globals
2653 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002654}
2655
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002656/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002657static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002658load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 char *name = *p_name;
2662 char *dot = strchr(name, '.');
2663 size_t len;
2664 char *p;
2665 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (strlen(name) == 0) {
2668 /* completely empty module name should only happen in
2669 'from . import' (or '__import__("")')*/
2670 Py_INCREF(mod);
2671 *p_name = NULL;
2672 return mod;
2673 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 if (dot == NULL) {
2676 *p_name = NULL;
2677 len = strlen(name);
2678 }
2679 else {
2680 *p_name = dot+1;
2681 len = dot-name;
2682 }
2683 if (len == 0) {
2684 PyErr_SetString(PyExc_ValueError,
2685 "Empty module name");
2686 return NULL;
2687 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 p = buf + *p_buflen;
2690 if (p != buf)
2691 *p++ = '.';
2692 if (p+len-buf >= MAXPATHLEN) {
2693 PyErr_SetString(PyExc_ValueError,
2694 "Module name too long");
2695 return NULL;
2696 }
2697 strncpy(p, name, len);
2698 p[len] = '\0';
2699 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 result = import_submodule(mod, p, buf);
2702 if (result == Py_None && altmod != mod) {
2703 Py_DECREF(result);
2704 /* Here, altmod must be None and mod must not be None */
2705 result = import_submodule(altmod, p, p);
2706 if (result != NULL && result != Py_None) {
2707 if (mark_miss(buf) != 0) {
2708 Py_DECREF(result);
2709 return NULL;
2710 }
2711 strncpy(buf, name, len);
2712 buf[len] = '\0';
2713 *p_buflen = len;
2714 }
2715 }
2716 if (result == NULL)
2717 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 if (result == Py_None) {
2720 Py_DECREF(result);
2721 PyErr_Format(PyExc_ImportError,
2722 "No module named %.200s", name);
2723 return NULL;
2724 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002727}
2728
2729static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002730mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 PyObject *modules = PyImport_GetModuleDict();
2733 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002734}
2735
2736static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002737ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 if (!PyObject_HasAttrString(mod, "__path__"))
2743 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 for (i = 0; ; i++) {
2746 PyObject *item = PySequence_GetItem(fromlist, i);
2747 int hasit;
2748 if (item == NULL) {
2749 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2750 PyErr_Clear();
2751 return 1;
2752 }
2753 return 0;
2754 }
2755 if (!PyUnicode_Check(item)) {
2756 PyErr_SetString(PyExc_TypeError,
2757 "Item in ``from list'' not a string");
2758 Py_DECREF(item);
2759 return 0;
2760 }
2761 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2762 PyObject *all;
2763 Py_DECREF(item);
2764 /* See if the package defines __all__ */
2765 if (recursive)
2766 continue; /* Avoid endless recursion */
2767 all = PyObject_GetAttrString(mod, "__all__");
2768 if (all == NULL)
2769 PyErr_Clear();
2770 else {
2771 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2772 Py_DECREF(all);
2773 if (!ret)
2774 return 0;
2775 }
2776 continue;
2777 }
2778 hasit = PyObject_HasAttr(mod, item);
2779 if (!hasit) {
2780 PyObject *item8;
2781 char *subname;
2782 PyObject *submod;
2783 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002784 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 if (!item8) {
2786 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2787 return 0;
2788 }
2789 subname = PyBytes_AS_STRING(item8);
2790 if (buflen + strlen(subname) >= MAXPATHLEN) {
2791 PyErr_SetString(PyExc_ValueError,
2792 "Module name too long");
2793 Py_DECREF(item);
2794 return 0;
2795 }
2796 p = buf + buflen;
2797 *p++ = '.';
2798 strcpy(p, subname);
2799 submod = import_submodule(mod, subname, buf);
2800 Py_DECREF(item8);
2801 Py_XDECREF(submod);
2802 if (submod == NULL) {
2803 Py_DECREF(item);
2804 return 0;
2805 }
2806 }
2807 Py_DECREF(item);
2808 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002811}
2812
Neil Schemenauer00b09662003-06-16 21:03:07 +00002813static int
2814add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 if (mod == Py_None)
2818 return 1;
2819 /* Irrespective of the success of this load, make a
2820 reference to it in the parent package module. A copy gets
2821 saved in the modules dictionary under the full name, so get a
2822 reference from there, if need be. (The exception is when the
2823 load failed with a SyntaxError -- then there's no trace in
2824 sys.modules. In that case, of course, do nothing extra.) */
2825 if (submod == NULL) {
2826 submod = PyDict_GetItemString(modules, fullname);
2827 if (submod == NULL)
2828 return 1;
2829 }
2830 if (PyModule_Check(mod)) {
2831 /* We can't use setattr here since it can give a
2832 * spurious warning if the submodule name shadows a
2833 * builtin name */
2834 PyObject *dict = PyModule_GetDict(mod);
2835 if (!dict)
2836 return 0;
2837 if (PyDict_SetItemString(dict, subname, submod) < 0)
2838 return 0;
2839 }
2840 else {
2841 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2842 return 0;
2843 }
2844 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002845}
2846
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002847static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002848import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 PyObject *modules = PyImport_GetModuleDict();
2851 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 /* Require:
2854 if mod == None: subname == fullname
2855 else: mod.__name__ + "." + subname == fullname
2856 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2859 Py_INCREF(m);
2860 }
2861 else {
2862 PyObject *path, *loader = NULL;
2863 char buf[MAXPATHLEN+1];
2864 struct filedescr *fdp;
2865 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 if (mod == Py_None)
2868 path = NULL;
2869 else {
2870 path = PyObject_GetAttrString(mod, "__path__");
2871 if (path == NULL) {
2872 PyErr_Clear();
2873 Py_INCREF(Py_None);
2874 return Py_None;
2875 }
2876 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 buf[0] = '\0';
2879 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2880 &fp, &loader);
2881 Py_XDECREF(path);
2882 if (fdp == NULL) {
2883 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2884 return NULL;
2885 PyErr_Clear();
2886 Py_INCREF(Py_None);
2887 return Py_None;
2888 }
2889 m = load_module(fullname, fp, buf, fdp->type, loader);
2890 Py_XDECREF(loader);
2891 if (fp)
2892 fclose(fp);
2893 if (!add_submodule(mod, m, fullname, subname, modules)) {
2894 Py_XDECREF(m);
2895 m = NULL;
2896 }
2897 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002900}
2901
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002902
2903/* Re-import a module of any kind and return its module object, WITH
2904 INCREMENTED REFERENCE COUNT */
2905
Guido van Rossum79f25d91997-04-29 20:08:16 +00002906PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002907PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 PyInterpreterState *interp = PyThreadState_Get()->interp;
2910 PyObject *modules_reloading = interp->modules_reloading;
2911 PyObject *modules = PyImport_GetModuleDict();
2912 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2913 char *name, *subname;
2914 char buf[MAXPATHLEN+1];
2915 struct filedescr *fdp;
2916 FILE *fp = NULL;
2917 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (modules_reloading == NULL) {
2920 Py_FatalError("PyImport_ReloadModule: "
2921 "no modules_reloading dictionary!");
2922 return NULL;
2923 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 if (m == NULL || !PyModule_Check(m)) {
2926 PyErr_SetString(PyExc_TypeError,
2927 "reload() argument must be module");
2928 return NULL;
2929 }
2930 name = (char*)PyModule_GetName(m);
2931 if (name == NULL)
2932 return NULL;
2933 if (m != PyDict_GetItemString(modules, name)) {
2934 PyErr_Format(PyExc_ImportError,
2935 "reload(): module %.200s not in sys.modules",
2936 name);
2937 return NULL;
2938 }
2939 existing_m = PyDict_GetItemString(modules_reloading, name);
2940 if (existing_m != NULL) {
2941 /* Due to a recursive reload, this module is already
2942 being reloaded. */
2943 Py_INCREF(existing_m);
2944 return existing_m;
2945 }
2946 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2947 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 subname = strrchr(name, '.');
2950 if (subname == NULL)
2951 subname = name;
2952 else {
2953 PyObject *parentname, *parent;
2954 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2955 if (parentname == NULL) {
2956 imp_modules_reloading_clear();
2957 return NULL;
2958 }
2959 parent = PyDict_GetItem(modules, parentname);
2960 if (parent == NULL) {
2961 PyErr_Format(PyExc_ImportError,
2962 "reload(): parent %U not in sys.modules",
2963 parentname);
2964 Py_DECREF(parentname);
2965 imp_modules_reloading_clear();
2966 return NULL;
2967 }
2968 Py_DECREF(parentname);
2969 subname++;
2970 path = PyObject_GetAttrString(parent, "__path__");
2971 if (path == NULL)
2972 PyErr_Clear();
2973 }
2974 buf[0] = '\0';
2975 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2976 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 if (fdp == NULL) {
2979 Py_XDECREF(loader);
2980 imp_modules_reloading_clear();
2981 return NULL;
2982 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 newm = load_module(name, fp, buf, fdp->type, loader);
2985 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 if (fp)
2988 fclose(fp);
2989 if (newm == NULL) {
2990 /* load_module probably removed name from modules because of
2991 * the error. Put back the original module object. We're
2992 * going to return NULL in this case regardless of whether
2993 * replacing name succeeds, so the return value is ignored.
2994 */
2995 PyDict_SetItemString(modules, name, m);
2996 }
2997 imp_modules_reloading_clear();
2998 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002999}
3000
3001
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003002/* Higher-level import emulator which emulates the "import" statement
3003 more accurately -- it invokes the __import__() function from the
3004 builtins of the current globals. This means that the import is
3005 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003006 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003007 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003008 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003009 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003010
3011PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003012PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 static PyObject *silly_list = NULL;
3015 static PyObject *builtins_str = NULL;
3016 static PyObject *import_str = NULL;
3017 PyObject *globals = NULL;
3018 PyObject *import = NULL;
3019 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003020 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 /* Initialize constant string objects */
3024 if (silly_list == NULL) {
3025 import_str = PyUnicode_InternFromString("__import__");
3026 if (import_str == NULL)
3027 return NULL;
3028 builtins_str = PyUnicode_InternFromString("__builtins__");
3029 if (builtins_str == NULL)
3030 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003031 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 if (silly_list == NULL)
3033 return NULL;
3034 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 /* Get the builtins from current globals */
3037 globals = PyEval_GetGlobals();
3038 if (globals != NULL) {
3039 Py_INCREF(globals);
3040 builtins = PyObject_GetItem(globals, builtins_str);
3041 if (builtins == NULL)
3042 goto err;
3043 }
3044 else {
3045 /* No globals -- use standard builtins, and fake globals */
3046 builtins = PyImport_ImportModuleLevel("builtins",
3047 NULL, NULL, NULL, 0);
3048 if (builtins == NULL)
3049 return NULL;
3050 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3051 if (globals == NULL)
3052 goto err;
3053 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 /* Get the __import__ function from the builtins */
3056 if (PyDict_Check(builtins)) {
3057 import = PyObject_GetItem(builtins, import_str);
3058 if (import == NULL)
3059 PyErr_SetObject(PyExc_KeyError, import_str);
3060 }
3061 else
3062 import = PyObject_GetAttr(builtins, import_str);
3063 if (import == NULL)
3064 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003067 Always use absolute import here.
3068 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3070 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003071 if (r == NULL)
3072 goto err;
3073 Py_DECREF(r);
3074
3075 modules = PyImport_GetModuleDict();
3076 r = PyDict_GetItem(modules, module_name);
3077 if (r != NULL)
3078 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003079
3080 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 Py_XDECREF(globals);
3082 Py_XDECREF(builtins);
3083 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003086}
3087
3088
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003089/* Module 'imp' provides Python access to the primitives used for
3090 importing modules.
3091*/
3092
Guido van Rossum79f25d91997-04-29 20:08:16 +00003093static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003094imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 buf[0] = (char) ((magic >> 0) & 0xff);
3099 buf[1] = (char) ((magic >> 8) & 0xff);
3100 buf[2] = (char) ((magic >> 16) & 0xff);
3101 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003104}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003105
3106static PyObject *
3107imp_get_magic(PyObject *self, PyObject *noargs)
3108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003110}
3111
3112static PyObject *
3113imp_get_tag(PyObject *self, PyObject *noargs)
3114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003116}
3117
Guido van Rossum79f25d91997-04-29 20:08:16 +00003118static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003119imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 PyObject *list;
3122 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 list = PyList_New(0);
3125 if (list == NULL)
3126 return NULL;
3127 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3128 PyObject *item = Py_BuildValue("ssi",
3129 fdp->suffix, fdp->mode, fdp->type);
3130 if (item == NULL) {
3131 Py_DECREF(list);
3132 return NULL;
3133 }
3134 if (PyList_Append(list, item) < 0) {
3135 Py_DECREF(list);
3136 Py_DECREF(item);
3137 return NULL;
3138 }
3139 Py_DECREF(item);
3140 }
3141 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003142}
3143
Guido van Rossum79f25d91997-04-29 20:08:16 +00003144static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003145call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 extern int fclose(FILE *);
3148 PyObject *fob, *ret;
3149 PyObject *pathobj;
3150 struct filedescr *fdp;
3151 char pathname[MAXPATHLEN+1];
3152 FILE *fp = NULL;
3153 int fd = -1;
3154 char *found_encoding = NULL;
3155 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 pathname[0] = '\0';
3158 if (path == Py_None)
3159 path = NULL;
3160 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3161 if (fdp == NULL)
3162 return NULL;
3163 if (fp != NULL) {
3164 fd = fileno(fp);
3165 if (fd != -1)
3166 fd = dup(fd);
3167 fclose(fp);
3168 fp = NULL;
3169 }
3170 if (fd != -1) {
3171 if (strchr(fdp->mode, 'b') == NULL) {
3172 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3173 memory. */
3174 found_encoding = PyTokenizer_FindEncoding(fd);
3175 lseek(fd, 0, 0); /* Reset position */
3176 if (found_encoding == NULL && PyErr_Occurred())
3177 return NULL;
3178 encoding = (found_encoding != NULL) ? found_encoding :
3179 (char*)PyUnicode_GetDefaultEncoding();
3180 }
3181 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3182 (char*)encoding, NULL, NULL, 1);
3183 if (fob == NULL) {
3184 close(fd);
3185 PyMem_FREE(found_encoding);
3186 return NULL;
3187 }
3188 }
3189 else {
3190 fob = Py_None;
3191 Py_INCREF(fob);
3192 }
3193 pathobj = PyUnicode_DecodeFSDefault(pathname);
3194 ret = Py_BuildValue("NN(ssi)",
3195 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3196 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003199}
3200
Guido van Rossum79f25d91997-04-29 20:08:16 +00003201static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003202imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 char *name;
3205 PyObject *ret, *path = NULL;
3206 if (!PyArg_ParseTuple(args, "es|O:find_module",
3207 Py_FileSystemDefaultEncoding, &name,
3208 &path))
3209 return NULL;
3210 ret = call_find_module(name, path);
3211 PyMem_Free(name);
3212 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003213}
3214
3215static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003216imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 char *name;
3219 int ret;
3220 PyObject *m;
3221 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3222 return NULL;
3223 ret = init_builtin(name);
3224 if (ret < 0)
3225 return NULL;
3226 if (ret == 0) {
3227 Py_INCREF(Py_None);
3228 return Py_None;
3229 }
3230 m = PyImport_AddModule(name);
3231 Py_XINCREF(m);
3232 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003233}
3234
Guido van Rossum79f25d91997-04-29 20:08:16 +00003235static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003236imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 char *name;
3239 int ret;
3240 PyObject *m;
3241 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3242 return NULL;
3243 ret = PyImport_ImportFrozenModule(name);
3244 if (ret < 0)
3245 return NULL;
3246 if (ret == 0) {
3247 Py_INCREF(Py_None);
3248 return Py_None;
3249 }
3250 m = PyImport_AddModule(name);
3251 Py_XINCREF(m);
3252 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003253}
3254
Guido van Rossum79f25d91997-04-29 20:08:16 +00003255static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003256imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3261 return NULL;
3262 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003263}
3264
Guido van Rossum79f25d91997-04-29 20:08:16 +00003265static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003266imp_is_frozen_package(PyObject *self, PyObject *args)
3267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3271 return NULL;
3272 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003273}
3274
3275static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003276imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 char *name;
3279 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3280 return NULL;
3281 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003282}
3283
Guido van Rossum79f25d91997-04-29 20:08:16 +00003284static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003285imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 char *name;
3288 struct _frozen *p;
3289 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3290 return NULL;
3291 p = find_frozen(name);
3292 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003293}
3294
3295static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003296get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 FILE *fp;
3299 if (mode[0] == 'U')
3300 mode = "r" PY_STDIOTEXTMODE;
3301 if (fob == NULL) {
3302 fp = fopen(pathname, mode);
3303 }
3304 else {
3305 int fd = PyObject_AsFileDescriptor(fob);
3306 if (fd == -1)
3307 return NULL;
3308 if (!_PyVerify_fd(fd))
3309 goto error;
3310 /* the FILE struct gets a new fd, so that it can be closed
3311 * independently of the file descriptor given
3312 */
3313 fd = dup(fd);
3314 if (fd == -1)
3315 goto error;
3316 fp = fdopen(fd, mode);
3317 }
3318 if (fp)
3319 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003320error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 PyErr_SetFromErrno(PyExc_IOError);
3322 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003323}
3324
Guido van Rossum79f25d91997-04-29 20:08:16 +00003325static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003326imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 char *name;
3329 char *pathname;
3330 PyObject *fob = NULL;
3331 PyObject *m;
3332 FILE *fp;
3333 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3334 &name,
3335 Py_FileSystemDefaultEncoding, &pathname,
3336 &fob))
3337 return NULL;
3338 fp = get_file(pathname, fob, "rb");
3339 if (fp == NULL) {
3340 PyMem_Free(pathname);
3341 return NULL;
3342 }
3343 m = load_compiled_module(name, pathname, fp);
3344 fclose(fp);
3345 PyMem_Free(pathname);
3346 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003347}
3348
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003349#ifdef HAVE_DYNAMIC_LOADING
3350
Guido van Rossum79f25d91997-04-29 20:08:16 +00003351static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003352imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003355 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 char *pathname;
3357 PyObject *fob = NULL;
3358 PyObject *m;
3359 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003360 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3361 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003363 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 if (fob) {
3365 fp = get_file(pathname, fob, "r");
3366 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003367 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 return NULL;
3369 }
3370 }
3371 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003372 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 if (fp)
3374 fclose(fp);
3375 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003376}
3377
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003378#endif /* HAVE_DYNAMIC_LOADING */
3379
Guido van Rossum79f25d91997-04-29 20:08:16 +00003380static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003381imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 char *name;
3384 char *pathname;
3385 PyObject *fob = NULL;
3386 PyObject *m;
3387 FILE *fp;
3388 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3389 &name,
3390 Py_FileSystemDefaultEncoding, &pathname,
3391 &fob))
3392 return NULL;
3393 fp = get_file(pathname, fob, "r");
3394 if (fp == NULL) {
3395 PyMem_Free(pathname);
3396 return NULL;
3397 }
3398 m = load_source_module(name, pathname, fp);
3399 PyMem_Free(pathname);
3400 fclose(fp);
3401 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003402}
3403
Guido van Rossum79f25d91997-04-29 20:08:16 +00003404static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003405imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 char *name;
3408 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003409 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 PyObject * ret;
3411 char *suffix; /* Unused */
3412 char *mode;
3413 int type;
3414 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003415
Victor Stinner1a563032010-10-15 22:43:10 +00003416 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003418 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 &suffix, &mode, &type))
3420 return NULL;
3421 if (*mode) {
3422 /* Mode must start with 'r' or 'U' and must not contain '+'.
3423 Implicit in this test is the assumption that the mode
3424 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3427 PyErr_Format(PyExc_ValueError,
3428 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003429 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 return NULL;
3431 }
3432 }
3433 if (fob == Py_None)
3434 fp = NULL;
3435 else {
3436 fp = get_file(NULL, fob, mode);
3437 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003438 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 return NULL;
3440 }
3441 }
Victor Stinner1a563032010-10-15 22:43:10 +00003442 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3443 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (fp)
3445 fclose(fp);
3446 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003447}
3448
3449static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003450imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 char *name;
3453 char *pathname;
3454 PyObject * ret;
3455 if (!PyArg_ParseTuple(args, "ses:load_package",
3456 &name, Py_FileSystemDefaultEncoding, &pathname))
3457 return NULL;
3458 ret = load_package(name, pathname);
3459 PyMem_Free(pathname);
3460 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003461}
3462
3463static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003464imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 char *name;
3467 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3468 return NULL;
3469 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003470}
3471
Christian Heimes13a7a212008-01-07 17:13:09 +00003472static PyObject *
3473imp_reload(PyObject *self, PyObject *v)
3474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003476}
3477
3478PyDoc_STRVAR(doc_reload,
3479"reload(module) -> module\n\
3480\n\
3481Reload the module. The module must have been successfully imported before.");
3482
Barry Warsaw28a691b2010-04-17 00:19:56 +00003483static PyObject *
3484imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003489 PyObject *pathbytes;
3490 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003491 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003495 args, kws, "O&|O", kwlist,
3496 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003498
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003499 if (debug_override != NULL &&
3500 (debug = PyObject_IsTrue(debug_override)) < 0) {
3501 Py_DECREF(pathbytes);
3502 return NULL;
3503 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003504
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003505 cpathname = make_compiled_pathname(
3506 PyBytes_AS_STRING(pathbytes),
3507 buf, MAXPATHLEN+1, debug);
3508 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 if (cpathname == NULL) {
3511 PyErr_Format(PyExc_SystemError, "path buffer too short");
3512 return NULL;
3513 }
Victor Stinner88bd8912010-10-15 22:46:07 +00003514 return PyUnicode_DecodeFSDefault(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003515}
3516
3517PyDoc_STRVAR(doc_cache_from_source,
3518"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3519\n\
3520The .py file does not need to exist; this simply returns the path to the\n\
3521.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3522will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3523\n\
3524If debug_override is not None, then it must be a boolean and is taken as\n\
3525the value of __debug__ instead.");
3526
3527static PyObject *
3528imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 char *pathname;
3533 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 if (!PyArg_ParseTupleAndKeywords(
3536 args, kws, "es", kwlist,
3537 Py_FileSystemDefaultEncoding, &pathname))
3538 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 if (make_source_pathname(pathname, buf) == NULL) {
3541 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3542 pathname);
3543 PyMem_Free(pathname);
3544 return NULL;
3545 }
3546 PyMem_Free(pathname);
3547 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003548}
3549
3550PyDoc_STRVAR(doc_source_from_cache,
3551"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3552\n\
3553The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3554the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3555does not conform to PEP 3147 format, ValueError will be raised.");
3556
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003557/* Doc strings */
3558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003559PyDoc_STRVAR(doc_imp,
3560"This module provides the components needed to build your own\n\
3561__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563PyDoc_STRVAR(doc_find_module,
3564"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003565Search for a module. If path is omitted or None, search for a\n\
3566built-in, frozen or special module and continue search in sys.path.\n\
3567The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003568package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003570PyDoc_STRVAR(doc_load_module,
3571"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003572Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003573The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003575PyDoc_STRVAR(doc_get_magic,
3576"get_magic() -> string\n\
3577Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003578
Barry Warsaw28a691b2010-04-17 00:19:56 +00003579PyDoc_STRVAR(doc_get_tag,
3580"get_tag() -> string\n\
3581Return the magic tag for .pyc or .pyo files.");
3582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003583PyDoc_STRVAR(doc_get_suffixes,
3584"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003585Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003586that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003587
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003588PyDoc_STRVAR(doc_new_module,
3589"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003590Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003591The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003593PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003594"lock_held() -> boolean\n\
3595Return True if the import lock is currently held, else False.\n\
3596On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003597
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003598PyDoc_STRVAR(doc_acquire_lock,
3599"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003600Acquires the interpreter's import lock for the current thread.\n\
3601This lock should be used by import hooks to ensure thread-safety\n\
3602when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003603On platforms without threads, this function does nothing.");
3604
3605PyDoc_STRVAR(doc_release_lock,
3606"release_lock() -> None\n\
3607Release the interpreter's import lock.\n\
3608On platforms without threads, this function does nothing.");
3609
Guido van Rossum79f25d91997-04-29 20:08:16 +00003610static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3612 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3613 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3614 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3615 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3616 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3617 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3618 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3619 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3620 {"reload", imp_reload, METH_O, doc_reload},
3621 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3622 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3623 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3624 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3625 /* The rest are obsolete */
3626 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3627 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3628 {"init_builtin", imp_init_builtin, METH_VARARGS},
3629 {"init_frozen", imp_init_frozen, METH_VARARGS},
3630 {"is_builtin", imp_is_builtin, METH_VARARGS},
3631 {"is_frozen", imp_is_frozen, METH_VARARGS},
3632 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003633#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003635#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 {"load_package", imp_load_package, METH_VARARGS},
3637 {"load_source", imp_load_source, METH_VARARGS},
3638 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003639};
3640
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003641static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003642setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 PyObject *v;
3645 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 v = PyLong_FromLong((long)value);
3648 err = PyDict_SetItemString(d, name, v);
3649 Py_XDECREF(v);
3650 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003651}
3652
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003653typedef struct {
3654 PyObject_HEAD
3655} NullImporter;
3656
3657static int
3658NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3659{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003660#ifndef MS_WINDOWS
3661 PyObject *path;
3662 struct stat statbuf;
3663 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3666 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003667
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003668 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3669 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003671
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003672 if (PyBytes_GET_SIZE(path) == 0) {
3673 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 PyErr_SetString(PyExc_ImportError, "empty pathname");
3675 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003677
3678 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3679 Py_DECREF(path);
3680 if (rv == 0) {
3681 /* it exists */
3682 if (S_ISDIR(statbuf.st_mode)) {
3683 /* it's a directory */
3684 PyErr_SetString(PyExc_ImportError, "existing directory");
3685 return -1;
3686 }
3687 }
3688#else /* MS_WINDOWS */
3689 PyObject *pathobj;
3690 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003691 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003692
3693 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3694 return -1;
3695
3696 if (!PyArg_ParseTuple(args, "U:NullImporter",
3697 &pathobj))
3698 return -1;
3699
3700 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3701 PyErr_SetString(PyExc_ImportError, "empty pathname");
3702 return -1;
3703 }
3704
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003705 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003706 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003707 return -1;
3708 /* see issue1293 and issue3677:
3709 * stat() on Windows doesn't recognise paths like
3710 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3711 */
3712 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003713 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003714 if (rv != INVALID_FILE_ATTRIBUTES) {
3715 /* it exists */
3716 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3717 /* it's a directory */
3718 PyErr_SetString(PyExc_ImportError, "existing directory");
3719 return -1;
3720 }
3721 }
3722#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003724}
3725
3726static PyObject *
3727NullImporter_find_module(NullImporter *self, PyObject *args)
3728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003730}
3731
3732static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3734 "Always return None"
3735 },
3736 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003737};
3738
3739
Christian Heimes9cd17752007-11-18 19:35:23 +00003740PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 PyVarObject_HEAD_INIT(NULL, 0)
3742 "imp.NullImporter", /*tp_name*/
3743 sizeof(NullImporter), /*tp_basicsize*/
3744 0, /*tp_itemsize*/
3745 0, /*tp_dealloc*/
3746 0, /*tp_print*/
3747 0, /*tp_getattr*/
3748 0, /*tp_setattr*/
3749 0, /*tp_reserved*/
3750 0, /*tp_repr*/
3751 0, /*tp_as_number*/
3752 0, /*tp_as_sequence*/
3753 0, /*tp_as_mapping*/
3754 0, /*tp_hash */
3755 0, /*tp_call*/
3756 0, /*tp_str*/
3757 0, /*tp_getattro*/
3758 0, /*tp_setattro*/
3759 0, /*tp_as_buffer*/
3760 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3761 "Null importer object", /* tp_doc */
3762 0, /* tp_traverse */
3763 0, /* tp_clear */
3764 0, /* tp_richcompare */
3765 0, /* tp_weaklistoffset */
3766 0, /* tp_iter */
3767 0, /* tp_iternext */
3768 NullImporter_methods, /* tp_methods */
3769 0, /* tp_members */
3770 0, /* tp_getset */
3771 0, /* tp_base */
3772 0, /* tp_dict */
3773 0, /* tp_descr_get */
3774 0, /* tp_descr_set */
3775 0, /* tp_dictoffset */
3776 (initproc)NullImporter_init, /* tp_init */
3777 0, /* tp_alloc */
3778 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003779};
3780
Martin v. Löwis1a214512008-06-11 05:26:20 +00003781static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 PyModuleDef_HEAD_INIT,
3783 "imp",
3784 doc_imp,
3785 0,
3786 imp_methods,
3787 NULL,
3788 NULL,
3789 NULL,
3790 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003791};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003792
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003793PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003794PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 if (PyType_Ready(&PyNullImporter_Type) < 0)
3799 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 m = PyModule_Create(&impmodule);
3802 if (m == NULL)
3803 goto failure;
3804 d = PyModule_GetDict(m);
3805 if (d == NULL)
3806 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3809 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3810 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3811 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3812 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3813 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3814 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3815 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3816 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3817 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 Py_INCREF(&PyNullImporter_Type);
3820 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3821 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003822 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 Py_XDECREF(m);
3824 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003825}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003826
3827
Guido van Rossumb18618d2000-05-03 23:44:39 +00003828/* API for embedding applications that want to add their own entries
3829 to the table of built-in modules. This should normally be called
3830 *before* Py_Initialize(). When the table resize fails, -1 is
3831 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003832
3833 After a similar function by Just van Rossum. */
3834
3835int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003836PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 static struct _inittab *our_copy = NULL;
3839 struct _inittab *p;
3840 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 /* Count the number of entries in both tables */
3843 for (n = 0; newtab[n].name != NULL; n++)
3844 ;
3845 if (n == 0)
3846 return 0; /* Nothing to do */
3847 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3848 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 /* Allocate new memory for the combined table */
3851 p = our_copy;
3852 PyMem_RESIZE(p, struct _inittab, i+n+1);
3853 if (p == NULL)
3854 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 /* Copy the tables into the new memory */
3857 if (our_copy != PyImport_Inittab)
3858 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3859 PyImport_Inittab = our_copy = p;
3860 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003863}
3864
3865/* Shorthand to add a single entry given a name and a function */
3866
3867int
Brett Cannona826f322009-04-02 03:41:46 +00003868PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 newtab[0].name = (char *)name;
3875 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003878}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003879
3880#ifdef __cplusplus
3881}
3882#endif