blob: 67c4f70adb5085de0e17729156ba7a138d778f20 [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 */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000011#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000012#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013
Guido van Rossum55a83382000-09-20 20:31:38 +000014#ifdef HAVE_FCNTL_H
15#include <fcntl.h>
16#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000017#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000018extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000020
Christian Heimesd3eb5a152008-02-24 00:38:49 +000021#ifdef MS_WINDOWS
22/* for stat.st_mode */
23typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000024/* for _mkdir */
25#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000026#endif
27
Guido van Rossum21d335e1993-10-15 13:01:11 +000028
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000029/* Magic word to reject .pyc files generated by other Python versions.
30 It should change for each incompatible change to the bytecode.
31
32 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000033 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000034 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000035
Guido van Rossum45aecf42006-03-15 04:58:47 +000036 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000037 -U interpeter flag will cause MAGIC+1 being used. They have been
38 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000040 There were a variety of old schemes for setting the magic number.
41 The current working scheme is to increment the previous value by
42 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000043
Barry Warsaw28a691b2010-04-17 00:19:56 +000044 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
45 number also includes a new "magic tag", i.e. a human readable string used
46 to represent the magic number in __pycache__ directories. When you change
47 the magic number, you must also set a new unique magic tag. Generally this
48 can be named after the Python major version of the magic number bump, but
49 it can really be anything, as long as it's different than anything else
50 that's come before. The tags are included in the following table, starting
51 with Python 3.2a0.
52
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000053 Known values:
54 Python 1.5: 20121
55 Python 1.5.1: 20121
56 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000058 Python 2.0: 50823
59 Python 2.0.1: 50823
60 Python 2.1: 60202
61 Python 2.1.1: 60202
62 Python 2.1.2: 60202
63 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000064 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000065 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000066 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000067 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000068 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000069 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000070 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000071 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000072 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000073 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
75 Python 2.5b3: 62111 (fix wrong code: x += yield)
76 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000078 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000079 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000080 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000081 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 3010 (removed UNARY_CONVERT)
83 3020 (added BUILD_SET)
84 3030 (added keyword-only parameters)
85 3040 (added signature annotations)
86 3050 (print becomes a function)
87 3060 (PEP 3115 metaclass syntax)
88 3061 (string literals become unicode)
89 3071 (PEP 3109 raise changes)
90 3081 (PEP 3137 make __file__ and __name__ unicode)
91 3091 (kill str8 interning)
92 3101 (merge from 2.6a0, see 62151)
93 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000094 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
95 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
96 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000100 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000102 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
103 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000104 Python 3.2a2 3180 (add DELETE_DEREF)
Tim Peters36515e22001-11-18 04:06:29 +0000105*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000106
Nick Coghlancd419ab2010-09-11 00:39:25 +0000107/* MAGIC must change whenever the bytecode emitted by the compiler may no
108 longer be understood by older implementations of the eval loop (usually
109 due to the addition of new opcodes)
110 TAG must change for each major Python release. The magic number will take
111 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112*/
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000113#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114#define TAG "cpython-32"
115#define CACHEDIR "__pycache__"
116/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000117static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000119
Victor Stinner49d3f252010-10-17 01:24:53 +0000120/* See _PyImport_FixupExtensionUnicode() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000122
Guido van Rossum771c6c81997-10-31 18:37:24 +0000123/* This table is defined in config.c: */
124extern struct _inittab _PyImport_Inittab[];
125
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000126/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000127extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000128
Guido van Rossum771c6c81997-10-31 18:37:24 +0000129struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000130
Guido van Rossumed1170e1999-12-20 21:23:41 +0000131/* these tables define the module suffixes that Python recognizes */
132struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000133
Guido van Rossumed1170e1999-12-20 21:23:41 +0000134static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000136#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 {".pyc", "rb", PY_COMPILED},
140 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000141};
142
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000144/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145
146void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000147_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 const struct filedescr *scan;
150 struct filedescr *filetab;
151 int countD = 0;
152 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 /* prepare _PyImport_Filetab: copy entries from
155 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
156 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000157#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
159 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
162 ++countS;
163 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
164 if (filetab == NULL)
165 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000166#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 memcpy(filetab, _PyImport_DynLoadFiletab,
168 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000169#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 memcpy(filetab + countD, _PyImport_StandardFiletab,
171 countS * sizeof(struct filedescr));
172 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (Py_OptimizeFlag) {
177 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
178 for (; filetab->suffix != NULL; filetab++) {
179 if (strcmp(filetab->suffix, ".pyc") == 0)
180 filetab->suffix = ".pyo";
181 }
182 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185void
Just van Rossum52e14d62002-12-30 22:08:05 +0000186_PyImportHooks_Init(void)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyObject *v, *path_hooks = NULL, *zimpimport;
189 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* adding sys.path_hooks and sys.path_importer_cache, setting up
192 zipimport */
193 if (PyType_Ready(&PyNullImporter_Type) < 0)
194 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (Py_VerboseFlag)
197 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 v = PyList_New(0);
200 if (v == NULL)
201 goto error;
202 err = PySys_SetObject("meta_path", v);
203 Py_DECREF(v);
204 if (err)
205 goto error;
206 v = PyDict_New();
207 if (v == NULL)
208 goto error;
209 err = PySys_SetObject("path_importer_cache", v);
210 Py_DECREF(v);
211 if (err)
212 goto error;
213 path_hooks = PyList_New(0);
214 if (path_hooks == NULL)
215 goto error;
216 err = PySys_SetObject("path_hooks", path_hooks);
217 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000218 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 PyErr_Print();
220 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
221 "path_importer_cache, or NullImporter failed"
222 );
223 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 zimpimport = PyImport_ImportModule("zipimport");
226 if (zimpimport == NULL) {
227 PyErr_Clear(); /* No zip import module -- okay */
228 if (Py_VerboseFlag)
229 PySys_WriteStderr("# can't import zipimport\n");
230 }
231 else {
232 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
233 "zipimporter");
234 Py_DECREF(zimpimport);
235 if (zipimporter == NULL) {
236 PyErr_Clear(); /* No zipimporter object -- okay */
237 if (Py_VerboseFlag)
238 PySys_WriteStderr(
239 "# can't import zipimport.zipimporter\n");
240 }
241 else {
242 /* sys.path_hooks.append(zipimporter) */
243 err = PyList_Append(path_hooks, zipimporter);
244 Py_DECREF(zipimporter);
245 if (err)
246 goto error;
247 if (Py_VerboseFlag)
248 PySys_WriteStderr(
249 "# installed zipimport hook\n");
250 }
251 }
252 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000253}
254
255void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000256_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 Py_XDECREF(extensions);
259 extensions = NULL;
260 PyMem_DEL(_PyImport_Filetab);
261 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000262}
263
264
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000265/* Locking primitives to prevent parallel imports of the same module
266 in different threads to return with a partially loaded module.
267 These calls are serialized by the global interpreter lock. */
268
269#ifdef WITH_THREAD
270
Guido van Rossum49b56061998-10-01 20:42:43 +0000271#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272
Guido van Rossum65d5b571998-12-21 19:32:43 +0000273static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000274static long import_lock_thread = -1;
275static int import_lock_level = 0;
276
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000277void
278_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 long me = PyThread_get_thread_ident();
281 if (me == -1)
282 return; /* Too bad */
283 if (import_lock == NULL) {
284 import_lock = PyThread_allocate_lock();
285 if (import_lock == NULL)
286 return; /* Nothing much we can do. */
287 }
288 if (import_lock_thread == me) {
289 import_lock_level++;
290 return;
291 }
292 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
293 {
294 PyThreadState *tstate = PyEval_SaveThread();
295 PyThread_acquire_lock(import_lock, 1);
296 PyEval_RestoreThread(tstate);
297 }
298 import_lock_thread = me;
299 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000300}
301
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000302int
303_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 long me = PyThread_get_thread_ident();
306 if (me == -1 || import_lock == NULL)
307 return 0; /* Too bad */
308 if (import_lock_thread != me)
309 return -1;
310 import_lock_level--;
311 if (import_lock_level == 0) {
312 import_lock_thread = -1;
313 PyThread_release_lock(import_lock);
314 }
315 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000316}
317
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000318/* This function is called from PyOS_AfterFork to ensure that newly
319 created child processes do not share locks with the parent.
320 We now acquire the import lock around fork() calls but on some platforms
321 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000322
323void
324_PyImport_ReInitLock(void)
325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (import_lock != NULL)
327 import_lock = PyThread_allocate_lock();
328 import_lock_thread = -1;
329 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000330}
331
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000332#endif
333
Tim Peters69232342001-08-30 05:16:13 +0000334static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000335imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000336{
Tim Peters69232342001-08-30 05:16:13 +0000337#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000339#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000341#endif
342}
343
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000344static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000345imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000346{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000347#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000349#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 Py_INCREF(Py_None);
351 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000352}
353
354static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000355imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000356{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000357#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (_PyImport_ReleaseLock() < 0) {
359 PyErr_SetString(PyExc_RuntimeError,
360 "not holding the import lock");
361 return NULL;
362 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000363#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 Py_INCREF(Py_None);
365 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000366}
367
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368static void
369imp_modules_reloading_clear(void)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyInterpreterState *interp = PyThreadState_Get()->interp;
372 if (interp->modules_reloading != NULL)
373 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000374}
375
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376/* Helper for sys */
377
378PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000379PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyInterpreterState *interp = PyThreadState_GET()->interp;
382 if (interp->modules == NULL)
383 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
384 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385}
386
Guido van Rossum3f5da241990-12-20 15:06:42 +0000387
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000388/* List of names to clear in sys */
389static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 "path", "argv", "ps1", "ps2",
391 "last_type", "last_value", "last_traceback",
392 "path_hooks", "path_importer_cache", "meta_path",
393 /* misc stuff */
394 "flags", "float_info",
395 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000396};
397
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000398static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 "stdin", "__stdin__",
400 "stdout", "__stdout__",
401 "stderr", "__stderr__",
402 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000403};
404
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000406/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000407
Guido van Rossum3f5da241990-12-20 15:06:42 +0000408void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_ssize_t pos, ndone;
412 char *name;
413 PyObject *key, *value, *dict;
414 PyInterpreterState *interp = PyThreadState_GET()->interp;
415 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (modules == NULL)
418 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* Delete some special variables first. These are common
421 places where user values hide and people complain when their
422 destructors fail. Since the modules containing them are
423 deleted *last* of all, they would come too late in the normal
424 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 value = PyDict_GetItemString(modules, "builtins");
427 if (value != NULL && PyModule_Check(value)) {
428 dict = PyModule_GetDict(value);
429 if (Py_VerboseFlag)
430 PySys_WriteStderr("# clear builtins._\n");
431 PyDict_SetItemString(dict, "_", Py_None);
432 }
433 value = PyDict_GetItemString(modules, "sys");
434 if (value != NULL && PyModule_Check(value)) {
435 char **p;
436 PyObject *v;
437 dict = PyModule_GetDict(value);
438 for (p = sys_deletes; *p != NULL; p++) {
439 if (Py_VerboseFlag)
440 PySys_WriteStderr("# clear sys.%s\n", *p);
441 PyDict_SetItemString(dict, *p, Py_None);
442 }
443 for (p = sys_files; *p != NULL; p+=2) {
444 if (Py_VerboseFlag)
445 PySys_WriteStderr("# restore sys.%s\n", *p);
446 v = PyDict_GetItemString(dict, *(p+1));
447 if (v == NULL)
448 v = Py_None;
449 PyDict_SetItemString(dict, *p, v);
450 }
451 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* First, delete __main__ */
454 value = PyDict_GetItemString(modules, "__main__");
455 if (value != NULL && PyModule_Check(value)) {
456 if (Py_VerboseFlag)
457 PySys_WriteStderr("# cleanup __main__\n");
458 _PyModule_Clear(value);
459 PyDict_SetItemString(modules, "__main__", Py_None);
460 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* The special treatment of "builtins" here is because even
463 when it's not referenced as a module, its dictionary is
464 referenced by almost every module's __builtins__. Since
465 deleting a module clears its dictionary (even if there are
466 references left to it), we need to delete the "builtins"
467 module last. Likewise, we don't delete sys until the very
468 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 Also note that we 'delete' modules by replacing their entry
471 in the modules dict with None, rather than really deleting
472 them; this avoids a rehash of the modules dictionary and
473 also marks them as "non existent" so they won't be
474 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Next, repeatedly delete modules with a reference count of
477 one (skipping builtins and sys) and delete them */
478 do {
479 ndone = 0;
480 pos = 0;
481 while (PyDict_Next(modules, &pos, &key, &value)) {
482 if (value->ob_refcnt != 1)
483 continue;
484 if (PyUnicode_Check(key) && PyModule_Check(value)) {
485 name = _PyUnicode_AsString(key);
486 if (strcmp(name, "builtins") == 0)
487 continue;
488 if (strcmp(name, "sys") == 0)
489 continue;
490 if (Py_VerboseFlag)
491 PySys_WriteStderr(
492 "# cleanup[1] %s\n", name);
493 _PyModule_Clear(value);
494 PyDict_SetItem(modules, key, Py_None);
495 ndone++;
496 }
497 }
498 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Next, delete all modules (still skipping builtins and sys) */
501 pos = 0;
502 while (PyDict_Next(modules, &pos, &key, &value)) {
503 if (PyUnicode_Check(key) && PyModule_Check(value)) {
504 name = _PyUnicode_AsString(key);
505 if (strcmp(name, "builtins") == 0)
506 continue;
507 if (strcmp(name, "sys") == 0)
508 continue;
509 if (Py_VerboseFlag)
510 PySys_WriteStderr("# cleanup[2] %s\n", name);
511 _PyModule_Clear(value);
512 PyDict_SetItem(modules, key, Py_None);
513 }
514 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Next, delete sys and builtins (in that order) */
517 value = PyDict_GetItemString(modules, "sys");
518 if (value != NULL && PyModule_Check(value)) {
519 if (Py_VerboseFlag)
520 PySys_WriteStderr("# cleanup sys\n");
521 _PyModule_Clear(value);
522 PyDict_SetItemString(modules, "sys", Py_None);
523 }
524 value = PyDict_GetItemString(modules, "builtins");
525 if (value != NULL && PyModule_Check(value)) {
526 if (Py_VerboseFlag)
527 PySys_WriteStderr("# cleanup builtins\n");
528 _PyModule_Clear(value);
529 PyDict_SetItemString(modules, "builtins", Py_None);
530 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 /* Finally, clear and delete the modules directory */
533 PyDict_Clear(modules);
534 interp->modules = NULL;
535 Py_DECREF(modules);
536 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000537}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000538
539
Barry Warsaw28a691b2010-04-17 00:19:56 +0000540/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000541
542long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000543PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000546}
547
548
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549const char *
550PyImport_GetMagicTag(void)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000553}
554
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555/* Magic for extension modules (built-in as well as dynamically
556 loaded). To prevent initializing an extension module more than
557 once, we keep a static dictionary 'extensions' keyed by module name
558 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000559 modules), containing these modules. A copy of the module's
Victor Stinner49d3f252010-10-17 01:24:53 +0000560 dictionary is stored by calling _PyImport_FixupExtensionUnicode()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561 immediately after the module initialization function succeeds. A
562 copy can be retrieved from there by calling
Victor Stinner49d3f252010-10-17 01:24:53 +0000563 _PyImport_FindExtensionUnicode().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000564
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000565 Modules which do support multiple initialization set their m_size
566 field to a non-negative number (indicating the size of the
567 module-specific state). They are still recorded in the extensions
568 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000569*/
570
571int
Victor Stinner49d3f252010-10-17 01:24:53 +0000572_PyImport_FixupExtensionUnicode(PyObject *mod, char *name, PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyObject *modules, *dict;
575 struct PyModuleDef *def;
576 if (extensions == NULL) {
577 extensions = PyDict_New();
578 if (extensions == NULL)
579 return -1;
580 }
581 if (mod == NULL || !PyModule_Check(mod)) {
582 PyErr_BadInternalCall();
583 return -1;
584 }
585 def = PyModule_GetDef(mod);
586 if (!def) {
587 PyErr_BadInternalCall();
588 return -1;
589 }
590 modules = PyImport_GetModuleDict();
591 if (PyDict_SetItemString(modules, name, mod) < 0)
592 return -1;
593 if (_PyState_AddModule(mod, def) < 0) {
594 PyDict_DelItemString(modules, name);
595 return -1;
596 }
597 if (def->m_size == -1) {
598 if (def->m_base.m_copy) {
599 /* Somebody already imported the module,
600 likely under a different name.
601 XXX this should really not happen. */
602 Py_DECREF(def->m_base.m_copy);
603 def->m_base.m_copy = NULL;
604 }
605 dict = PyModule_GetDict(mod);
606 if (dict == NULL)
607 return -1;
608 def->m_base.m_copy = PyDict_Copy(dict);
609 if (def->m_base.m_copy == NULL)
610 return -1;
611 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000612 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614}
615
Victor Stinner49d3f252010-10-17 01:24:53 +0000616int
617_PyImport_FixupBuiltin(PyObject *mod, char *name)
618{
619 int res;
620 PyObject *filename;
621 filename = PyUnicode_FromString(name);
622 if (filename == NULL)
623 return -1;
624 res = _PyImport_FixupExtensionUnicode(mod, name, filename);
625 Py_DECREF(filename);
626 return res;
627}
628
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629PyObject *
Victor Stinner49d3f252010-10-17 01:24:53 +0000630_PyImport_FindExtensionUnicode(char *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject *mod, *mdict;
633 PyModuleDef* def;
634 if (extensions == NULL)
635 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000636 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (def == NULL)
638 return NULL;
639 if (def->m_size == -1) {
640 /* Module does not support repeated initialization */
641 if (def->m_base.m_copy == NULL)
642 return NULL;
643 mod = PyImport_AddModule(name);
644 if (mod == NULL)
645 return NULL;
646 mdict = PyModule_GetDict(mod);
647 if (mdict == NULL)
648 return NULL;
649 if (PyDict_Update(mdict, def->m_base.m_copy))
650 return NULL;
651 }
652 else {
653 if (def->m_base.m_init == NULL)
654 return NULL;
655 mod = def->m_base.m_init();
656 if (mod == NULL)
657 return NULL;
658 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
659 Py_DECREF(mod);
660 }
661 if (_PyState_AddModule(mod, def) < 0) {
662 PyDict_DelItemString(PyImport_GetModuleDict(), name);
663 Py_DECREF(mod);
664 return NULL;
665 }
666 if (Py_VerboseFlag)
Victor Stinner49d3f252010-10-17 01:24:53 +0000667 PySys_FormatStderr("import %s # previously loaded (%U)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 name, filename);
669 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000670
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000671}
672
Victor Stinner49d3f252010-10-17 01:24:53 +0000673PyObject *
674_PyImport_FindBuiltin(char *name)
675{
676 PyObject *res, *filename;
677 filename = PyUnicode_FromString(name);
678 if (filename == NULL)
679 return NULL;
680 res = _PyImport_FindExtensionUnicode(name, filename);
681 Py_DECREF(filename);
682 return res;
683}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684
685/* Get the module object corresponding to a module name.
686 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000687 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000688 Because the former action is most common, THIS DOES NOT RETURN A
689 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690
Guido van Rossum79f25d91997-04-29 20:08:16 +0000691PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000692PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyObject *modules = PyImport_GetModuleDict();
695 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
698 PyModule_Check(m))
699 return m;
700 m = PyModule_New(name);
701 if (m == NULL)
702 return NULL;
703 if (PyDict_SetItemString(modules, name, m) != 0) {
704 Py_DECREF(m);
705 return NULL;
706 }
707 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710}
711
Tim Peters1cd70172004-08-02 03:52:12 +0000712/* Remove name from sys.modules, if it's there. */
713static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000714remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyObject *modules = PyImport_GetModuleDict();
717 if (PyDict_GetItemString(modules, name) == NULL)
718 return;
719 if (PyDict_DelItemString(modules, name) < 0)
720 Py_FatalError("import: deleting existing key in"
721 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000722}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000723
Barry Warsaw28a691b2010-04-17 00:19:56 +0000724static PyObject * get_sourcefile(char *file);
725static char *make_source_pathname(char *pathname, char *buf);
726static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000728
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000729/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000730 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
731 * removed from sys.modules, to avoid leaving damaged module objects
732 * in sys.modules. The caller may wish to restore the original
733 * module object (if any) in this case; PyImport_ReloadModule is an
734 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000735 *
736 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
737 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000738 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000739PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000740PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 return PyImport_ExecCodeModuleWithPathnames(
743 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000744}
745
746PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000747PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return PyImport_ExecCodeModuleWithPathnames(
750 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000751}
752
753PyObject *
754PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyObject *modules = PyImport_GetModuleDict();
758 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 m = PyImport_AddModule(name);
761 if (m == NULL)
762 return NULL;
763 /* If the module is being reloaded, we get the old module back
764 and re-use its dict to exec the new code. */
765 d = PyModule_GetDict(m);
766 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
767 if (PyDict_SetItemString(d, "__builtins__",
768 PyEval_GetBuiltins()) != 0)
769 goto error;
770 }
771 /* Remember the filename as the __file__ attribute */
772 v = NULL;
773 if (pathname != NULL) {
774 v = get_sourcefile(pathname);
775 if (v == NULL)
776 PyErr_Clear();
777 }
778 if (v == NULL) {
779 v = ((PyCodeObject *)co)->co_filename;
780 Py_INCREF(v);
781 }
782 if (PyDict_SetItemString(d, "__file__", v) != 0)
783 PyErr_Clear(); /* Not important enough to report */
784 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 /* Remember the pyc path name as the __cached__ attribute. */
787 if (cpathname == NULL) {
788 v = Py_None;
789 Py_INCREF(v);
790 }
791 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
792 PyErr_Clear(); /* Not important enough to report */
793 v = Py_None;
794 Py_INCREF(v);
795 }
796 if (PyDict_SetItemString(d, "__cached__", v) != 0)
797 PyErr_Clear(); /* Not important enough to report */
798 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
801 if (v == NULL)
802 goto error;
803 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
806 PyErr_Format(PyExc_ImportError,
807 "Loaded module %.200s not found in sys.modules",
808 name);
809 return NULL;
810 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000815
816 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 remove_module(name);
818 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000819}
820
821
Barry Warsaw28a691b2010-04-17 00:19:56 +0000822/* Like strrchr(string, '/') but searches for the rightmost of either SEP
823 or ALTSEP, if the latter is defined.
824*/
825static char *
826rightmost_sep(char *s)
827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 char *found, c;
829 for (found = NULL; (c = *s); s++) {
830 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000831#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000833#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 )
835 {
836 found = s;
837 }
838 }
839 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000840}
841
842
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000843/* Given a pathname for a Python source file, fill a buffer with the
844 pathname for the corresponding compiled file. Return the pathname
845 for the compiled file, or NULL if there's no space in the buffer.
846 Doesn't set an exception. */
847
848static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000849make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* foo.py -> __pycache__/foo.<tag>.pyc */
852 size_t len = strlen(pathname);
853 size_t i, save;
854 char *pos;
855 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 /* Sanity check that the buffer has roughly enough space to hold what
858 will eventually be the full path to the compiled file. The 5 extra
859 bytes include the slash afer __pycache__, the two extra dots, the
860 extra trailing character ('c' or 'o') and null. This isn't exact
861 because the contents of the buffer can affect how many actual
862 characters of the string get into the buffer. We'll do a final
863 sanity check before writing the extension to ensure we do not
864 overflow the buffer.
865 */
866 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
867 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Find the last path separator and copy everything from the start of
870 the source string up to and including the separator.
871 */
872 if ((pos = rightmost_sep(pathname)) == NULL) {
873 i = 0;
874 }
875 else {
876 sep = *pos;
877 i = pos - pathname + 1;
878 strncpy(buf, pathname, i);
879 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 save = i;
882 buf[i++] = '\0';
883 /* Add __pycache__/ */
884 strcat(buf, CACHEDIR);
885 i += strlen(CACHEDIR) - 1;
886 buf[i++] = sep;
887 buf[i++] = '\0';
888 /* Add the base filename, but remove the .py or .pyw extension, since
889 the tag name must go before the extension.
890 */
891 strcat(buf, pathname + save);
892 if ((pos = strrchr(buf, '.')) != NULL)
893 *++pos = '\0';
894 strcat(buf, pyc_tag);
895 /* The length test above assumes that we're only adding one character
896 to the end of what would normally be the extension. What if there
897 is no extension, or the string ends in '.' or '.p', and otherwise
898 fills the buffer? By appending 4 more characters onto the string
899 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 As a simple example, let's say buflen=32 and the input string is
902 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 which is false and so the name mangling would continue. This would
907 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
912 We can even handle an input string of say 'xxxxx' above because
913 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
914 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 which is 32 characters including the nul, and thus fits in the
919 buffer. However, an input string of 'xxxxxx' would yield a result
920 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 which is 33 characters long (including the nul), thus overflowing
925 the buffer, even though the first test would fail, i.e.: the input
926 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 The reason the first test fails but we still overflow the buffer is
929 that the test above only expects to add one extra character to be
930 added to the extension, and here we're adding three (pyc). We
931 don't add the first dot, so that reclaims one of expected
932 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
933 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 The best we can do is ensure that we still have enough room in the
936 target buffer before we write the extension. Because it's always
937 only the extension that can cause the overflow, and never the other
938 path bytes we've written, it's sufficient to just do one more test
939 here. Still, the assertion that follows can't hurt.
940 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000941#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000943#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (strlen(buf) + 5 > buflen)
945 return NULL;
946 strcat(buf, debug ? ".pyc" : ".pyo");
947 assert(strlen(buf) < buflen);
948 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000949}
950
951
Barry Warsaw28a691b2010-04-17 00:19:56 +0000952/* Given a pathname to a Python byte compiled file, return the path to the
953 source file, if the path matches the PEP 3147 format. This does not check
954 for any file existence, however, if the pyc file name does not match PEP
955 3147 style, NULL is returned. buf must be at least as big as pathname;
956 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957
Barry Warsaw28a691b2010-04-17 00:19:56 +0000958static char *
959make_source_pathname(char *pathname, char *buf)
960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* __pycache__/foo.<tag>.pyc -> foo.py */
962 size_t i, j;
963 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* Look back two slashes from the end. In between these two slashes
966 must be the string __pycache__ or this is not a PEP 3147 style
967 path. It's possible for there to be only one slash.
968 */
969 if ((right = rightmost_sep(pathname)) == NULL)
970 return NULL;
971 sep = *right;
972 *right = '\0';
973 left = rightmost_sep(pathname);
974 *right = sep;
975 if (left == NULL)
976 left = pathname;
977 else
978 left++;
979 if (right-left != strlen(CACHEDIR) ||
980 strncmp(left, CACHEDIR, right-left) != 0)
981 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 /* Now verify that the path component to the right of the last slash
984 has two dots in it.
985 */
986 if ((dot0 = strchr(right + 1, '.')) == NULL)
987 return NULL;
988 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
989 return NULL;
990 /* Too many dots? */
991 if (strchr(dot1 + 1, '.') != NULL)
992 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* This is a PEP 3147 path. Start by copying everything from the
995 start of pathname up to and including the leftmost slash. Then
996 copy the file's basename, removing the magic tag and adding a .py
997 suffix.
998 */
999 strncpy(buf, pathname, (i=left-pathname));
1000 strncpy(buf+i, right+1, (j=dot0-right));
1001 strcpy(buf+i+j, "py");
1002 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001003}
1004
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001005/* Given a pathname for a Python source file, its time of last
1006 modification, and a pathname for a compiled file, check whether the
1007 compiled file represents the same version of the source. If so,
1008 return a FILE pointer for the compiled file, positioned just after
1009 the header; if not, return NULL.
1010 Doesn't set an exception. */
1011
1012static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001013check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 FILE *fp;
1016 long magic;
1017 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 fp = fopen(cpathname, "rb");
1020 if (fp == NULL)
1021 return NULL;
1022 magic = PyMarshal_ReadLongFromFile(fp);
1023 if (magic != pyc_magic) {
1024 if (Py_VerboseFlag)
1025 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1026 fclose(fp);
1027 return NULL;
1028 }
1029 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1030 if (pyc_mtime != mtime) {
1031 if (Py_VerboseFlag)
1032 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1033 fclose(fp);
1034 return NULL;
1035 }
1036 if (Py_VerboseFlag)
1037 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1038 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001039}
1040
1041
1042/* Read a code object from a file and check it for validity */
1043
Guido van Rossum79f25d91997-04-29 20:08:16 +00001044static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001045read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 co = PyMarshal_ReadLastObjectFromFile(fp);
1050 if (co == NULL)
1051 return NULL;
1052 if (!PyCode_Check(co)) {
1053 PyErr_Format(PyExc_ImportError,
1054 "Non-code object in %.200s", cpathname);
1055 Py_DECREF(co);
1056 return NULL;
1057 }
1058 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001059}
1060
1061
1062/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001063 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001064
Guido van Rossum79f25d91997-04-29 20:08:16 +00001065static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001066load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 long magic;
1069 PyCodeObject *co;
1070 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 magic = PyMarshal_ReadLongFromFile(fp);
1073 if (magic != pyc_magic) {
1074 PyErr_Format(PyExc_ImportError,
1075 "Bad magic number in %.200s", cpathname);
1076 return NULL;
1077 }
1078 (void) PyMarshal_ReadLongFromFile(fp);
1079 co = read_compiled_module(cpathname, fp);
1080 if (co == NULL)
1081 return NULL;
1082 if (Py_VerboseFlag)
1083 PySys_WriteStderr("import %s # precompiled from %s\n",
1084 name, cpathname);
1085 m = PyImport_ExecCodeModuleWithPathnames(
1086 name, (PyObject *)co, cpathname, cpathname);
1087 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001090}
1091
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001092/* Parse a source file and return the corresponding code object */
1093
Guido van Rossum79f25d91997-04-29 20:08:16 +00001094static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001095parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyCodeObject *co = NULL;
1098 mod_ty mod;
1099 PyCompilerFlags flags;
1100 PyArena *arena = PyArena_New();
1101 if (arena == NULL)
1102 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 flags.cf_flags = 0;
1105 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1106 Py_file_input, 0, 0, &flags,
1107 NULL, arena);
1108 if (mod) {
1109 co = PyAST_Compile(mod, pathname, NULL, arena);
1110 }
1111 PyArena_Free(arena);
1112 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001113}
1114
1115
Guido van Rossum55a83382000-09-20 20:31:38 +00001116/* Helper to open a bytecode file for writing in exclusive mode */
1117
1118static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001119open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001120{
1121#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 /* Use O_EXCL to avoid a race condition when another process tries to
1123 write the same file. When that happens, our open() call fails,
1124 which is just fine (since it's only a cache).
1125 XXX If the file exists and is writable but the directory is not
1126 writable, the file will never be written. Oh well.
1127 */
1128 int fd;
1129 (void) unlink(filename);
1130 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001131#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001133#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001134#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001136#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 );
1140 if (fd < 0)
1141 return NULL;
1142 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001143#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 /* Best we can do -- on Windows this can't happen anyway */
1145 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001146#endif
1147}
1148
1149
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001150/* Write a compiled module to a file, placing the time of last
1151 modification of its source into the header.
1152 Errors are ignored, if a write error occurs an attempt is made to
1153 remove the file. */
1154
1155static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001156write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 FILE *fp;
1159 char *dirpath;
1160 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001161#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001163#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1165 mode_t dirmode = (srcstat->st_mode |
1166 S_IXUSR | S_IXGRP | S_IXOTH |
1167 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001168#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Ensure that the __pycache__ directory exists. */
1172 dirpath = rightmost_sep(cpathname);
1173 if (dirpath == NULL) {
1174 if (Py_VerboseFlag)
1175 PySys_WriteStderr(
1176 "# no %s path found %s\n",
1177 CACHEDIR, cpathname);
1178 return;
1179 }
1180 saved = *dirpath;
1181 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001182
1183#ifdef MS_WINDOWS
1184 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1185#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001187#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 *dirpath = saved;
1189 if (Py_VerboseFlag)
1190 PySys_WriteStderr(
1191 "# cannot create cache dir %s\n", cpathname);
1192 return;
1193 }
1194 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 fp = open_exclusive(cpathname, mode);
1197 if (fp == NULL) {
1198 if (Py_VerboseFlag)
1199 PySys_WriteStderr(
1200 "# can't create %s\n", cpathname);
1201 return;
1202 }
1203 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1204 /* First write a 0 for mtime */
1205 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1206 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1207 if (fflush(fp) != 0 || ferror(fp)) {
1208 if (Py_VerboseFlag)
1209 PySys_WriteStderr("# can't write %s\n", cpathname);
1210 /* Don't keep partial file */
1211 fclose(fp);
1212 (void) unlink(cpathname);
1213 return;
1214 }
1215 /* Now write the true mtime */
1216 fseek(fp, 4L, 0);
1217 assert(mtime < LONG_MAX);
1218 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1219 fflush(fp);
1220 fclose(fp);
1221 if (Py_VerboseFlag)
1222 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223}
1224
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001225static void
1226update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyObject *constants, *tmp;
1229 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (PyUnicode_Compare(co->co_filename, oldname))
1232 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 tmp = co->co_filename;
1235 co->co_filename = newname;
1236 Py_INCREF(co->co_filename);
1237 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 constants = co->co_consts;
1240 n = PyTuple_GET_SIZE(constants);
1241 for (i = 0; i < n; i++) {
1242 tmp = PyTuple_GET_ITEM(constants, i);
1243 if (PyCode_Check(tmp))
1244 update_code_filenames((PyCodeObject *)tmp,
1245 oldname, newname);
1246 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001247}
1248
1249static int
1250update_compiled_module(PyCodeObject *co, char *pathname)
1251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 newname = PyUnicode_DecodeFSDefault(pathname);
1255 if (newname == NULL)
1256 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (!PyUnicode_Compare(co->co_filename, newname)) {
1259 Py_DECREF(newname);
1260 return 0;
1261 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 oldname = co->co_filename;
1264 Py_INCREF(oldname);
1265 update_code_filenames(co, oldname, newname);
1266 Py_DECREF(oldname);
1267 Py_DECREF(newname);
1268 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001269}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001270
1271/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001272 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1273 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001274
Guido van Rossum79f25d91997-04-29 20:08:16 +00001275static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001276load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 struct stat st;
1279 FILE *fpc;
1280 char buf[MAXPATHLEN+1];
1281 char *cpathname;
1282 PyCodeObject *co;
1283 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (fstat(fileno(fp), &st) != 0) {
1286 PyErr_Format(PyExc_RuntimeError,
1287 "unable to get file status from '%s'",
1288 pathname);
1289 return NULL;
1290 }
Fred Drake4c82b232000-06-30 16:18:57 +00001291#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* Python's .pyc timestamp handling presumes that the timestamp fits
1293 in 4 bytes. This will be fine until sometime in the year 2038,
1294 when a 4-byte signed time_t will overflow.
1295 */
1296 if (st.st_mtime >> 32) {
1297 PyErr_SetString(PyExc_OverflowError,
1298 "modification time overflows a 4 byte field");
1299 return NULL;
1300 }
Fred Drake4c82b232000-06-30 16:18:57 +00001301#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 cpathname = make_compiled_pathname(
1303 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1304 if (cpathname != NULL &&
1305 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1306 co = read_compiled_module(cpathname, fpc);
1307 fclose(fpc);
1308 if (co == NULL)
1309 return NULL;
1310 if (update_compiled_module(co, pathname) < 0)
1311 return NULL;
1312 if (Py_VerboseFlag)
1313 PySys_WriteStderr("import %s # precompiled from %s\n",
1314 name, cpathname);
1315 pathname = cpathname;
1316 }
1317 else {
1318 co = parse_source_module(pathname, fp);
1319 if (co == NULL)
1320 return NULL;
1321 if (Py_VerboseFlag)
1322 PySys_WriteStderr("import %s # from %s\n",
1323 name, pathname);
1324 if (cpathname) {
1325 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1326 if (ro == NULL || !PyObject_IsTrue(ro))
1327 write_compiled_module(co, cpathname, &st);
1328 }
1329 }
1330 m = PyImport_ExecCodeModuleWithPathnames(
1331 name, (PyObject *)co, pathname, cpathname);
1332 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001335}
1336
Christian Heimes3b06e532008-01-07 20:12:44 +00001337/* Get source file -> unicode or None
1338 * Returns the path to the py file if available, else the given path
1339 */
1340static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001341get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 char py[MAXPATHLEN + 1];
1344 Py_ssize_t len;
1345 PyObject *u;
1346 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (!file || !*file) {
1349 Py_RETURN_NONE;
1350 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 len = strlen(file);
1353 /* match '*.py?' */
1354 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1355 return PyUnicode_DecodeFSDefault(file);
1356 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* Start by trying to turn PEP 3147 path into source path. If that
1359 * fails, just chop off the trailing character, i.e. legacy pyc path
1360 * to py.
1361 */
1362 if (make_source_pathname(file, py) == NULL) {
1363 strncpy(py, file, len-1);
1364 py[len-1] = '\0';
1365 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 if (stat(py, &statbuf) == 0 &&
1368 S_ISREG(statbuf.st_mode)) {
1369 u = PyUnicode_DecodeFSDefault(py);
1370 }
1371 else {
1372 u = PyUnicode_DecodeFSDefault(file);
1373 }
1374 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001375}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001376
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001377/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001378static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1379static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001381static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001382
1383/* Load a package and return its module object WITH INCREMENTED
1384 REFERENCE COUNT */
1385
1386static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001387load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *m, *d;
1390 PyObject *file = NULL;
1391 PyObject *path = NULL;
1392 int err;
1393 char buf[MAXPATHLEN+1];
1394 FILE *fp = NULL;
1395 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 m = PyImport_AddModule(name);
1398 if (m == NULL)
1399 return NULL;
1400 if (Py_VerboseFlag)
1401 PySys_WriteStderr("import %s # directory %s\n",
1402 name, pathname);
1403 d = PyModule_GetDict(m);
1404 file = get_sourcefile(pathname);
1405 if (file == NULL)
1406 goto error;
1407 path = Py_BuildValue("[O]", file);
1408 if (path == NULL)
1409 goto error;
1410 err = PyDict_SetItemString(d, "__file__", file);
1411 if (err == 0)
1412 err = PyDict_SetItemString(d, "__path__", path);
1413 if (err != 0)
1414 goto error;
1415 buf[0] = '\0';
1416 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1417 if (fdp == NULL) {
1418 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1419 PyErr_Clear();
1420 Py_INCREF(m);
1421 }
1422 else
1423 m = NULL;
1424 goto cleanup;
1425 }
1426 m = load_module(name, fp, buf, fdp->type, NULL);
1427 if (fp != NULL)
1428 fclose(fp);
1429 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001430
1431 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001433 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 Py_XDECREF(path);
1435 Py_XDECREF(file);
1436 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001437}
1438
1439
1440/* Helper to test for built-in module */
1441
1442static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001443is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 int i;
1446 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1447 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1448 if (PyImport_Inittab[i].initfunc == NULL)
1449 return -1;
1450 else
1451 return 1;
1452 }
1453 }
1454 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001455}
1456
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001457
Just van Rossum52e14d62002-12-30 22:08:05 +00001458/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1459 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001460 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001461 that can handle the path item. Return None if no hook could;
1462 this tells our caller it should fall back to the builtin
1463 import mechanism. Cache the result in path_importer_cache.
1464 Returns a borrowed reference. */
1465
1466static PyObject *
1467get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyObject *importer;
1471 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 /* These conditions are the caller's responsibility: */
1474 assert(PyList_Check(path_hooks));
1475 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 nhooks = PyList_Size(path_hooks);
1478 if (nhooks < 0)
1479 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 importer = PyDict_GetItem(path_importer_cache, p);
1482 if (importer != NULL)
1483 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 /* set path_importer_cache[p] to None to avoid recursion */
1486 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1487 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 for (j = 0; j < nhooks; j++) {
1490 PyObject *hook = PyList_GetItem(path_hooks, j);
1491 if (hook == NULL)
1492 return NULL;
1493 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1494 if (importer != NULL)
1495 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1498 return NULL;
1499 }
1500 PyErr_Clear();
1501 }
1502 if (importer == NULL) {
1503 importer = PyObject_CallFunctionObjArgs(
1504 (PyObject *)&PyNullImporter_Type, p, NULL
1505 );
1506 if (importer == NULL) {
1507 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1508 PyErr_Clear();
1509 return Py_None;
1510 }
1511 }
1512 }
1513 if (importer != NULL) {
1514 int err = PyDict_SetItem(path_importer_cache, p, importer);
1515 Py_DECREF(importer);
1516 if (err != 0)
1517 return NULL;
1518 }
1519 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001520}
1521
Christian Heimes9cd17752007-11-18 19:35:23 +00001522PyAPI_FUNC(PyObject *)
1523PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1527 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1528 importer = get_path_importer(path_importer_cache,
1529 path_hooks, path);
1530 }
1531 }
1532 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1533 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001534}
1535
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001536/* Search the path (default sys.path) for a module. Return the
1537 corresponding filedescr struct, and (via return arguments) the
1538 pathname and an open file. Return NULL if the module is not found. */
1539
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001540#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001541extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001543#endif
1544
Martin v. Löwis18e16552006-02-15 17:27:45 +00001545static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001546static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001547static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001548
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001549static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001550find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 Py_ssize_t i, npath;
1554 size_t len, namelen;
1555 struct filedescr *fdp = NULL;
1556 char *filemode;
1557 FILE *fp = NULL;
1558 PyObject *path_hooks, *path_importer_cache;
1559 struct stat statbuf;
1560 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1561 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1562 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1563 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001564#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 size_t saved_len;
1566 size_t saved_namelen;
1567 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001568#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (p_loader != NULL)
1570 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (strlen(subname) > MAXPATHLEN) {
1573 PyErr_SetString(PyExc_OverflowError,
1574 "module name is too long");
1575 return NULL;
1576 }
1577 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 /* sys.meta_path import hook */
1580 if (p_loader != NULL) {
1581 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 meta_path = PySys_GetObject("meta_path");
1584 if (meta_path == NULL || !PyList_Check(meta_path)) {
1585 PyErr_SetString(PyExc_ImportError,
1586 "sys.meta_path must be a list of "
1587 "import hooks");
1588 return NULL;
1589 }
1590 Py_INCREF(meta_path); /* zap guard */
1591 npath = PyList_Size(meta_path);
1592 for (i = 0; i < npath; i++) {
1593 PyObject *loader;
1594 PyObject *hook = PyList_GetItem(meta_path, i);
1595 loader = PyObject_CallMethod(hook, "find_module",
1596 "sO", fullname,
1597 path != NULL ?
1598 path : Py_None);
1599 if (loader == NULL) {
1600 Py_DECREF(meta_path);
1601 return NULL; /* true error */
1602 }
1603 if (loader != Py_None) {
1604 /* a loader was found */
1605 *p_loader = loader;
1606 Py_DECREF(meta_path);
1607 return &importhookdescr;
1608 }
1609 Py_DECREF(loader);
1610 }
1611 Py_DECREF(meta_path);
1612 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (find_frozen(fullname) != NULL) {
1615 strcpy(buf, fullname);
1616 return &fd_frozen;
1617 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (path == NULL) {
1620 if (is_builtin(name)) {
1621 strcpy(buf, name);
1622 return &fd_builtin;
1623 }
Guido van Rossumac279101996-08-22 23:10:58 +00001624#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1626 if (fp != NULL) {
1627 *p_fp = fp;
1628 return fdp;
1629 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001630#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 path = PySys_GetObject("path");
1632 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (path == NULL || !PyList_Check(path)) {
1635 PyErr_SetString(PyExc_ImportError,
1636 "sys.path must be a list of directory names");
1637 return NULL;
1638 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 path_hooks = PySys_GetObject("path_hooks");
1641 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1642 PyErr_SetString(PyExc_ImportError,
1643 "sys.path_hooks must be a list of "
1644 "import hooks");
1645 return NULL;
1646 }
1647 path_importer_cache = PySys_GetObject("path_importer_cache");
1648 if (path_importer_cache == NULL ||
1649 !PyDict_Check(path_importer_cache)) {
1650 PyErr_SetString(PyExc_ImportError,
1651 "sys.path_importer_cache must be a dict");
1652 return NULL;
1653 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 npath = PyList_Size(path);
1656 namelen = strlen(name);
1657 for (i = 0; i < npath; i++) {
1658 PyObject *v = PyList_GetItem(path, i);
1659 PyObject *origv = v;
1660 const char *base;
1661 Py_ssize_t size;
1662 if (!v)
1663 return NULL;
1664 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001665 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (v == NULL)
1667 return NULL;
1668 }
1669 else if (!PyBytes_Check(v))
1670 continue;
1671 else
1672 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 base = PyBytes_AS_STRING(v);
1675 size = PyBytes_GET_SIZE(v);
1676 len = size;
1677 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1678 Py_DECREF(v);
1679 continue; /* Too long */
1680 }
1681 strcpy(buf, base);
1682 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (strlen(buf) != len) {
1685 continue; /* v contains '\0' */
1686 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* sys.path_hooks import hook */
1689 if (p_loader != NULL) {
1690 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 importer = get_path_importer(path_importer_cache,
1693 path_hooks, origv);
1694 if (importer == NULL) {
1695 return NULL;
1696 }
1697 /* Note: importer is a borrowed reference */
1698 if (importer != Py_None) {
1699 PyObject *loader;
1700 loader = PyObject_CallMethod(importer,
1701 "find_module",
1702 "s", fullname);
1703 if (loader == NULL)
1704 return NULL; /* error */
1705 if (loader != Py_None) {
1706 /* a loader was found */
1707 *p_loader = loader;
1708 return &importhookdescr;
1709 }
1710 Py_DECREF(loader);
1711 continue;
1712 }
1713 }
1714 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001717#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001719#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 )
1721 buf[len++] = SEP;
1722 strcpy(buf+len, name);
1723 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 /* Check for package import (buf holds a directory name,
1726 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001727#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 if (stat(buf, &statbuf) == 0 && /* it exists */
1729 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1730 case_ok(buf, len, namelen, name)) { /* case matches */
1731 if (find_init_module(buf)) { /* and has __init__.py */
1732 return &fd_package;
1733 }
1734 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001735 int err;
1736 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1737 if (unicode == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 return NULL;
Victor Stinnered7916d2010-10-17 02:07:09 +00001739 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1740 "Not importing directory '%U': missing __init__.py",
1741 unicode);
1742 Py_DECREF(unicode);
1743 if (err)
1744 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 }
1746 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001747#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001748#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 /* take a snapshot of the module spec for restoration
1750 * after the 8 character DLL hackery
1751 */
1752 saved_buf = strdup(buf);
1753 saved_len = len;
1754 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001755#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001757#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 /* OS/2 limits DLLs to 8 character names (w/o
1759 extension)
1760 * so if the name is longer than that and its a
1761 * dynamically loaded module we're going to try,
1762 * truncate the name before trying
1763 */
1764 if (strlen(subname) > 8) {
1765 /* is this an attempt to load a C extension? */
1766 const struct filedescr *scan;
1767 scan = _PyImport_DynLoadFiletab;
1768 while (scan->suffix != NULL) {
1769 if (!strcmp(scan->suffix, fdp->suffix))
1770 break;
1771 else
1772 scan++;
1773 }
1774 if (scan->suffix != NULL) {
1775 /* yes, so truncate the name */
1776 namelen = 8;
1777 len -= strlen(subname) - namelen;
1778 buf[len] = '\0';
1779 }
1780 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001781#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 strcpy(buf+len, fdp->suffix);
1783 if (Py_VerboseFlag > 1)
1784 PySys_WriteStderr("# trying %s\n", buf);
1785 filemode = fdp->mode;
1786 if (filemode[0] == 'U')
1787 filemode = "r" PY_STDIOTEXTMODE;
1788 fp = fopen(buf, filemode);
1789 if (fp != NULL) {
1790 if (case_ok(buf, len, namelen, name))
1791 break;
1792 else { /* continue search */
1793 fclose(fp);
1794 fp = NULL;
1795 }
1796 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001797#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* restore the saved snapshot */
1799 strcpy(buf, saved_buf);
1800 len = saved_len;
1801 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001802#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001804#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* don't need/want the module name snapshot anymore */
1806 if (saved_buf)
1807 {
1808 free(saved_buf);
1809 saved_buf = NULL;
1810 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001811#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 if (fp != NULL)
1813 break;
1814 }
1815 if (fp == NULL) {
1816 PyErr_Format(PyExc_ImportError,
1817 "No module named %.200s", name);
1818 return NULL;
1819 }
1820 *p_fp = fp;
1821 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001822}
1823
Martin v. Löwis18e16552006-02-15 17:27:45 +00001824/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001825 * The arguments here are tricky, best shown by example:
1826 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1827 * ^ ^ ^ ^
1828 * |--------------------- buf ---------------------|
1829 * |------------------- len ------------------|
1830 * |------ name -------|
1831 * |----- namelen -----|
1832 * buf is the full path, but len only counts up to (& exclusive of) the
1833 * extension. name is the module name, also exclusive of extension.
1834 *
1835 * We've already done a successful stat() or fopen() on buf, so know that
1836 * there's some match, possibly case-insensitive.
1837 *
Tim Peters50d8d372001-02-28 05:34:27 +00001838 * case_ok() is to return 1 if there's a case-sensitive match for
1839 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1840 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001841 *
Tim Peters50d8d372001-02-28 05:34:27 +00001842 * case_ok() is used to implement case-sensitive import semantics even
1843 * on platforms with case-insensitive filesystems. It's trivial to implement
1844 * for case-sensitive filesystems. It's pretty much a cross-platform
1845 * nightmare for systems with case-insensitive filesystems.
1846 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001847
Tim Peters50d8d372001-02-28 05:34:27 +00001848/* First we may need a pile of platform-specific header files; the sequence
1849 * of #if's here should match the sequence in the body of case_ok().
1850 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001851#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001852#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001853
Tim Peters50d8d372001-02-28 05:34:27 +00001854#elif defined(DJGPP)
1855#include <dir.h>
1856
Jason Tishler7961aa62005-05-20 00:56:54 +00001857#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001858#include <sys/types.h>
1859#include <dirent.h>
1860
Andrew MacIntyred9400542002-02-26 11:41:34 +00001861#elif defined(PYOS_OS2)
1862#define INCL_DOS
1863#define INCL_DOSERRORS
1864#define INCL_NOPMAPI
1865#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001866#endif
1867
Guido van Rossum0980bd91998-02-13 17:18:36 +00001868static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001869case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001870{
Tim Peters50d8d372001-02-28 05:34:27 +00001871/* Pick a platform-specific implementation; the sequence of #if's here should
1872 * match the sequence just above.
1873 */
1874
Jason Tishler7961aa62005-05-20 00:56:54 +00001875/* MS_WINDOWS */
1876#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 WIN32_FIND_DATA data;
1878 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (Py_GETENV("PYTHONCASEOK") != NULL)
1881 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 h = FindFirstFile(buf, &data);
1884 if (h == INVALID_HANDLE_VALUE) {
1885 PyErr_Format(PyExc_NameError,
1886 "Can't find file for module %.100s\n(filename %.300s)",
1887 name, buf);
1888 return 0;
1889 }
1890 FindClose(h);
1891 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001892
1893/* DJGPP */
1894#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 struct ffblk ffblk;
1896 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (Py_GETENV("PYTHONCASEOK") != NULL)
1899 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1902 if (done) {
1903 PyErr_Format(PyExc_NameError,
1904 "Can't find file for module %.100s\n(filename %.300s)",
1905 name, buf);
1906 return 0;
1907 }
1908 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001909
Jason Tishler7961aa62005-05-20 00:56:54 +00001910/* new-fangled macintosh (macosx) or Cygwin */
1911#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 DIR *dirp;
1913 struct dirent *dp;
1914 char dirname[MAXPATHLEN + 1];
1915 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 if (Py_GETENV("PYTHONCASEOK") != NULL)
1918 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 /* Copy the dir component into dirname; substitute "." if empty */
1921 if (dirlen <= 0) {
1922 dirname[0] = '.';
1923 dirname[1] = '\0';
1924 }
1925 else {
1926 assert(dirlen <= MAXPATHLEN);
1927 memcpy(dirname, buf, dirlen);
1928 dirname[dirlen] = '\0';
1929 }
1930 /* Open the directory and search the entries for an exact match. */
1931 dirp = opendir(dirname);
1932 if (dirp) {
1933 char *nameWithExt = buf + len - namelen;
1934 while ((dp = readdir(dirp)) != NULL) {
1935 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001936#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001938#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001940#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (thislen >= namelen &&
1942 strcmp(dp->d_name, nameWithExt) == 0) {
1943 (void)closedir(dirp);
1944 return 1; /* Found */
1945 }
1946 }
1947 (void)closedir(dirp);
1948 }
1949 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001950
Andrew MacIntyred9400542002-02-26 11:41:34 +00001951/* OS/2 */
1952#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 HDIR hdir = 1;
1954 ULONG srchcnt = 1;
1955 FILEFINDBUF3 ffbuf;
1956 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (Py_GETENV("PYTHONCASEOK") != NULL)
1959 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 rc = DosFindFirst(buf,
1962 &hdir,
1963 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1964 &ffbuf, sizeof(ffbuf),
1965 &srchcnt,
1966 FIL_STANDARD);
1967 if (rc != NO_ERROR)
1968 return 0;
1969 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001970
Tim Peters50d8d372001-02-28 05:34:27 +00001971/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1972#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001974
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001975#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001976}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001977
Guido van Rossum197346f1997-10-31 18:38:52 +00001978#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001979
Guido van Rossum197346f1997-10-31 18:38:52 +00001980/* Helper to look for __init__.py or __init__.py[co] in potential package */
1981static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001982find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 const size_t save_len = strlen(buf);
1985 size_t i = save_len;
1986 char *pname; /* pointer to start of __init__ */
1987 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989/* For calling case_ok(buf, len, namelen, name):
1990 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1991 * ^ ^ ^ ^
1992 * |--------------------- buf ---------------------|
1993 * |------------------- len ------------------|
1994 * |------ name -------|
1995 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00001996 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (save_len + 13 >= MAXPATHLEN)
1998 return 0;
1999 buf[i++] = SEP;
2000 pname = buf + i;
2001 strcpy(pname, "__init__.py");
2002 if (stat(buf, &statbuf) == 0) {
2003 if (case_ok(buf,
2004 save_len + 9, /* len("/__init__") */
2005 8, /* len("__init__") */
2006 pname)) {
2007 buf[save_len] = '\0';
2008 return 1;
2009 }
2010 }
2011 i += strlen(pname);
2012 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2013 if (stat(buf, &statbuf) == 0) {
2014 if (case_ok(buf,
2015 save_len + 9, /* len("/__init__") */
2016 8, /* len("__init__") */
2017 pname)) {
2018 buf[save_len] = '\0';
2019 return 1;
2020 }
2021 }
2022 buf[save_len] = '\0';
2023 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002024}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002025
Guido van Rossum197346f1997-10-31 18:38:52 +00002026#endif /* HAVE_STAT */
2027
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002028
Tim Petersdbd9ba62000-07-09 03:09:57 +00002029static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002030
Victor Stinner44c6c152010-08-09 00:59:10 +00002031static PyObject*
2032load_builtin(char *name, char *pathname, int type)
2033{
2034 PyObject *m, *modules;
2035 int err;
2036
2037 if (pathname != NULL && pathname[0] != '\0')
2038 name = pathname;
2039
2040 if (type == C_BUILTIN)
2041 err = init_builtin(name);
2042 else
2043 err = PyImport_ImportFrozenModule(name);
2044 if (err < 0)
2045 return NULL;
2046 if (err == 0) {
2047 PyErr_Format(PyExc_ImportError,
2048 "Purported %s module %.200s not found",
2049 type == C_BUILTIN ?
2050 "builtin" : "frozen",
2051 name);
2052 return NULL;
2053 }
2054
2055 modules = PyImport_GetModuleDict();
2056 m = PyDict_GetItemString(modules, name);
2057 if (m == NULL) {
2058 PyErr_Format(
2059 PyExc_ImportError,
2060 "%s module %.200s not properly initialized",
2061 type == C_BUILTIN ?
2062 "builtin" : "frozen",
2063 name);
2064 return NULL;
2065 }
2066 Py_INCREF(m);
2067 return m;
2068}
2069
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002071 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002072
Guido van Rossum79f25d91997-04-29 20:08:16 +00002073static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002074load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 /* First check that there's an open file (if we need one) */
2079 switch (type) {
2080 case PY_SOURCE:
2081 case PY_COMPILED:
2082 if (fp == NULL) {
2083 PyErr_Format(PyExc_ValueError,
2084 "file object required for import (type code %d)",
2085 type);
2086 return NULL;
2087 }
2088 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 case PY_SOURCE:
2093 m = load_source_module(name, pathname, fp);
2094 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 case PY_COMPILED:
2097 m = load_compiled_module(name, pathname, fp);
2098 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002099
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002100#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 case C_EXTENSION:
2102 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2103 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002104#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 case PKG_DIRECTORY:
2107 m = load_package(name, pathname);
2108 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 case C_BUILTIN:
2111 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002112 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 case IMP_HOOK: {
2116 if (loader == NULL) {
2117 PyErr_SetString(PyExc_ImportError,
2118 "import hook without loader");
2119 return NULL;
2120 }
2121 m = PyObject_CallMethod(loader, "load_module", "s", name);
2122 break;
2123 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 default:
2126 PyErr_Format(PyExc_ImportError,
2127 "Don't know how to import %.200s (type code %d)",
2128 name, type);
2129 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002134}
2135
2136
2137/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002138 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002139 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002140
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002141static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002142init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002145
Victor Stinner49d3f252010-10-17 01:24:53 +00002146 if (_PyImport_FindBuiltin(name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 for (p = PyImport_Inittab; p->name != NULL; p++) {
2150 PyObject *mod;
2151 if (strcmp(name, p->name) == 0) {
2152 if (p->initfunc == NULL) {
2153 PyErr_Format(PyExc_ImportError,
2154 "Cannot re-init internal module %.200s",
2155 name);
2156 return -1;
2157 }
2158 if (Py_VerboseFlag)
2159 PySys_WriteStderr("import %s # builtin\n", name);
2160 mod = (*p->initfunc)();
2161 if (mod == 0)
2162 return -1;
Victor Stinner49d3f252010-10-17 01:24:53 +00002163 if (_PyImport_FixupBuiltin(mod, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 return -1;
2165 /* FixupExtension has put the module into sys.modules,
2166 so we can release our own reference. */
2167 Py_DECREF(mod);
2168 return 1;
2169 }
2170 }
2171 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002172}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002173
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002174
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002175/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002176
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002177static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002178find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (!name)
2183 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 for (p = PyImport_FrozenModules; ; p++) {
2186 if (p->name == NULL)
2187 return NULL;
2188 if (strcmp(p->name, name) == 0)
2189 break;
2190 }
2191 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002192}
2193
Guido van Rossum79f25d91997-04-29 20:08:16 +00002194static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002195get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 struct _frozen *p = find_frozen(name);
2198 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 if (p == NULL) {
2201 PyErr_Format(PyExc_ImportError,
2202 "No such frozen object named %.200s",
2203 name);
2204 return NULL;
2205 }
2206 if (p->code == NULL) {
2207 PyErr_Format(PyExc_ImportError,
2208 "Excluded frozen object named %.200s",
2209 name);
2210 return NULL;
2211 }
2212 size = p->size;
2213 if (size < 0)
2214 size = -size;
2215 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002216}
2217
Brett Cannon8d110132009-03-15 02:20:16 +00002218static PyObject *
2219is_frozen_package(char *name)
2220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 struct _frozen *p = find_frozen(name);
2222 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (p == NULL) {
2225 PyErr_Format(PyExc_ImportError,
2226 "No such frozen object named %.200s",
2227 name);
2228 return NULL;
2229 }
Brett Cannon8d110132009-03-15 02:20:16 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (size < 0)
2234 Py_RETURN_TRUE;
2235 else
2236 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002237}
2238
2239
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002240/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002241 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002242 an exception set if the initialization failed.
2243 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002244
2245int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002246PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 struct _frozen *p = find_frozen(name);
2249 PyObject *co;
2250 PyObject *m;
2251 int ispackage;
2252 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (p == NULL)
2255 return 0;
2256 if (p->code == NULL) {
2257 PyErr_Format(PyExc_ImportError,
2258 "Excluded frozen object named %.200s",
2259 name);
2260 return -1;
2261 }
2262 size = p->size;
2263 ispackage = (size < 0);
2264 if (ispackage)
2265 size = -size;
2266 if (Py_VerboseFlag)
2267 PySys_WriteStderr("import %s # frozen%s\n",
2268 name, ispackage ? " package" : "");
2269 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2270 if (co == NULL)
2271 return -1;
2272 if (!PyCode_Check(co)) {
2273 PyErr_Format(PyExc_TypeError,
2274 "frozen object %.200s is not a code object",
2275 name);
2276 goto err_return;
2277 }
2278 if (ispackage) {
2279 /* Set __path__ to the package name */
2280 PyObject *d, *s, *l;
2281 int err;
2282 m = PyImport_AddModule(name);
2283 if (m == NULL)
2284 goto err_return;
2285 d = PyModule_GetDict(m);
2286 s = PyUnicode_InternFromString(name);
2287 if (s == NULL)
2288 goto err_return;
2289 l = PyList_New(1);
2290 if (l == NULL) {
2291 Py_DECREF(s);
2292 goto err_return;
2293 }
2294 PyList_SET_ITEM(l, 0, s);
2295 err = PyDict_SetItemString(d, "__path__", l);
2296 Py_DECREF(l);
2297 if (err != 0)
2298 goto err_return;
2299 }
2300 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2301 if (m == NULL)
2302 goto err_return;
2303 Py_DECREF(co);
2304 Py_DECREF(m);
2305 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002306err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 Py_DECREF(co);
2308 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002309}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002310
2311
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002312/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002313 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002314
Guido van Rossum79f25d91997-04-29 20:08:16 +00002315PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002316PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 PyObject *pname;
2319 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 pname = PyUnicode_FromString(name);
2322 if (pname == NULL)
2323 return NULL;
2324 result = PyImport_Import(pname);
2325 Py_DECREF(pname);
2326 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002327}
2328
Christian Heimes072c0f12008-01-03 23:01:04 +00002329/* Import a module without blocking
2330 *
2331 * At first it tries to fetch the module from sys.modules. If the module was
2332 * never loaded before it loads it with PyImport_ImportModule() unless another
2333 * thread holds the import lock. In the latter case the function raises an
2334 * ImportError instead of blocking.
2335 *
2336 * Returns the module object with incremented ref count.
2337 */
2338PyObject *
2339PyImport_ImportModuleNoBlock(const char *name)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 PyObject *result;
2342 PyObject *modules;
2343 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* Try to get the module from sys.modules[name] */
2346 modules = PyImport_GetModuleDict();
2347 if (modules == NULL)
2348 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 result = PyDict_GetItemString(modules, name);
2351 if (result != NULL) {
2352 Py_INCREF(result);
2353 return result;
2354 }
2355 else {
2356 PyErr_Clear();
2357 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002358#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* check the import lock
2360 * me might be -1 but I ignore the error here, the lock function
2361 * takes care of the problem */
2362 me = PyThread_get_thread_ident();
2363 if (import_lock_thread == -1 || import_lock_thread == me) {
2364 /* no thread or me is holding the lock */
2365 return PyImport_ImportModule(name);
2366 }
2367 else {
2368 PyErr_Format(PyExc_ImportError,
2369 "Failed to import %.200s because the import lock"
2370 "is held by another thread.",
2371 name);
2372 return NULL;
2373 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002374#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002376#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002377}
2378
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002379/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002380static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002382static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002384static int mark_miss(char *name);
2385static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002387static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002388
2389/* The Magnum Opus of dotted-name import :-) */
2390
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002391static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002392import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 char buf[MAXPATHLEN+1];
2396 Py_ssize_t buflen = 0;
2397 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002400#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002402#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 ) {
2404 PyErr_SetString(PyExc_ImportError,
2405 "Import by filename is not supported.");
2406 return NULL;
2407 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 parent = get_parent(globals, buf, &buflen, level);
2410 if (parent == NULL)
2411 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002412
Benjamin Peterson556d8002010-06-27 22:37:28 +00002413 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2414 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 if (head == NULL)
2416 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 tail = head;
2419 Py_INCREF(tail);
2420 while (name) {
2421 next = load_next(tail, tail, &name, buf, &buflen);
2422 Py_DECREF(tail);
2423 if (next == NULL) {
2424 Py_DECREF(head);
2425 return NULL;
2426 }
2427 tail = next;
2428 }
2429 if (tail == Py_None) {
2430 /* If tail is Py_None, both get_parent and load_next found
2431 an empty module name: someone called __import__("") or
2432 doctored faulty bytecode */
2433 Py_DECREF(tail);
2434 Py_DECREF(head);
2435 PyErr_SetString(PyExc_ValueError,
2436 "Empty module name");
2437 return NULL;
2438 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (fromlist != NULL) {
2441 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2442 fromlist = NULL;
2443 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 if (fromlist == NULL) {
2446 Py_DECREF(tail);
2447 return head;
2448 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 Py_DECREF(head);
2451 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2452 Py_DECREF(tail);
2453 return NULL;
2454 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002457}
2458
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002459PyObject *
2460PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 PyObject *result;
2464 _PyImport_AcquireLock();
2465 result = import_module_level(name, globals, locals, fromlist, level);
2466 if (_PyImport_ReleaseLock() < 0) {
2467 Py_XDECREF(result);
2468 PyErr_SetString(PyExc_RuntimeError,
2469 "not holding the import lock");
2470 return NULL;
2471 }
2472 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002473}
2474
Fred Drake87590902004-05-28 20:21:36 +00002475/* Return the package that an import is being performed in. If globals comes
2476 from the module foo.bar.bat (not itself a package), this returns the
2477 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002478 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002479
2480 The *name* of the returned package is returned in buf, with the length of
2481 the name in *p_buflen.
2482
2483 If globals doesn't come from a package or a module in a package, or a
2484 corresponding entry is not found in sys.modules, Py_None is returned.
2485*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002486static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002487get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 static PyObject *namestr = NULL;
2490 static PyObject *pathstr = NULL;
2491 static PyObject *pkgstr = NULL;
2492 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2493 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (globals == NULL || !PyDict_Check(globals) || !level)
2496 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (namestr == NULL) {
2499 namestr = PyUnicode_InternFromString("__name__");
2500 if (namestr == NULL)
2501 return NULL;
2502 }
2503 if (pathstr == NULL) {
2504 pathstr = PyUnicode_InternFromString("__path__");
2505 if (pathstr == NULL)
2506 return NULL;
2507 }
2508 if (pkgstr == NULL) {
2509 pkgstr = PyUnicode_InternFromString("__package__");
2510 if (pkgstr == NULL)
2511 return NULL;
2512 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 *buf = '\0';
2515 *p_buflen = 0;
2516 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if ((pkgname != NULL) && (pkgname != Py_None)) {
2519 /* __package__ is set, so use it */
2520 char *pkgname_str;
2521 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 if (!PyUnicode_Check(pkgname)) {
2524 PyErr_SetString(PyExc_ValueError,
2525 "__package__ set to non-string");
2526 return NULL;
2527 }
2528 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2529 if (len == 0) {
2530 if (level > 0) {
2531 PyErr_SetString(PyExc_ValueError,
2532 "Attempted relative import in non-package");
2533 return NULL;
2534 }
2535 return Py_None;
2536 }
2537 if (len > MAXPATHLEN) {
2538 PyErr_SetString(PyExc_ValueError,
2539 "Package name too long");
2540 return NULL;
2541 }
2542 strcpy(buf, pkgname_str);
2543 } else {
2544 /* __package__ not set, so figure it out and set it */
2545 modname = PyDict_GetItem(globals, namestr);
2546 if (modname == NULL || !PyUnicode_Check(modname))
2547 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 modpath = PyDict_GetItem(globals, pathstr);
2550 if (modpath != NULL) {
2551 /* __path__ is set, so modname is already the package name */
2552 char *modname_str;
2553 Py_ssize_t len;
2554 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2557 if (len > MAXPATHLEN) {
2558 PyErr_SetString(PyExc_ValueError,
2559 "Module name too long");
2560 return NULL;
2561 }
2562 strcpy(buf, modname_str);
2563 error = PyDict_SetItem(globals, pkgstr, modname);
2564 if (error) {
2565 PyErr_SetString(PyExc_ValueError,
2566 "Could not set __package__");
2567 return NULL;
2568 }
2569 } else {
2570 /* Normal module, so work out the package name if any */
2571 char *start = _PyUnicode_AsString(modname);
2572 char *lastdot = strrchr(start, '.');
2573 size_t len;
2574 int error;
2575 if (lastdot == NULL && level > 0) {
2576 PyErr_SetString(PyExc_ValueError,
2577 "Attempted relative import in non-package");
2578 return NULL;
2579 }
2580 if (lastdot == NULL) {
2581 error = PyDict_SetItem(globals, pkgstr, Py_None);
2582 if (error) {
2583 PyErr_SetString(PyExc_ValueError,
2584 "Could not set __package__");
2585 return NULL;
2586 }
2587 return Py_None;
2588 }
2589 len = lastdot - start;
2590 if (len >= MAXPATHLEN) {
2591 PyErr_SetString(PyExc_ValueError,
2592 "Module name too long");
2593 return NULL;
2594 }
2595 strncpy(buf, start, len);
2596 buf[len] = '\0';
2597 pkgname = PyUnicode_FromString(buf);
2598 if (pkgname == NULL) {
2599 return NULL;
2600 }
2601 error = PyDict_SetItem(globals, pkgstr, pkgname);
2602 Py_DECREF(pkgname);
2603 if (error) {
2604 PyErr_SetString(PyExc_ValueError,
2605 "Could not set __package__");
2606 return NULL;
2607 }
2608 }
2609 }
2610 while (--level > 0) {
2611 char *dot = strrchr(buf, '.');
2612 if (dot == NULL) {
2613 PyErr_SetString(PyExc_ValueError,
2614 "Attempted relative import beyond "
2615 "toplevel package");
2616 return NULL;
2617 }
2618 *dot = '\0';
2619 }
2620 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 modules = PyImport_GetModuleDict();
2623 parent = PyDict_GetItemString(modules, buf);
2624 if (parent == NULL) {
2625 if (orig_level < 1) {
2626 PyObject *err_msg = PyBytes_FromFormat(
2627 "Parent module '%.200s' not found "
2628 "while handling absolute import", buf);
2629 if (err_msg == NULL) {
2630 return NULL;
2631 }
2632 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2633 PyBytes_AsString(err_msg), 1)) {
2634 *buf = '\0';
2635 *p_buflen = 0;
2636 parent = Py_None;
2637 }
2638 Py_DECREF(err_msg);
2639 } else {
2640 PyErr_Format(PyExc_SystemError,
2641 "Parent module '%.200s' not loaded, "
2642 "cannot perform relative import", buf);
2643 }
2644 }
2645 return parent;
2646 /* We expect, but can't guarantee, if parent != None, that:
2647 - parent.__name__ == buf
2648 - parent.__dict__ is globals
2649 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002650}
2651
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002652/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002653static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002654load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 char *name = *p_name;
2658 char *dot = strchr(name, '.');
2659 size_t len;
2660 char *p;
2661 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 if (strlen(name) == 0) {
2664 /* completely empty module name should only happen in
2665 'from . import' (or '__import__("")')*/
2666 Py_INCREF(mod);
2667 *p_name = NULL;
2668 return mod;
2669 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if (dot == NULL) {
2672 *p_name = NULL;
2673 len = strlen(name);
2674 }
2675 else {
2676 *p_name = dot+1;
2677 len = dot-name;
2678 }
2679 if (len == 0) {
2680 PyErr_SetString(PyExc_ValueError,
2681 "Empty module name");
2682 return NULL;
2683 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 p = buf + *p_buflen;
2686 if (p != buf)
2687 *p++ = '.';
2688 if (p+len-buf >= MAXPATHLEN) {
2689 PyErr_SetString(PyExc_ValueError,
2690 "Module name too long");
2691 return NULL;
2692 }
2693 strncpy(p, name, len);
2694 p[len] = '\0';
2695 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 result = import_submodule(mod, p, buf);
2698 if (result == Py_None && altmod != mod) {
2699 Py_DECREF(result);
2700 /* Here, altmod must be None and mod must not be None */
2701 result = import_submodule(altmod, p, p);
2702 if (result != NULL && result != Py_None) {
2703 if (mark_miss(buf) != 0) {
2704 Py_DECREF(result);
2705 return NULL;
2706 }
2707 strncpy(buf, name, len);
2708 buf[len] = '\0';
2709 *p_buflen = len;
2710 }
2711 }
2712 if (result == NULL)
2713 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 if (result == Py_None) {
2716 Py_DECREF(result);
2717 PyErr_Format(PyExc_ImportError,
2718 "No module named %.200s", name);
2719 return NULL;
2720 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002723}
2724
2725static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002726mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 PyObject *modules = PyImport_GetModuleDict();
2729 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002730}
2731
2732static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002733ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 if (!PyObject_HasAttrString(mod, "__path__"))
2739 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 for (i = 0; ; i++) {
2742 PyObject *item = PySequence_GetItem(fromlist, i);
2743 int hasit;
2744 if (item == NULL) {
2745 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2746 PyErr_Clear();
2747 return 1;
2748 }
2749 return 0;
2750 }
2751 if (!PyUnicode_Check(item)) {
2752 PyErr_SetString(PyExc_TypeError,
2753 "Item in ``from list'' not a string");
2754 Py_DECREF(item);
2755 return 0;
2756 }
2757 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2758 PyObject *all;
2759 Py_DECREF(item);
2760 /* See if the package defines __all__ */
2761 if (recursive)
2762 continue; /* Avoid endless recursion */
2763 all = PyObject_GetAttrString(mod, "__all__");
2764 if (all == NULL)
2765 PyErr_Clear();
2766 else {
2767 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2768 Py_DECREF(all);
2769 if (!ret)
2770 return 0;
2771 }
2772 continue;
2773 }
2774 hasit = PyObject_HasAttr(mod, item);
2775 if (!hasit) {
2776 PyObject *item8;
2777 char *subname;
2778 PyObject *submod;
2779 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002780 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 if (!item8) {
2782 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2783 return 0;
2784 }
2785 subname = PyBytes_AS_STRING(item8);
2786 if (buflen + strlen(subname) >= MAXPATHLEN) {
2787 PyErr_SetString(PyExc_ValueError,
2788 "Module name too long");
2789 Py_DECREF(item);
2790 return 0;
2791 }
2792 p = buf + buflen;
2793 *p++ = '.';
2794 strcpy(p, subname);
2795 submod = import_submodule(mod, subname, buf);
2796 Py_DECREF(item8);
2797 Py_XDECREF(submod);
2798 if (submod == NULL) {
2799 Py_DECREF(item);
2800 return 0;
2801 }
2802 }
2803 Py_DECREF(item);
2804 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002807}
2808
Neil Schemenauer00b09662003-06-16 21:03:07 +00002809static int
2810add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 if (mod == Py_None)
2814 return 1;
2815 /* Irrespective of the success of this load, make a
2816 reference to it in the parent package module. A copy gets
2817 saved in the modules dictionary under the full name, so get a
2818 reference from there, if need be. (The exception is when the
2819 load failed with a SyntaxError -- then there's no trace in
2820 sys.modules. In that case, of course, do nothing extra.) */
2821 if (submod == NULL) {
2822 submod = PyDict_GetItemString(modules, fullname);
2823 if (submod == NULL)
2824 return 1;
2825 }
2826 if (PyModule_Check(mod)) {
2827 /* We can't use setattr here since it can give a
2828 * spurious warning if the submodule name shadows a
2829 * builtin name */
2830 PyObject *dict = PyModule_GetDict(mod);
2831 if (!dict)
2832 return 0;
2833 if (PyDict_SetItemString(dict, subname, submod) < 0)
2834 return 0;
2835 }
2836 else {
2837 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2838 return 0;
2839 }
2840 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002841}
2842
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002843static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002844import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 PyObject *modules = PyImport_GetModuleDict();
2847 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 /* Require:
2850 if mod == None: subname == fullname
2851 else: mod.__name__ + "." + subname == fullname
2852 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2855 Py_INCREF(m);
2856 }
2857 else {
2858 PyObject *path, *loader = NULL;
2859 char buf[MAXPATHLEN+1];
2860 struct filedescr *fdp;
2861 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 if (mod == Py_None)
2864 path = NULL;
2865 else {
2866 path = PyObject_GetAttrString(mod, "__path__");
2867 if (path == NULL) {
2868 PyErr_Clear();
2869 Py_INCREF(Py_None);
2870 return Py_None;
2871 }
2872 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 buf[0] = '\0';
2875 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2876 &fp, &loader);
2877 Py_XDECREF(path);
2878 if (fdp == NULL) {
2879 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2880 return NULL;
2881 PyErr_Clear();
2882 Py_INCREF(Py_None);
2883 return Py_None;
2884 }
2885 m = load_module(fullname, fp, buf, fdp->type, loader);
2886 Py_XDECREF(loader);
2887 if (fp)
2888 fclose(fp);
2889 if (!add_submodule(mod, m, fullname, subname, modules)) {
2890 Py_XDECREF(m);
2891 m = NULL;
2892 }
2893 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002896}
2897
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002898
2899/* Re-import a module of any kind and return its module object, WITH
2900 INCREMENTED REFERENCE COUNT */
2901
Guido van Rossum79f25d91997-04-29 20:08:16 +00002902PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002903PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 PyInterpreterState *interp = PyThreadState_Get()->interp;
2906 PyObject *modules_reloading = interp->modules_reloading;
2907 PyObject *modules = PyImport_GetModuleDict();
2908 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2909 char *name, *subname;
2910 char buf[MAXPATHLEN+1];
2911 struct filedescr *fdp;
2912 FILE *fp = NULL;
2913 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 if (modules_reloading == NULL) {
2916 Py_FatalError("PyImport_ReloadModule: "
2917 "no modules_reloading dictionary!");
2918 return NULL;
2919 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 if (m == NULL || !PyModule_Check(m)) {
2922 PyErr_SetString(PyExc_TypeError,
2923 "reload() argument must be module");
2924 return NULL;
2925 }
2926 name = (char*)PyModule_GetName(m);
2927 if (name == NULL)
2928 return NULL;
2929 if (m != PyDict_GetItemString(modules, name)) {
2930 PyErr_Format(PyExc_ImportError,
2931 "reload(): module %.200s not in sys.modules",
2932 name);
2933 return NULL;
2934 }
2935 existing_m = PyDict_GetItemString(modules_reloading, name);
2936 if (existing_m != NULL) {
2937 /* Due to a recursive reload, this module is already
2938 being reloaded. */
2939 Py_INCREF(existing_m);
2940 return existing_m;
2941 }
2942 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2943 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 subname = strrchr(name, '.');
2946 if (subname == NULL)
2947 subname = name;
2948 else {
2949 PyObject *parentname, *parent;
2950 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2951 if (parentname == NULL) {
2952 imp_modules_reloading_clear();
2953 return NULL;
2954 }
2955 parent = PyDict_GetItem(modules, parentname);
2956 if (parent == NULL) {
2957 PyErr_Format(PyExc_ImportError,
2958 "reload(): parent %U not in sys.modules",
2959 parentname);
2960 Py_DECREF(parentname);
2961 imp_modules_reloading_clear();
2962 return NULL;
2963 }
2964 Py_DECREF(parentname);
2965 subname++;
2966 path = PyObject_GetAttrString(parent, "__path__");
2967 if (path == NULL)
2968 PyErr_Clear();
2969 }
2970 buf[0] = '\0';
2971 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2972 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 if (fdp == NULL) {
2975 Py_XDECREF(loader);
2976 imp_modules_reloading_clear();
2977 return NULL;
2978 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 newm = load_module(name, fp, buf, fdp->type, loader);
2981 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 if (fp)
2984 fclose(fp);
2985 if (newm == NULL) {
2986 /* load_module probably removed name from modules because of
2987 * the error. Put back the original module object. We're
2988 * going to return NULL in this case regardless of whether
2989 * replacing name succeeds, so the return value is ignored.
2990 */
2991 PyDict_SetItemString(modules, name, m);
2992 }
2993 imp_modules_reloading_clear();
2994 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002995}
2996
2997
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002998/* Higher-level import emulator which emulates the "import" statement
2999 more accurately -- it invokes the __import__() function from the
3000 builtins of the current globals. This means that the import is
3001 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003002 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003003 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003004 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003005 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003006
3007PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003008PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 static PyObject *silly_list = NULL;
3011 static PyObject *builtins_str = NULL;
3012 static PyObject *import_str = NULL;
3013 PyObject *globals = NULL;
3014 PyObject *import = NULL;
3015 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003016 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 /* Initialize constant string objects */
3020 if (silly_list == NULL) {
3021 import_str = PyUnicode_InternFromString("__import__");
3022 if (import_str == NULL)
3023 return NULL;
3024 builtins_str = PyUnicode_InternFromString("__builtins__");
3025 if (builtins_str == NULL)
3026 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003027 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 if (silly_list == NULL)
3029 return NULL;
3030 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 /* Get the builtins from current globals */
3033 globals = PyEval_GetGlobals();
3034 if (globals != NULL) {
3035 Py_INCREF(globals);
3036 builtins = PyObject_GetItem(globals, builtins_str);
3037 if (builtins == NULL)
3038 goto err;
3039 }
3040 else {
3041 /* No globals -- use standard builtins, and fake globals */
3042 builtins = PyImport_ImportModuleLevel("builtins",
3043 NULL, NULL, NULL, 0);
3044 if (builtins == NULL)
3045 return NULL;
3046 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3047 if (globals == NULL)
3048 goto err;
3049 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 /* Get the __import__ function from the builtins */
3052 if (PyDict_Check(builtins)) {
3053 import = PyObject_GetItem(builtins, import_str);
3054 if (import == NULL)
3055 PyErr_SetObject(PyExc_KeyError, import_str);
3056 }
3057 else
3058 import = PyObject_GetAttr(builtins, import_str);
3059 if (import == NULL)
3060 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003063 Always use absolute import here.
3064 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3066 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003067 if (r == NULL)
3068 goto err;
3069 Py_DECREF(r);
3070
3071 modules = PyImport_GetModuleDict();
3072 r = PyDict_GetItem(modules, module_name);
3073 if (r != NULL)
3074 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003075
3076 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 Py_XDECREF(globals);
3078 Py_XDECREF(builtins);
3079 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003082}
3083
3084
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003085/* Module 'imp' provides Python access to the primitives used for
3086 importing modules.
3087*/
3088
Guido van Rossum79f25d91997-04-29 20:08:16 +00003089static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003090imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 buf[0] = (char) ((magic >> 0) & 0xff);
3095 buf[1] = (char) ((magic >> 8) & 0xff);
3096 buf[2] = (char) ((magic >> 16) & 0xff);
3097 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003100}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003101
3102static PyObject *
3103imp_get_magic(PyObject *self, PyObject *noargs)
3104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003106}
3107
3108static PyObject *
3109imp_get_tag(PyObject *self, PyObject *noargs)
3110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003112}
3113
Guido van Rossum79f25d91997-04-29 20:08:16 +00003114static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003115imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 PyObject *list;
3118 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 list = PyList_New(0);
3121 if (list == NULL)
3122 return NULL;
3123 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3124 PyObject *item = Py_BuildValue("ssi",
3125 fdp->suffix, fdp->mode, fdp->type);
3126 if (item == NULL) {
3127 Py_DECREF(list);
3128 return NULL;
3129 }
3130 if (PyList_Append(list, item) < 0) {
3131 Py_DECREF(list);
3132 Py_DECREF(item);
3133 return NULL;
3134 }
3135 Py_DECREF(item);
3136 }
3137 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003138}
3139
Guido van Rossum79f25d91997-04-29 20:08:16 +00003140static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003141call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 extern int fclose(FILE *);
3144 PyObject *fob, *ret;
3145 PyObject *pathobj;
3146 struct filedescr *fdp;
3147 char pathname[MAXPATHLEN+1];
3148 FILE *fp = NULL;
3149 int fd = -1;
3150 char *found_encoding = NULL;
3151 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 pathname[0] = '\0';
3154 if (path == Py_None)
3155 path = NULL;
3156 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3157 if (fdp == NULL)
3158 return NULL;
3159 if (fp != NULL) {
3160 fd = fileno(fp);
3161 if (fd != -1)
3162 fd = dup(fd);
3163 fclose(fp);
3164 fp = NULL;
3165 }
3166 if (fd != -1) {
3167 if (strchr(fdp->mode, 'b') == NULL) {
3168 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3169 memory. */
3170 found_encoding = PyTokenizer_FindEncoding(fd);
3171 lseek(fd, 0, 0); /* Reset position */
3172 if (found_encoding == NULL && PyErr_Occurred())
3173 return NULL;
3174 encoding = (found_encoding != NULL) ? found_encoding :
3175 (char*)PyUnicode_GetDefaultEncoding();
3176 }
3177 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3178 (char*)encoding, NULL, NULL, 1);
3179 if (fob == NULL) {
3180 close(fd);
3181 PyMem_FREE(found_encoding);
3182 return NULL;
3183 }
3184 }
3185 else {
3186 fob = Py_None;
3187 Py_INCREF(fob);
3188 }
3189 pathobj = PyUnicode_DecodeFSDefault(pathname);
3190 ret = Py_BuildValue("NN(ssi)",
3191 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3192 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003195}
3196
Guido van Rossum79f25d91997-04-29 20:08:16 +00003197static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003198imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 char *name;
3201 PyObject *ret, *path = NULL;
3202 if (!PyArg_ParseTuple(args, "es|O:find_module",
3203 Py_FileSystemDefaultEncoding, &name,
3204 &path))
3205 return NULL;
3206 ret = call_find_module(name, path);
3207 PyMem_Free(name);
3208 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003209}
3210
3211static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003212imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 char *name;
3215 int ret;
3216 PyObject *m;
3217 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3218 return NULL;
3219 ret = init_builtin(name);
3220 if (ret < 0)
3221 return NULL;
3222 if (ret == 0) {
3223 Py_INCREF(Py_None);
3224 return Py_None;
3225 }
3226 m = PyImport_AddModule(name);
3227 Py_XINCREF(m);
3228 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003229}
3230
Guido van Rossum79f25d91997-04-29 20:08:16 +00003231static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003232imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 char *name;
3235 int ret;
3236 PyObject *m;
3237 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3238 return NULL;
3239 ret = PyImport_ImportFrozenModule(name);
3240 if (ret < 0)
3241 return NULL;
3242 if (ret == 0) {
3243 Py_INCREF(Py_None);
3244 return Py_None;
3245 }
3246 m = PyImport_AddModule(name);
3247 Py_XINCREF(m);
3248 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003249}
3250
Guido van Rossum79f25d91997-04-29 20:08:16 +00003251static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003252imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3257 return NULL;
3258 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003259}
3260
Guido van Rossum79f25d91997-04-29 20:08:16 +00003261static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003262imp_is_frozen_package(PyObject *self, PyObject *args)
3263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3267 return NULL;
3268 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003269}
3270
3271static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003272imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 char *name;
3275 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3276 return NULL;
3277 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003278}
3279
Guido van Rossum79f25d91997-04-29 20:08:16 +00003280static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003281imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 char *name;
3284 struct _frozen *p;
3285 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3286 return NULL;
3287 p = find_frozen(name);
3288 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003289}
3290
3291static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003292get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 FILE *fp;
3295 if (mode[0] == 'U')
3296 mode = "r" PY_STDIOTEXTMODE;
3297 if (fob == NULL) {
3298 fp = fopen(pathname, mode);
3299 }
3300 else {
3301 int fd = PyObject_AsFileDescriptor(fob);
3302 if (fd == -1)
3303 return NULL;
3304 if (!_PyVerify_fd(fd))
3305 goto error;
3306 /* the FILE struct gets a new fd, so that it can be closed
3307 * independently of the file descriptor given
3308 */
3309 fd = dup(fd);
3310 if (fd == -1)
3311 goto error;
3312 fp = fdopen(fd, mode);
3313 }
3314 if (fp)
3315 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003316error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 PyErr_SetFromErrno(PyExc_IOError);
3318 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003319}
3320
Guido van Rossum79f25d91997-04-29 20:08:16 +00003321static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003322imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 char *name;
3325 char *pathname;
3326 PyObject *fob = NULL;
3327 PyObject *m;
3328 FILE *fp;
3329 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3330 &name,
3331 Py_FileSystemDefaultEncoding, &pathname,
3332 &fob))
3333 return NULL;
3334 fp = get_file(pathname, fob, "rb");
3335 if (fp == NULL) {
3336 PyMem_Free(pathname);
3337 return NULL;
3338 }
3339 m = load_compiled_module(name, pathname, fp);
3340 fclose(fp);
3341 PyMem_Free(pathname);
3342 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003343}
3344
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003345#ifdef HAVE_DYNAMIC_LOADING
3346
Guido van Rossum79f25d91997-04-29 20:08:16 +00003347static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003348imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003351 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 char *pathname;
3353 PyObject *fob = NULL;
3354 PyObject *m;
3355 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003356 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3357 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003359 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 if (fob) {
3361 fp = get_file(pathname, fob, "r");
3362 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003363 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 return NULL;
3365 }
3366 }
3367 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003368 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 if (fp)
3370 fclose(fp);
3371 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003372}
3373
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003374#endif /* HAVE_DYNAMIC_LOADING */
3375
Guido van Rossum79f25d91997-04-29 20:08:16 +00003376static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003377imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 char *name;
3380 char *pathname;
3381 PyObject *fob = NULL;
3382 PyObject *m;
3383 FILE *fp;
3384 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3385 &name,
3386 Py_FileSystemDefaultEncoding, &pathname,
3387 &fob))
3388 return NULL;
3389 fp = get_file(pathname, fob, "r");
3390 if (fp == NULL) {
3391 PyMem_Free(pathname);
3392 return NULL;
3393 }
3394 m = load_source_module(name, pathname, fp);
3395 PyMem_Free(pathname);
3396 fclose(fp);
3397 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003398}
3399
Guido van Rossum79f25d91997-04-29 20:08:16 +00003400static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003401imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 char *name;
3404 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003405 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 PyObject * ret;
3407 char *suffix; /* Unused */
3408 char *mode;
3409 int type;
3410 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003411
Victor Stinner1a563032010-10-15 22:43:10 +00003412 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003414 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 &suffix, &mode, &type))
3416 return NULL;
3417 if (*mode) {
3418 /* Mode must start with 'r' or 'U' and must not contain '+'.
3419 Implicit in this test is the assumption that the mode
3420 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3423 PyErr_Format(PyExc_ValueError,
3424 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003425 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 return NULL;
3427 }
3428 }
3429 if (fob == Py_None)
3430 fp = NULL;
3431 else {
3432 fp = get_file(NULL, fob, mode);
3433 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003434 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 return NULL;
3436 }
3437 }
Victor Stinner1a563032010-10-15 22:43:10 +00003438 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3439 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 if (fp)
3441 fclose(fp);
3442 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003443}
3444
3445static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003446imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 char *name;
3449 char *pathname;
3450 PyObject * ret;
3451 if (!PyArg_ParseTuple(args, "ses:load_package",
3452 &name, Py_FileSystemDefaultEncoding, &pathname))
3453 return NULL;
3454 ret = load_package(name, pathname);
3455 PyMem_Free(pathname);
3456 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003457}
3458
3459static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003460imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 char *name;
3463 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3464 return NULL;
3465 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003466}
3467
Christian Heimes13a7a212008-01-07 17:13:09 +00003468static PyObject *
3469imp_reload(PyObject *self, PyObject *v)
3470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003472}
3473
3474PyDoc_STRVAR(doc_reload,
3475"reload(module) -> module\n\
3476\n\
3477Reload the module. The module must have been successfully imported before.");
3478
Barry Warsaw28a691b2010-04-17 00:19:56 +00003479static PyObject *
3480imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003485 PyObject *pathbytes;
3486 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003487 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003491 args, kws, "O&|O", kwlist,
3492 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003494
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003495 if (debug_override != NULL &&
3496 (debug = PyObject_IsTrue(debug_override)) < 0) {
3497 Py_DECREF(pathbytes);
3498 return NULL;
3499 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003500
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003501 cpathname = make_compiled_pathname(
3502 PyBytes_AS_STRING(pathbytes),
3503 buf, MAXPATHLEN+1, debug);
3504 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 if (cpathname == NULL) {
3507 PyErr_Format(PyExc_SystemError, "path buffer too short");
3508 return NULL;
3509 }
Victor Stinner88bd8912010-10-15 22:46:07 +00003510 return PyUnicode_DecodeFSDefault(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003511}
3512
3513PyDoc_STRVAR(doc_cache_from_source,
3514"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3515\n\
3516The .py file does not need to exist; this simply returns the path to the\n\
3517.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3518will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3519\n\
3520If debug_override is not None, then it must be a boolean and is taken as\n\
3521the value of __debug__ instead.");
3522
3523static PyObject *
3524imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 char *pathname;
3529 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 if (!PyArg_ParseTupleAndKeywords(
3532 args, kws, "es", kwlist,
3533 Py_FileSystemDefaultEncoding, &pathname))
3534 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 if (make_source_pathname(pathname, buf) == NULL) {
3537 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3538 pathname);
3539 PyMem_Free(pathname);
3540 return NULL;
3541 }
3542 PyMem_Free(pathname);
3543 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003544}
3545
3546PyDoc_STRVAR(doc_source_from_cache,
3547"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3548\n\
3549The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3550the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3551does not conform to PEP 3147 format, ValueError will be raised.");
3552
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003553/* Doc strings */
3554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003555PyDoc_STRVAR(doc_imp,
3556"This module provides the components needed to build your own\n\
3557__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003559PyDoc_STRVAR(doc_find_module,
3560"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003561Search for a module. If path is omitted or None, search for a\n\
3562built-in, frozen or special module and continue search in sys.path.\n\
3563The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003564package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003565
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003566PyDoc_STRVAR(doc_load_module,
3567"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003568Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003569The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003571PyDoc_STRVAR(doc_get_magic,
3572"get_magic() -> string\n\
3573Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003574
Barry Warsaw28a691b2010-04-17 00:19:56 +00003575PyDoc_STRVAR(doc_get_tag,
3576"get_tag() -> string\n\
3577Return the magic tag for .pyc or .pyo files.");
3578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003579PyDoc_STRVAR(doc_get_suffixes,
3580"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003581Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003582that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003584PyDoc_STRVAR(doc_new_module,
3585"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003586Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003587The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003589PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003590"lock_held() -> boolean\n\
3591Return True if the import lock is currently held, else False.\n\
3592On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003593
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003594PyDoc_STRVAR(doc_acquire_lock,
3595"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003596Acquires the interpreter's import lock for the current thread.\n\
3597This lock should be used by import hooks to ensure thread-safety\n\
3598when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003599On platforms without threads, this function does nothing.");
3600
3601PyDoc_STRVAR(doc_release_lock,
3602"release_lock() -> None\n\
3603Release the interpreter's import lock.\n\
3604On platforms without threads, this function does nothing.");
3605
Guido van Rossum79f25d91997-04-29 20:08:16 +00003606static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3608 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3609 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3610 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3611 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3612 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3613 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3614 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3615 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3616 {"reload", imp_reload, METH_O, doc_reload},
3617 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3618 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3619 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3620 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3621 /* The rest are obsolete */
3622 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3623 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3624 {"init_builtin", imp_init_builtin, METH_VARARGS},
3625 {"init_frozen", imp_init_frozen, METH_VARARGS},
3626 {"is_builtin", imp_is_builtin, METH_VARARGS},
3627 {"is_frozen", imp_is_frozen, METH_VARARGS},
3628 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003629#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003631#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 {"load_package", imp_load_package, METH_VARARGS},
3633 {"load_source", imp_load_source, METH_VARARGS},
3634 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003635};
3636
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003637static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003638setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 PyObject *v;
3641 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 v = PyLong_FromLong((long)value);
3644 err = PyDict_SetItemString(d, name, v);
3645 Py_XDECREF(v);
3646 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003647}
3648
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003649typedef struct {
3650 PyObject_HEAD
3651} NullImporter;
3652
3653static int
3654NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3655{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003656#ifndef MS_WINDOWS
3657 PyObject *path;
3658 struct stat statbuf;
3659 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3662 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003663
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003664 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3665 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003667
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003668 if (PyBytes_GET_SIZE(path) == 0) {
3669 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 PyErr_SetString(PyExc_ImportError, "empty pathname");
3671 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003673
3674 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3675 Py_DECREF(path);
3676 if (rv == 0) {
3677 /* it exists */
3678 if (S_ISDIR(statbuf.st_mode)) {
3679 /* it's a directory */
3680 PyErr_SetString(PyExc_ImportError, "existing directory");
3681 return -1;
3682 }
3683 }
3684#else /* MS_WINDOWS */
3685 PyObject *pathobj;
3686 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003687 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003688
3689 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3690 return -1;
3691
3692 if (!PyArg_ParseTuple(args, "U:NullImporter",
3693 &pathobj))
3694 return -1;
3695
3696 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3697 PyErr_SetString(PyExc_ImportError, "empty pathname");
3698 return -1;
3699 }
3700
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003701 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003702 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003703 return -1;
3704 /* see issue1293 and issue3677:
3705 * stat() on Windows doesn't recognise paths like
3706 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3707 */
3708 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003709 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003710 if (rv != INVALID_FILE_ATTRIBUTES) {
3711 /* it exists */
3712 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3713 /* it's a directory */
3714 PyErr_SetString(PyExc_ImportError, "existing directory");
3715 return -1;
3716 }
3717 }
3718#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003720}
3721
3722static PyObject *
3723NullImporter_find_module(NullImporter *self, PyObject *args)
3724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003726}
3727
3728static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3730 "Always return None"
3731 },
3732 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003733};
3734
3735
Christian Heimes9cd17752007-11-18 19:35:23 +00003736PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 PyVarObject_HEAD_INIT(NULL, 0)
3738 "imp.NullImporter", /*tp_name*/
3739 sizeof(NullImporter), /*tp_basicsize*/
3740 0, /*tp_itemsize*/
3741 0, /*tp_dealloc*/
3742 0, /*tp_print*/
3743 0, /*tp_getattr*/
3744 0, /*tp_setattr*/
3745 0, /*tp_reserved*/
3746 0, /*tp_repr*/
3747 0, /*tp_as_number*/
3748 0, /*tp_as_sequence*/
3749 0, /*tp_as_mapping*/
3750 0, /*tp_hash */
3751 0, /*tp_call*/
3752 0, /*tp_str*/
3753 0, /*tp_getattro*/
3754 0, /*tp_setattro*/
3755 0, /*tp_as_buffer*/
3756 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3757 "Null importer object", /* tp_doc */
3758 0, /* tp_traverse */
3759 0, /* tp_clear */
3760 0, /* tp_richcompare */
3761 0, /* tp_weaklistoffset */
3762 0, /* tp_iter */
3763 0, /* tp_iternext */
3764 NullImporter_methods, /* tp_methods */
3765 0, /* tp_members */
3766 0, /* tp_getset */
3767 0, /* tp_base */
3768 0, /* tp_dict */
3769 0, /* tp_descr_get */
3770 0, /* tp_descr_set */
3771 0, /* tp_dictoffset */
3772 (initproc)NullImporter_init, /* tp_init */
3773 0, /* tp_alloc */
3774 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003775};
3776
Martin v. Löwis1a214512008-06-11 05:26:20 +00003777static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 PyModuleDef_HEAD_INIT,
3779 "imp",
3780 doc_imp,
3781 0,
3782 imp_methods,
3783 NULL,
3784 NULL,
3785 NULL,
3786 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003787};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003788
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003789PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003790PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 if (PyType_Ready(&PyNullImporter_Type) < 0)
3795 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 m = PyModule_Create(&impmodule);
3798 if (m == NULL)
3799 goto failure;
3800 d = PyModule_GetDict(m);
3801 if (d == NULL)
3802 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3805 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3806 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3807 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3808 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3809 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3810 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3811 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3812 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3813 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 Py_INCREF(&PyNullImporter_Type);
3816 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3817 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003818 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 Py_XDECREF(m);
3820 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003821}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003822
3823
Guido van Rossumb18618d2000-05-03 23:44:39 +00003824/* API for embedding applications that want to add their own entries
3825 to the table of built-in modules. This should normally be called
3826 *before* Py_Initialize(). When the table resize fails, -1 is
3827 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003828
3829 After a similar function by Just van Rossum. */
3830
3831int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003832PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 static struct _inittab *our_copy = NULL;
3835 struct _inittab *p;
3836 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 /* Count the number of entries in both tables */
3839 for (n = 0; newtab[n].name != NULL; n++)
3840 ;
3841 if (n == 0)
3842 return 0; /* Nothing to do */
3843 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3844 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 /* Allocate new memory for the combined table */
3847 p = our_copy;
3848 PyMem_RESIZE(p, struct _inittab, i+n+1);
3849 if (p == NULL)
3850 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 /* Copy the tables into the new memory */
3853 if (our_copy != PyImport_Inittab)
3854 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3855 PyImport_Inittab = our_copy = p;
3856 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003859}
3860
3861/* Shorthand to add a single entry given a name and a function */
3862
3863int
Brett Cannona826f322009-04-02 03:41:46 +00003864PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 newtab[0].name = (char *)name;
3871 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003874}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003875
3876#ifdef __cplusplus
3877}
3878#endif