blob: 09fc52cbda06bfef68886f69c0c5a259479d4255 [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();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000328 if (import_lock_level > 1) {
329 /* Forked as a side effect of import */
330 long me = PyThread_get_thread_ident();
331 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100332 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000333 import_lock_thread = me;
334 import_lock_level--;
335 } else {
336 import_lock_thread = -1;
337 import_lock_level = 0;
338 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000339}
340
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000341#endif
342
Tim Peters69232342001-08-30 05:16:13 +0000343static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000344imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000345{
Tim Peters69232342001-08-30 05:16:13 +0000346#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000348#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000350#endif
351}
352
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000354imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000355{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000356#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000358#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 Py_INCREF(Py_None);
360 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361}
362
363static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000364imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000365{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000366#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (_PyImport_ReleaseLock() < 0) {
368 PyErr_SetString(PyExc_RuntimeError,
369 "not holding the import lock");
370 return NULL;
371 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000372#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 Py_INCREF(Py_None);
374 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000375}
376
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377static void
378imp_modules_reloading_clear(void)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyInterpreterState *interp = PyThreadState_Get()->interp;
381 if (interp->modules_reloading != NULL)
382 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383}
384
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385/* Helper for sys */
386
387PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000388PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyInterpreterState *interp = PyThreadState_GET()->interp;
391 if (interp->modules == NULL)
392 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
393 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394}
395
Guido van Rossum3f5da241990-12-20 15:06:42 +0000396
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000397/* List of names to clear in sys */
398static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 "path", "argv", "ps1", "ps2",
400 "last_type", "last_value", "last_traceback",
401 "path_hooks", "path_importer_cache", "meta_path",
402 /* misc stuff */
403 "flags", "float_info",
404 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405};
406
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000407static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 "stdin", "__stdin__",
409 "stdout", "__stdout__",
410 "stderr", "__stderr__",
411 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000412};
413
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000415/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000416
Guido van Rossum3f5da241990-12-20 15:06:42 +0000417void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000418PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *key, *value, *dict;
422 PyInterpreterState *interp = PyThreadState_GET()->interp;
423 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (modules == NULL)
426 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 /* Delete some special variables first. These are common
429 places where user values hide and people complain when their
430 destructors fail. Since the modules containing them are
431 deleted *last* of all, they would come too late in the normal
432 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 value = PyDict_GetItemString(modules, "builtins");
435 if (value != NULL && PyModule_Check(value)) {
436 dict = PyModule_GetDict(value);
437 if (Py_VerboseFlag)
438 PySys_WriteStderr("# clear builtins._\n");
439 PyDict_SetItemString(dict, "_", Py_None);
440 }
441 value = PyDict_GetItemString(modules, "sys");
442 if (value != NULL && PyModule_Check(value)) {
443 char **p;
444 PyObject *v;
445 dict = PyModule_GetDict(value);
446 for (p = sys_deletes; *p != NULL; p++) {
447 if (Py_VerboseFlag)
448 PySys_WriteStderr("# clear sys.%s\n", *p);
449 PyDict_SetItemString(dict, *p, Py_None);
450 }
451 for (p = sys_files; *p != NULL; p+=2) {
452 if (Py_VerboseFlag)
453 PySys_WriteStderr("# restore sys.%s\n", *p);
454 v = PyDict_GetItemString(dict, *(p+1));
455 if (v == NULL)
456 v = Py_None;
457 PyDict_SetItemString(dict, *p, v);
458 }
459 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* First, delete __main__ */
462 value = PyDict_GetItemString(modules, "__main__");
463 if (value != NULL && PyModule_Check(value)) {
464 if (Py_VerboseFlag)
465 PySys_WriteStderr("# cleanup __main__\n");
466 _PyModule_Clear(value);
467 PyDict_SetItemString(modules, "__main__", Py_None);
468 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 /* The special treatment of "builtins" here is because even
471 when it's not referenced as a module, its dictionary is
472 referenced by almost every module's __builtins__. Since
473 deleting a module clears its dictionary (even if there are
474 references left to it), we need to delete the "builtins"
475 module last. Likewise, we don't delete sys until the very
476 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Also note that we 'delete' modules by replacing their entry
479 in the modules dict with None, rather than really deleting
480 them; this avoids a rehash of the modules dictionary and
481 also marks them as "non existent" so they won't be
482 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Next, repeatedly delete modules with a reference count of
485 one (skipping builtins and sys) and delete them */
486 do {
487 ndone = 0;
488 pos = 0;
489 while (PyDict_Next(modules, &pos, &key, &value)) {
490 if (value->ob_refcnt != 1)
491 continue;
492 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100493 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100495 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 continue;
497 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100498 PySys_FormatStderr(
499 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 _PyModule_Clear(value);
501 PyDict_SetItem(modules, key, Py_None);
502 ndone++;
503 }
504 }
505 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Next, delete all modules (still skipping builtins and sys) */
508 pos = 0;
509 while (PyDict_Next(modules, &pos, &key, &value)) {
510 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100511 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100513 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 continue;
515 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100516 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 _PyModule_Clear(value);
518 PyDict_SetItem(modules, key, Py_None);
519 }
520 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* Next, delete sys and builtins (in that order) */
523 value = PyDict_GetItemString(modules, "sys");
524 if (value != NULL && PyModule_Check(value)) {
525 if (Py_VerboseFlag)
526 PySys_WriteStderr("# cleanup sys\n");
527 _PyModule_Clear(value);
528 PyDict_SetItemString(modules, "sys", Py_None);
529 }
530 value = PyDict_GetItemString(modules, "builtins");
531 if (value != NULL && PyModule_Check(value)) {
532 if (Py_VerboseFlag)
533 PySys_WriteStderr("# cleanup builtins\n");
534 _PyModule_Clear(value);
535 PyDict_SetItemString(modules, "builtins", Py_None);
536 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 /* Finally, clear and delete the modules directory */
539 PyDict_Clear(modules);
540 interp->modules = NULL;
541 Py_DECREF(modules);
542 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000543}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000544
545
Barry Warsaw28a691b2010-04-17 00:19:56 +0000546/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547
548long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000552}
553
554
Barry Warsaw28a691b2010-04-17 00:19:56 +0000555const char *
556PyImport_GetMagicTag(void)
557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000559}
560
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561/* Magic for extension modules (built-in as well as dynamically
562 loaded). To prevent initializing an extension module more than
563 once, we keep a static dictionary 'extensions' keyed by module name
564 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000565 modules), containing these modules. A copy of the module's
Victor Stinner49d3f252010-10-17 01:24:53 +0000566 dictionary is stored by calling _PyImport_FixupExtensionUnicode()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567 immediately after the module initialization function succeeds. A
568 copy can be retrieved from there by calling
Victor Stinner49d3f252010-10-17 01:24:53 +0000569 _PyImport_FindExtensionUnicode().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000571 Modules which do support multiple initialization set their m_size
572 field to a non-negative number (indicating the size of the
573 module-specific state). They are still recorded in the extensions
574 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000575*/
576
577int
Victor Stinner49d3f252010-10-17 01:24:53 +0000578_PyImport_FixupExtensionUnicode(PyObject *mod, char *name, PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyObject *modules, *dict;
581 struct PyModuleDef *def;
582 if (extensions == NULL) {
583 extensions = PyDict_New();
584 if (extensions == NULL)
585 return -1;
586 }
587 if (mod == NULL || !PyModule_Check(mod)) {
588 PyErr_BadInternalCall();
589 return -1;
590 }
591 def = PyModule_GetDef(mod);
592 if (!def) {
593 PyErr_BadInternalCall();
594 return -1;
595 }
596 modules = PyImport_GetModuleDict();
597 if (PyDict_SetItemString(modules, name, mod) < 0)
598 return -1;
599 if (_PyState_AddModule(mod, def) < 0) {
600 PyDict_DelItemString(modules, name);
601 return -1;
602 }
603 if (def->m_size == -1) {
604 if (def->m_base.m_copy) {
605 /* Somebody already imported the module,
606 likely under a different name.
607 XXX this should really not happen. */
608 Py_DECREF(def->m_base.m_copy);
609 def->m_base.m_copy = NULL;
610 }
611 dict = PyModule_GetDict(mod);
612 if (dict == NULL)
613 return -1;
614 def->m_base.m_copy = PyDict_Copy(dict);
615 if (def->m_base.m_copy == NULL)
616 return -1;
617 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000618 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620}
621
Victor Stinner49d3f252010-10-17 01:24:53 +0000622int
623_PyImport_FixupBuiltin(PyObject *mod, char *name)
624{
625 int res;
626 PyObject *filename;
627 filename = PyUnicode_FromString(name);
628 if (filename == NULL)
629 return -1;
630 res = _PyImport_FixupExtensionUnicode(mod, name, filename);
631 Py_DECREF(filename);
632 return res;
633}
634
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000636_PyImport_FindExtensionUnicode(const char *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *mod, *mdict;
639 PyModuleDef* def;
640 if (extensions == NULL)
641 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000642 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (def == NULL)
644 return NULL;
645 if (def->m_size == -1) {
646 /* Module does not support repeated initialization */
647 if (def->m_base.m_copy == NULL)
648 return NULL;
649 mod = PyImport_AddModule(name);
650 if (mod == NULL)
651 return NULL;
652 mdict = PyModule_GetDict(mod);
653 if (mdict == NULL)
654 return NULL;
655 if (PyDict_Update(mdict, def->m_base.m_copy))
656 return NULL;
657 }
658 else {
659 if (def->m_base.m_init == NULL)
660 return NULL;
661 mod = def->m_base.m_init();
662 if (mod == NULL)
663 return NULL;
664 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
665 Py_DECREF(mod);
666 }
667 if (_PyState_AddModule(mod, def) < 0) {
668 PyDict_DelItemString(PyImport_GetModuleDict(), name);
669 Py_DECREF(mod);
670 return NULL;
671 }
672 if (Py_VerboseFlag)
Victor Stinner49d3f252010-10-17 01:24:53 +0000673 PySys_FormatStderr("import %s # previously loaded (%U)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 name, filename);
675 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000676
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677}
678
Victor Stinner49d3f252010-10-17 01:24:53 +0000679PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000680_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000681{
682 PyObject *res, *filename;
683 filename = PyUnicode_FromString(name);
684 if (filename == NULL)
685 return NULL;
686 res = _PyImport_FindExtensionUnicode(name, filename);
687 Py_DECREF(filename);
688 return res;
689}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690
691/* Get the module object corresponding to a module name.
692 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000693 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000694 Because the former action is most common, THIS DOES NOT RETURN A
695 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696
Guido van Rossum79f25d91997-04-29 20:08:16 +0000697PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000698PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PyObject *modules = PyImport_GetModuleDict();
701 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702
Victor Stinner27ee0892011-03-04 12:57:09 +0000703 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyModule_Check(m))
705 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000706 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (m == NULL)
708 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000709 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(m);
711 return NULL;
712 }
713 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000716}
717
Victor Stinner27ee0892011-03-04 12:57:09 +0000718PyObject *
719PyImport_AddModule(const char *name)
720{
721 PyObject *nameobj, *module;
722 nameobj = PyUnicode_FromString(name);
723 if (nameobj == NULL)
724 return NULL;
725 module = PyImport_AddModuleObject(nameobj);
726 Py_DECREF(nameobj);
727 return module;
728}
729
730
Tim Peters1cd70172004-08-02 03:52:12 +0000731/* Remove name from sys.modules, if it's there. */
732static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000733remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000736 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000738 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 Py_FatalError("import: deleting existing key in"
740 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000741}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000742
Barry Warsaw28a691b2010-04-17 00:19:56 +0000743static PyObject * get_sourcefile(char *file);
744static char *make_source_pathname(char *pathname, char *buf);
745static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000747
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000748/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000749 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
750 * removed from sys.modules, to avoid leaving damaged module objects
751 * in sys.modules. The caller may wish to restore the original
752 * module object (if any) in this case; PyImport_ReloadModule is an
753 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000754 *
755 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
756 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000757 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000758PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000759PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 return PyImport_ExecCodeModuleWithPathnames(
762 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000763}
764
765PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000766PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 return PyImport_ExecCodeModuleWithPathnames(
769 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000770}
771
772PyObject *
773PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000775{
Victor Stinner27ee0892011-03-04 12:57:09 +0000776 PyObject *m = NULL;
777 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
778
779 nameobj = PyUnicode_FromString(name);
780 if (nameobj == NULL)
781 return NULL;
782
783 if (pathname != NULL) {
784 pathobj = PyUnicode_DecodeFSDefault(pathname);
785 if (pathobj == NULL)
786 goto error;
787 } else
788 pathobj = NULL;
789 if (cpathname != NULL) {
790 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
791 if (cpathobj == NULL)
792 goto error;
793 } else
794 cpathobj = NULL;
795 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
796error:
797 Py_DECREF(nameobj);
798 Py_XDECREF(pathobj);
799 Py_XDECREF(cpathobj);
800 return m;
801}
802
803PyObject*
804PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
805 PyObject *cpathname)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyObject *modules = PyImport_GetModuleDict();
808 PyObject *m, *d, *v;
Victor Stinner27ee0892011-03-04 12:57:09 +0000809 PyObject *pathbytes;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000810
Victor Stinner27ee0892011-03-04 12:57:09 +0000811 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (m == NULL)
813 return NULL;
814 /* If the module is being reloaded, we get the old module back
815 and re-use its dict to exec the new code. */
816 d = PyModule_GetDict(m);
817 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
818 if (PyDict_SetItemString(d, "__builtins__",
819 PyEval_GetBuiltins()) != 0)
820 goto error;
821 }
822 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (pathname != NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000824 pathbytes = PyUnicode_EncodeFSDefault(pathname);
825 if (pathbytes != NULL) {
826 v = get_sourcefile(PyBytes_AS_STRING(pathbytes));
827 Py_DECREF(pathbytes);
828 } else
829 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (v == NULL)
831 PyErr_Clear();
832 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000833 else
834 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (v == NULL) {
836 v = ((PyCodeObject *)co)->co_filename;
837 Py_INCREF(v);
838 }
839 if (PyDict_SetItemString(d, "__file__", v) != 0)
840 PyErr_Clear(); /* Not important enough to report */
841 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000844 if (cpathname != NULL)
845 v = cpathname;
846 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (PyDict_SetItemString(d, "__cached__", v) != 0)
849 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000850
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000851 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (v == NULL)
853 goto error;
854 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000855
Victor Stinner27ee0892011-03-04 12:57:09 +0000856 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000858 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 name);
860 return NULL;
861 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000866
867 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 remove_module(name);
869 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000870}
871
872
Barry Warsaw28a691b2010-04-17 00:19:56 +0000873/* Like strrchr(string, '/') but searches for the rightmost of either SEP
874 or ALTSEP, if the latter is defined.
875*/
876static char *
877rightmost_sep(char *s)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 char *found, c;
880 for (found = NULL; (c = *s); s++) {
881 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000882#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000884#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 )
886 {
887 found = s;
888 }
889 }
890 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000891}
892
893
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000894/* Given a pathname for a Python source file, fill a buffer with the
895 pathname for the corresponding compiled file. Return the pathname
896 for the compiled file, or NULL if there's no space in the buffer.
897 Doesn't set an exception. */
898
899static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000900make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* foo.py -> __pycache__/foo.<tag>.pyc */
903 size_t len = strlen(pathname);
904 size_t i, save;
905 char *pos;
906 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 /* Sanity check that the buffer has roughly enough space to hold what
909 will eventually be the full path to the compiled file. The 5 extra
910 bytes include the slash afer __pycache__, the two extra dots, the
911 extra trailing character ('c' or 'o') and null. This isn't exact
912 because the contents of the buffer can affect how many actual
913 characters of the string get into the buffer. We'll do a final
914 sanity check before writing the extension to ensure we do not
915 overflow the buffer.
916 */
917 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
918 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Find the last path separator and copy everything from the start of
921 the source string up to and including the separator.
922 */
923 if ((pos = rightmost_sep(pathname)) == NULL) {
924 i = 0;
925 }
926 else {
927 sep = *pos;
928 i = pos - pathname + 1;
929 strncpy(buf, pathname, i);
930 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 save = i;
933 buf[i++] = '\0';
934 /* Add __pycache__/ */
935 strcat(buf, CACHEDIR);
936 i += strlen(CACHEDIR) - 1;
937 buf[i++] = sep;
938 buf[i++] = '\0';
939 /* Add the base filename, but remove the .py or .pyw extension, since
940 the tag name must go before the extension.
941 */
942 strcat(buf, pathname + save);
943 if ((pos = strrchr(buf, '.')) != NULL)
944 *++pos = '\0';
945 strcat(buf, pyc_tag);
946 /* The length test above assumes that we're only adding one character
947 to the end of what would normally be the extension. What if there
948 is no extension, or the string ends in '.' or '.p', and otherwise
949 fills the buffer? By appending 4 more characters onto the string
950 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 As a simple example, let's say buflen=32 and the input string is
953 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 which is false and so the name mangling would continue. This would
958 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
963 We can even handle an input string of say 'xxxxx' above because
964 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
965 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 which is 32 characters including the nul, and thus fits in the
970 buffer. However, an input string of 'xxxxxx' would yield a result
971 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 which is 33 characters long (including the nul), thus overflowing
976 the buffer, even though the first test would fail, i.e.: the input
977 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 The reason the first test fails but we still overflow the buffer is
980 that the test above only expects to add one extra character to be
981 added to the extension, and here we're adding three (pyc). We
982 don't add the first dot, so that reclaims one of expected
983 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
984 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 The best we can do is ensure that we still have enough room in the
987 target buffer before we write the extension. Because it's always
988 only the extension that can cause the overflow, and never the other
989 path bytes we've written, it's sufficient to just do one more test
990 here. Still, the assertion that follows can't hurt.
991 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000992#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000994#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (strlen(buf) + 5 > buflen)
996 return NULL;
997 strcat(buf, debug ? ".pyc" : ".pyo");
998 assert(strlen(buf) < buflen);
999 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001000}
1001
1002
Barry Warsaw28a691b2010-04-17 00:19:56 +00001003/* Given a pathname to a Python byte compiled file, return the path to the
1004 source file, if the path matches the PEP 3147 format. This does not check
1005 for any file existence, however, if the pyc file name does not match PEP
1006 3147 style, NULL is returned. buf must be at least as big as pathname;
1007 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008
Barry Warsaw28a691b2010-04-17 00:19:56 +00001009static char *
1010make_source_pathname(char *pathname, char *buf)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 /* __pycache__/foo.<tag>.pyc -> foo.py */
1013 size_t i, j;
1014 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* Look back two slashes from the end. In between these two slashes
1017 must be the string __pycache__ or this is not a PEP 3147 style
1018 path. It's possible for there to be only one slash.
1019 */
1020 if ((right = rightmost_sep(pathname)) == NULL)
1021 return NULL;
1022 sep = *right;
1023 *right = '\0';
1024 left = rightmost_sep(pathname);
1025 *right = sep;
1026 if (left == NULL)
1027 left = pathname;
1028 else
1029 left++;
1030 if (right-left != strlen(CACHEDIR) ||
1031 strncmp(left, CACHEDIR, right-left) != 0)
1032 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 /* Now verify that the path component to the right of the last slash
1035 has two dots in it.
1036 */
1037 if ((dot0 = strchr(right + 1, '.')) == NULL)
1038 return NULL;
1039 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
1040 return NULL;
1041 /* Too many dots? */
1042 if (strchr(dot1 + 1, '.') != NULL)
1043 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* This is a PEP 3147 path. Start by copying everything from the
1046 start of pathname up to and including the leftmost slash. Then
1047 copy the file's basename, removing the magic tag and adding a .py
1048 suffix.
1049 */
1050 strncpy(buf, pathname, (i=left-pathname));
1051 strncpy(buf+i, right+1, (j=dot0-right));
1052 strcpy(buf+i+j, "py");
1053 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001054}
1055
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001056/* Given a pathname for a Python source file, its time of last
1057 modification, and a pathname for a compiled file, check whether the
1058 compiled file represents the same version of the source. If so,
1059 return a FILE pointer for the compiled file, positioned just after
1060 the header; if not, return NULL.
1061 Doesn't set an exception. */
1062
1063static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001064check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 FILE *fp;
1067 long magic;
1068 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 fp = fopen(cpathname, "rb");
1071 if (fp == NULL)
1072 return NULL;
1073 magic = PyMarshal_ReadLongFromFile(fp);
1074 if (magic != pyc_magic) {
1075 if (Py_VerboseFlag)
1076 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1077 fclose(fp);
1078 return NULL;
1079 }
1080 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1081 if (pyc_mtime != mtime) {
1082 if (Py_VerboseFlag)
1083 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1084 fclose(fp);
1085 return NULL;
1086 }
1087 if (Py_VerboseFlag)
1088 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1089 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001090}
1091
1092
1093/* Read a code object from a file and check it for validity */
1094
Guido van Rossum79f25d91997-04-29 20:08:16 +00001095static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001096read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 co = PyMarshal_ReadLastObjectFromFile(fp);
1101 if (co == NULL)
1102 return NULL;
1103 if (!PyCode_Check(co)) {
1104 PyErr_Format(PyExc_ImportError,
1105 "Non-code object in %.200s", cpathname);
1106 Py_DECREF(co);
1107 return NULL;
1108 }
1109 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001110}
1111
1112
1113/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001114 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001115
Guido van Rossum79f25d91997-04-29 20:08:16 +00001116static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001117load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 long magic;
1120 PyCodeObject *co;
1121 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 magic = PyMarshal_ReadLongFromFile(fp);
1124 if (magic != pyc_magic) {
1125 PyErr_Format(PyExc_ImportError,
1126 "Bad magic number in %.200s", cpathname);
1127 return NULL;
1128 }
1129 (void) PyMarshal_ReadLongFromFile(fp);
1130 co = read_compiled_module(cpathname, fp);
1131 if (co == NULL)
1132 return NULL;
1133 if (Py_VerboseFlag)
1134 PySys_WriteStderr("import %s # precompiled from %s\n",
1135 name, cpathname);
1136 m = PyImport_ExecCodeModuleWithPathnames(
1137 name, (PyObject *)co, cpathname, cpathname);
1138 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001141}
1142
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001143/* Parse a source file and return the corresponding code object */
1144
Guido van Rossum79f25d91997-04-29 20:08:16 +00001145static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001146parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyCodeObject *co = NULL;
1149 mod_ty mod;
1150 PyCompilerFlags flags;
1151 PyArena *arena = PyArena_New();
1152 if (arena == NULL)
1153 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 flags.cf_flags = 0;
1156 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1157 Py_file_input, 0, 0, &flags,
1158 NULL, arena);
1159 if (mod) {
1160 co = PyAST_Compile(mod, pathname, NULL, arena);
1161 }
1162 PyArena_Free(arena);
1163 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001164}
1165
1166
Guido van Rossum55a83382000-09-20 20:31:38 +00001167/* Helper to open a bytecode file for writing in exclusive mode */
1168
1169static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001170open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001171{
1172#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 /* Use O_EXCL to avoid a race condition when another process tries to
1174 write the same file. When that happens, our open() call fails,
1175 which is just fine (since it's only a cache).
1176 XXX If the file exists and is writable but the directory is not
1177 writable, the file will never be written. Oh well.
1178 */
1179 int fd;
1180 (void) unlink(filename);
1181 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001182#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001184#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001185#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001187#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001189#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 );
1191 if (fd < 0)
1192 return NULL;
1193 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001194#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 /* Best we can do -- on Windows this can't happen anyway */
1196 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001197#endif
1198}
1199
1200
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001201/* Write a compiled module to a file, placing the time of last
1202 modification of its source into the header.
1203 Errors are ignored, if a write error occurs an attempt is made to
1204 remove the file. */
1205
1206static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001207write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 FILE *fp;
1210 char *dirpath;
1211 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001212#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001214#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1216 mode_t dirmode = (srcstat->st_mode |
1217 S_IXUSR | S_IXGRP | S_IXOTH |
1218 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001219#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 /* Ensure that the __pycache__ directory exists. */
1223 dirpath = rightmost_sep(cpathname);
1224 if (dirpath == NULL) {
1225 if (Py_VerboseFlag)
1226 PySys_WriteStderr(
1227 "# no %s path found %s\n",
1228 CACHEDIR, cpathname);
1229 return;
1230 }
1231 saved = *dirpath;
1232 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001233
1234#ifdef MS_WINDOWS
1235 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1236#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001238#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 *dirpath = saved;
1240 if (Py_VerboseFlag)
1241 PySys_WriteStderr(
1242 "# cannot create cache dir %s\n", cpathname);
1243 return;
1244 }
1245 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 fp = open_exclusive(cpathname, mode);
1248 if (fp == NULL) {
1249 if (Py_VerboseFlag)
1250 PySys_WriteStderr(
1251 "# can't create %s\n", cpathname);
1252 return;
1253 }
1254 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1255 /* First write a 0 for mtime */
1256 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1257 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1258 if (fflush(fp) != 0 || ferror(fp)) {
1259 if (Py_VerboseFlag)
1260 PySys_WriteStderr("# can't write %s\n", cpathname);
1261 /* Don't keep partial file */
1262 fclose(fp);
1263 (void) unlink(cpathname);
1264 return;
1265 }
1266 /* Now write the true mtime */
1267 fseek(fp, 4L, 0);
1268 assert(mtime < LONG_MAX);
1269 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1270 fflush(fp);
1271 fclose(fp);
1272 if (Py_VerboseFlag)
1273 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001274}
1275
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001276static void
1277update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 PyObject *constants, *tmp;
1280 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (PyUnicode_Compare(co->co_filename, oldname))
1283 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 tmp = co->co_filename;
1286 co->co_filename = newname;
1287 Py_INCREF(co->co_filename);
1288 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 constants = co->co_consts;
1291 n = PyTuple_GET_SIZE(constants);
1292 for (i = 0; i < n; i++) {
1293 tmp = PyTuple_GET_ITEM(constants, i);
1294 if (PyCode_Check(tmp))
1295 update_code_filenames((PyCodeObject *)tmp,
1296 oldname, newname);
1297 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001298}
1299
1300static int
1301update_compiled_module(PyCodeObject *co, char *pathname)
1302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 newname = PyUnicode_DecodeFSDefault(pathname);
1306 if (newname == NULL)
1307 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (!PyUnicode_Compare(co->co_filename, newname)) {
1310 Py_DECREF(newname);
1311 return 0;
1312 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 oldname = co->co_filename;
1315 Py_INCREF(oldname);
1316 update_code_filenames(co, oldname, newname);
1317 Py_DECREF(oldname);
1318 Py_DECREF(newname);
1319 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001320}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001321
1322/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001323 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1324 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001325
Guido van Rossum79f25d91997-04-29 20:08:16 +00001326static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001327load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 struct stat st;
1330 FILE *fpc;
1331 char buf[MAXPATHLEN+1];
1332 char *cpathname;
1333 PyCodeObject *co;
1334 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (fstat(fileno(fp), &st) != 0) {
1337 PyErr_Format(PyExc_RuntimeError,
1338 "unable to get file status from '%s'",
1339 pathname);
1340 return NULL;
1341 }
Fred Drake4c82b232000-06-30 16:18:57 +00001342#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 /* Python's .pyc timestamp handling presumes that the timestamp fits
1344 in 4 bytes. This will be fine until sometime in the year 2038,
1345 when a 4-byte signed time_t will overflow.
1346 */
1347 if (st.st_mtime >> 32) {
1348 PyErr_SetString(PyExc_OverflowError,
1349 "modification time overflows a 4 byte field");
1350 return NULL;
1351 }
Fred Drake4c82b232000-06-30 16:18:57 +00001352#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 cpathname = make_compiled_pathname(
1354 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1355 if (cpathname != NULL &&
1356 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1357 co = read_compiled_module(cpathname, fpc);
1358 fclose(fpc);
1359 if (co == NULL)
1360 return NULL;
1361 if (update_compiled_module(co, pathname) < 0)
1362 return NULL;
1363 if (Py_VerboseFlag)
1364 PySys_WriteStderr("import %s # precompiled from %s\n",
1365 name, cpathname);
1366 pathname = cpathname;
1367 }
1368 else {
1369 co = parse_source_module(pathname, fp);
1370 if (co == NULL)
1371 return NULL;
1372 if (Py_VerboseFlag)
1373 PySys_WriteStderr("import %s # from %s\n",
1374 name, pathname);
1375 if (cpathname) {
1376 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1377 if (ro == NULL || !PyObject_IsTrue(ro))
1378 write_compiled_module(co, cpathname, &st);
1379 }
1380 }
1381 m = PyImport_ExecCodeModuleWithPathnames(
1382 name, (PyObject *)co, pathname, cpathname);
1383 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001386}
1387
Christian Heimes3b06e532008-01-07 20:12:44 +00001388/* Get source file -> unicode or None
1389 * Returns the path to the py file if available, else the given path
1390 */
1391static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001392get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 char py[MAXPATHLEN + 1];
1395 Py_ssize_t len;
1396 PyObject *u;
1397 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 if (!file || !*file) {
1400 Py_RETURN_NONE;
1401 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 len = strlen(file);
1404 /* match '*.py?' */
1405 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1406 return PyUnicode_DecodeFSDefault(file);
1407 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 /* Start by trying to turn PEP 3147 path into source path. If that
1410 * fails, just chop off the trailing character, i.e. legacy pyc path
1411 * to py.
1412 */
1413 if (make_source_pathname(file, py) == NULL) {
1414 strncpy(py, file, len-1);
1415 py[len-1] = '\0';
1416 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (stat(py, &statbuf) == 0 &&
1419 S_ISREG(statbuf.st_mode)) {
1420 u = PyUnicode_DecodeFSDefault(py);
1421 }
1422 else {
1423 u = PyUnicode_DecodeFSDefault(file);
1424 }
1425 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001426}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001427
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001428/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001429static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1430static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 char *, size_t, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001432static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001433
1434/* Load a package and return its module object WITH INCREMENTED
1435 REFERENCE COUNT */
1436
1437static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001438load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 PyObject *m, *d;
1441 PyObject *file = NULL;
1442 PyObject *path = NULL;
1443 int err;
1444 char buf[MAXPATHLEN+1];
1445 FILE *fp = NULL;
1446 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 m = PyImport_AddModule(name);
1449 if (m == NULL)
1450 return NULL;
1451 if (Py_VerboseFlag)
1452 PySys_WriteStderr("import %s # directory %s\n",
1453 name, pathname);
1454 d = PyModule_GetDict(m);
1455 file = get_sourcefile(pathname);
1456 if (file == NULL)
1457 goto error;
1458 path = Py_BuildValue("[O]", file);
1459 if (path == NULL)
1460 goto error;
1461 err = PyDict_SetItemString(d, "__file__", file);
1462 if (err == 0)
1463 err = PyDict_SetItemString(d, "__path__", path);
1464 if (err != 0)
1465 goto error;
1466 buf[0] = '\0';
1467 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1468 if (fdp == NULL) {
1469 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1470 PyErr_Clear();
1471 Py_INCREF(m);
1472 }
1473 else
1474 m = NULL;
1475 goto cleanup;
1476 }
1477 m = load_module(name, fp, buf, fdp->type, NULL);
1478 if (fp != NULL)
1479 fclose(fp);
1480 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001481
1482 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001484 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_XDECREF(path);
1486 Py_XDECREF(file);
1487 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001488}
1489
1490
1491/* Helper to test for built-in module */
1492
1493static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001494is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 int i;
1497 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1498 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1499 if (PyImport_Inittab[i].initfunc == NULL)
1500 return -1;
1501 else
1502 return 1;
1503 }
1504 }
1505 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001506}
1507
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001508
Just van Rossum52e14d62002-12-30 22:08:05 +00001509/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1510 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001511 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001512 that can handle the path item. Return None if no hook could;
1513 this tells our caller it should fall back to the builtin
1514 import mechanism. Cache the result in path_importer_cache.
1515 Returns a borrowed reference. */
1516
1517static PyObject *
1518get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 PyObject *importer;
1522 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 /* These conditions are the caller's responsibility: */
1525 assert(PyList_Check(path_hooks));
1526 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 nhooks = PyList_Size(path_hooks);
1529 if (nhooks < 0)
1530 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 importer = PyDict_GetItem(path_importer_cache, p);
1533 if (importer != NULL)
1534 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 /* set path_importer_cache[p] to None to avoid recursion */
1537 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1538 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 for (j = 0; j < nhooks; j++) {
1541 PyObject *hook = PyList_GetItem(path_hooks, j);
1542 if (hook == NULL)
1543 return NULL;
1544 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1545 if (importer != NULL)
1546 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1549 return NULL;
1550 }
1551 PyErr_Clear();
1552 }
1553 if (importer == NULL) {
1554 importer = PyObject_CallFunctionObjArgs(
1555 (PyObject *)&PyNullImporter_Type, p, NULL
1556 );
1557 if (importer == NULL) {
1558 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1559 PyErr_Clear();
1560 return Py_None;
1561 }
1562 }
1563 }
1564 if (importer != NULL) {
1565 int err = PyDict_SetItem(path_importer_cache, p, importer);
1566 Py_DECREF(importer);
1567 if (err != 0)
1568 return NULL;
1569 }
1570 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001571}
1572
Christian Heimes9cd17752007-11-18 19:35:23 +00001573PyAPI_FUNC(PyObject *)
1574PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1578 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1579 importer = get_path_importer(path_importer_cache,
1580 path_hooks, path);
1581 }
1582 }
1583 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1584 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001585}
1586
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001587/* Search the path (default sys.path) for a module. Return the
1588 corresponding filedescr struct, and (via return arguments) the
1589 pathname and an open file. Return NULL if the module is not found. */
1590
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001591#ifdef MS_COREDLL
Victor Stinner9b99b442011-02-22 23:12:28 +00001592extern FILE *_PyWin_FindRegisteredModule(const char *, struct filedescr **,
1593 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001594#endif
1595
Martin v. Löwis18e16552006-02-15 17:27:45 +00001596static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001597static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001598static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001599
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001600static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001601find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 Py_ssize_t i, npath;
1605 size_t len, namelen;
1606 struct filedescr *fdp = NULL;
1607 char *filemode;
1608 FILE *fp = NULL;
1609 PyObject *path_hooks, *path_importer_cache;
1610 struct stat statbuf;
1611 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1612 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1613 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1614 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001615#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 size_t saved_len;
1617 size_t saved_namelen;
1618 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001619#endif
Victor Stinner53dc7352011-03-20 01:50:21 +01001620 PyObject *fullname_obj;
1621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (p_loader != NULL)
1623 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (strlen(subname) > MAXPATHLEN) {
1626 PyErr_SetString(PyExc_OverflowError,
1627 "module name is too long");
1628 return NULL;
1629 }
1630 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 /* sys.meta_path import hook */
1633 if (p_loader != NULL) {
1634 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 meta_path = PySys_GetObject("meta_path");
1637 if (meta_path == NULL || !PyList_Check(meta_path)) {
1638 PyErr_SetString(PyExc_ImportError,
1639 "sys.meta_path must be a list of "
1640 "import hooks");
1641 return NULL;
1642 }
1643 Py_INCREF(meta_path); /* zap guard */
1644 npath = PyList_Size(meta_path);
1645 for (i = 0; i < npath; i++) {
1646 PyObject *loader;
1647 PyObject *hook = PyList_GetItem(meta_path, i);
1648 loader = PyObject_CallMethod(hook, "find_module",
1649 "sO", fullname,
1650 path != NULL ?
1651 path : Py_None);
1652 if (loader == NULL) {
1653 Py_DECREF(meta_path);
1654 return NULL; /* true error */
1655 }
1656 if (loader != Py_None) {
1657 /* a loader was found */
1658 *p_loader = loader;
1659 Py_DECREF(meta_path);
1660 return &importhookdescr;
1661 }
1662 Py_DECREF(loader);
1663 }
1664 Py_DECREF(meta_path);
1665 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001666
Victor Stinner53dc7352011-03-20 01:50:21 +01001667 if (fullname != NULL) {
1668 fullname_obj = PyUnicode_FromString(fullname);
1669 if (fullname == NULL)
1670 return NULL;
1671 if (find_frozen(fullname_obj) != NULL) {
1672 Py_DECREF(fullname_obj);
1673 strcpy(buf, fullname);
1674 return &fd_frozen;
1675 }
1676 Py_DECREF(fullname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (path == NULL) {
1680 if (is_builtin(name)) {
1681 strcpy(buf, name);
1682 return &fd_builtin;
1683 }
Guido van Rossumac279101996-08-22 23:10:58 +00001684#ifdef MS_COREDLL
Victor Stinner9b99b442011-02-22 23:12:28 +00001685 fp = _PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (fp != NULL) {
1687 *p_fp = fp;
1688 return fdp;
1689 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001690#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 path = PySys_GetObject("path");
1692 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (path == NULL || !PyList_Check(path)) {
1695 PyErr_SetString(PyExc_ImportError,
1696 "sys.path must be a list of directory names");
1697 return NULL;
1698 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 path_hooks = PySys_GetObject("path_hooks");
1701 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1702 PyErr_SetString(PyExc_ImportError,
1703 "sys.path_hooks must be a list of "
1704 "import hooks");
1705 return NULL;
1706 }
1707 path_importer_cache = PySys_GetObject("path_importer_cache");
1708 if (path_importer_cache == NULL ||
1709 !PyDict_Check(path_importer_cache)) {
1710 PyErr_SetString(PyExc_ImportError,
1711 "sys.path_importer_cache must be a dict");
1712 return NULL;
1713 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 npath = PyList_Size(path);
1716 namelen = strlen(name);
1717 for (i = 0; i < npath; i++) {
1718 PyObject *v = PyList_GetItem(path, i);
1719 PyObject *origv = v;
1720 const char *base;
1721 Py_ssize_t size;
1722 if (!v)
1723 return NULL;
1724 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001725 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (v == NULL)
1727 return NULL;
1728 }
1729 else if (!PyBytes_Check(v))
1730 continue;
1731 else
1732 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 base = PyBytes_AS_STRING(v);
1735 size = PyBytes_GET_SIZE(v);
1736 len = size;
1737 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1738 Py_DECREF(v);
1739 continue; /* Too long */
1740 }
1741 strcpy(buf, base);
1742 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (strlen(buf) != len) {
1745 continue; /* v contains '\0' */
1746 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 /* sys.path_hooks import hook */
1749 if (p_loader != NULL) {
1750 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 importer = get_path_importer(path_importer_cache,
1753 path_hooks, origv);
1754 if (importer == NULL) {
1755 return NULL;
1756 }
1757 /* Note: importer is a borrowed reference */
1758 if (importer != Py_None) {
1759 PyObject *loader;
1760 loader = PyObject_CallMethod(importer,
1761 "find_module",
1762 "s", fullname);
1763 if (loader == NULL)
1764 return NULL; /* error */
1765 if (loader != Py_None) {
1766 /* a loader was found */
1767 *p_loader = loader;
1768 return &importhookdescr;
1769 }
1770 Py_DECREF(loader);
1771 continue;
1772 }
1773 }
1774 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001777#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001779#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 )
1781 buf[len++] = SEP;
1782 strcpy(buf+len, name);
1783 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* Check for package import (buf holds a directory name,
1786 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001787#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (stat(buf, &statbuf) == 0 && /* it exists */
1789 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1790 case_ok(buf, len, namelen, name)) { /* case matches */
1791 if (find_init_module(buf)) { /* and has __init__.py */
1792 return &fd_package;
1793 }
1794 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001795 int err;
1796 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1797 if (unicode == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return NULL;
Victor Stinnered7916d2010-10-17 02:07:09 +00001799 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1800 "Not importing directory '%U': missing __init__.py",
1801 unicode);
1802 Py_DECREF(unicode);
1803 if (err)
1804 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 }
1806 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001807#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001808#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 /* take a snapshot of the module spec for restoration
1810 * after the 8 character DLL hackery
1811 */
1812 saved_buf = strdup(buf);
1813 saved_len = len;
1814 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001815#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001817#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 /* OS/2 limits DLLs to 8 character names (w/o
1819 extension)
1820 * so if the name is longer than that and its a
1821 * dynamically loaded module we're going to try,
1822 * truncate the name before trying
1823 */
1824 if (strlen(subname) > 8) {
1825 /* is this an attempt to load a C extension? */
1826 const struct filedescr *scan;
1827 scan = _PyImport_DynLoadFiletab;
1828 while (scan->suffix != NULL) {
1829 if (!strcmp(scan->suffix, fdp->suffix))
1830 break;
1831 else
1832 scan++;
1833 }
1834 if (scan->suffix != NULL) {
1835 /* yes, so truncate the name */
1836 namelen = 8;
1837 len -= strlen(subname) - namelen;
1838 buf[len] = '\0';
1839 }
1840 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001841#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 strcpy(buf+len, fdp->suffix);
1843 if (Py_VerboseFlag > 1)
1844 PySys_WriteStderr("# trying %s\n", buf);
1845 filemode = fdp->mode;
1846 if (filemode[0] == 'U')
1847 filemode = "r" PY_STDIOTEXTMODE;
1848 fp = fopen(buf, filemode);
1849 if (fp != NULL) {
1850 if (case_ok(buf, len, namelen, name))
1851 break;
1852 else { /* continue search */
1853 fclose(fp);
1854 fp = NULL;
1855 }
1856 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001857#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* restore the saved snapshot */
1859 strcpy(buf, saved_buf);
1860 len = saved_len;
1861 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001864#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* don't need/want the module name snapshot anymore */
1866 if (saved_buf)
1867 {
1868 free(saved_buf);
1869 saved_buf = NULL;
1870 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001871#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (fp != NULL)
1873 break;
1874 }
1875 if (fp == NULL) {
1876 PyErr_Format(PyExc_ImportError,
1877 "No module named %.200s", name);
1878 return NULL;
1879 }
1880 *p_fp = fp;
1881 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001882}
1883
Martin v. Löwis18e16552006-02-15 17:27:45 +00001884/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001885 * The arguments here are tricky, best shown by example:
1886 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1887 * ^ ^ ^ ^
1888 * |--------------------- buf ---------------------|
1889 * |------------------- len ------------------|
1890 * |------ name -------|
1891 * |----- namelen -----|
1892 * buf is the full path, but len only counts up to (& exclusive of) the
1893 * extension. name is the module name, also exclusive of extension.
1894 *
1895 * We've already done a successful stat() or fopen() on buf, so know that
1896 * there's some match, possibly case-insensitive.
1897 *
Tim Peters50d8d372001-02-28 05:34:27 +00001898 * case_ok() is to return 1 if there's a case-sensitive match for
1899 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1900 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001901 *
Tim Peters50d8d372001-02-28 05:34:27 +00001902 * case_ok() is used to implement case-sensitive import semantics even
1903 * on platforms with case-insensitive filesystems. It's trivial to implement
1904 * for case-sensitive filesystems. It's pretty much a cross-platform
1905 * nightmare for systems with case-insensitive filesystems.
1906 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001907
Tim Peters50d8d372001-02-28 05:34:27 +00001908/* First we may need a pile of platform-specific header files; the sequence
1909 * of #if's here should match the sequence in the body of case_ok().
1910 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001911#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001912#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001913
Tim Peters50d8d372001-02-28 05:34:27 +00001914#elif defined(DJGPP)
1915#include <dir.h>
1916
Jason Tishler7961aa62005-05-20 00:56:54 +00001917#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001918#include <sys/types.h>
1919#include <dirent.h>
1920
Andrew MacIntyred9400542002-02-26 11:41:34 +00001921#elif defined(PYOS_OS2)
1922#define INCL_DOS
1923#define INCL_DOSERRORS
1924#define INCL_NOPMAPI
1925#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001926#endif
1927
Guido van Rossum0980bd91998-02-13 17:18:36 +00001928static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001929case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001930{
Tim Peters50d8d372001-02-28 05:34:27 +00001931/* Pick a platform-specific implementation; the sequence of #if's here should
1932 * match the sequence just above.
1933 */
1934
Jason Tishler7961aa62005-05-20 00:56:54 +00001935/* MS_WINDOWS */
1936#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 WIN32_FIND_DATA data;
1938 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (Py_GETENV("PYTHONCASEOK") != NULL)
1941 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 h = FindFirstFile(buf, &data);
1944 if (h == INVALID_HANDLE_VALUE) {
1945 PyErr_Format(PyExc_NameError,
1946 "Can't find file for module %.100s\n(filename %.300s)",
1947 name, buf);
1948 return 0;
1949 }
1950 FindClose(h);
1951 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001952
1953/* DJGPP */
1954#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 struct ffblk ffblk;
1956 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (Py_GETENV("PYTHONCASEOK") != NULL)
1959 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1962 if (done) {
1963 PyErr_Format(PyExc_NameError,
1964 "Can't find file for module %.100s\n(filename %.300s)",
1965 name, buf);
1966 return 0;
1967 }
1968 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001969
Jason Tishler7961aa62005-05-20 00:56:54 +00001970/* new-fangled macintosh (macosx) or Cygwin */
1971#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 DIR *dirp;
1973 struct dirent *dp;
1974 char dirname[MAXPATHLEN + 1];
1975 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (Py_GETENV("PYTHONCASEOK") != NULL)
1978 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 /* Copy the dir component into dirname; substitute "." if empty */
1981 if (dirlen <= 0) {
1982 dirname[0] = '.';
1983 dirname[1] = '\0';
1984 }
1985 else {
1986 assert(dirlen <= MAXPATHLEN);
1987 memcpy(dirname, buf, dirlen);
1988 dirname[dirlen] = '\0';
1989 }
1990 /* Open the directory and search the entries for an exact match. */
1991 dirp = opendir(dirname);
1992 if (dirp) {
1993 char *nameWithExt = buf + len - namelen;
1994 while ((dp = readdir(dirp)) != NULL) {
1995 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001996#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001998#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002000#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (thislen >= namelen &&
2002 strcmp(dp->d_name, nameWithExt) == 0) {
2003 (void)closedir(dirp);
2004 return 1; /* Found */
2005 }
2006 }
2007 (void)closedir(dirp);
2008 }
2009 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002010
Andrew MacIntyred9400542002-02-26 11:41:34 +00002011/* OS/2 */
2012#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 HDIR hdir = 1;
2014 ULONG srchcnt = 1;
2015 FILEFINDBUF3 ffbuf;
2016 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (Py_GETENV("PYTHONCASEOK") != NULL)
2019 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 rc = DosFindFirst(buf,
2022 &hdir,
2023 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2024 &ffbuf, sizeof(ffbuf),
2025 &srchcnt,
2026 FIL_STANDARD);
2027 if (rc != NO_ERROR)
2028 return 0;
2029 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002030
Tim Peters50d8d372001-02-28 05:34:27 +00002031/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2032#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002034
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002035#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002036}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002037
Guido van Rossum197346f1997-10-31 18:38:52 +00002038#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002039
Guido van Rossum197346f1997-10-31 18:38:52 +00002040/* Helper to look for __init__.py or __init__.py[co] in potential package */
2041static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002042find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 const size_t save_len = strlen(buf);
2045 size_t i = save_len;
2046 char *pname; /* pointer to start of __init__ */
2047 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049/* For calling case_ok(buf, len, namelen, name):
2050 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2051 * ^ ^ ^ ^
2052 * |--------------------- buf ---------------------|
2053 * |------------------- len ------------------|
2054 * |------ name -------|
2055 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002056 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (save_len + 13 >= MAXPATHLEN)
2058 return 0;
2059 buf[i++] = SEP;
2060 pname = buf + i;
2061 strcpy(pname, "__init__.py");
2062 if (stat(buf, &statbuf) == 0) {
2063 if (case_ok(buf,
2064 save_len + 9, /* len("/__init__") */
2065 8, /* len("__init__") */
2066 pname)) {
2067 buf[save_len] = '\0';
2068 return 1;
2069 }
2070 }
2071 i += strlen(pname);
2072 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2073 if (stat(buf, &statbuf) == 0) {
2074 if (case_ok(buf,
2075 save_len + 9, /* len("/__init__") */
2076 8, /* len("__init__") */
2077 pname)) {
2078 buf[save_len] = '\0';
2079 return 1;
2080 }
2081 }
2082 buf[save_len] = '\0';
2083 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002084}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002085
Guido van Rossum197346f1997-10-31 18:38:52 +00002086#endif /* HAVE_STAT */
2087
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002088
Tim Petersdbd9ba62000-07-09 03:09:57 +00002089static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002090
Victor Stinner44c6c152010-08-09 00:59:10 +00002091static PyObject*
2092load_builtin(char *name, char *pathname, int type)
2093{
2094 PyObject *m, *modules;
2095 int err;
2096
2097 if (pathname != NULL && pathname[0] != '\0')
2098 name = pathname;
2099
2100 if (type == C_BUILTIN)
2101 err = init_builtin(name);
2102 else
2103 err = PyImport_ImportFrozenModule(name);
2104 if (err < 0)
2105 return NULL;
2106 if (err == 0) {
2107 PyErr_Format(PyExc_ImportError,
2108 "Purported %s module %.200s not found",
2109 type == C_BUILTIN ?
2110 "builtin" : "frozen",
2111 name);
2112 return NULL;
2113 }
2114
2115 modules = PyImport_GetModuleDict();
2116 m = PyDict_GetItemString(modules, name);
2117 if (m == NULL) {
2118 PyErr_Format(
2119 PyExc_ImportError,
2120 "%s module %.200s not properly initialized",
2121 type == C_BUILTIN ?
2122 "builtin" : "frozen",
2123 name);
2124 return NULL;
2125 }
2126 Py_INCREF(m);
2127 return m;
2128}
2129
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002130/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002131 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002132
Guido van Rossum79f25d91997-04-29 20:08:16 +00002133static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002134load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 /* First check that there's an open file (if we need one) */
2139 switch (type) {
2140 case PY_SOURCE:
2141 case PY_COMPILED:
2142 if (fp == NULL) {
2143 PyErr_Format(PyExc_ValueError,
2144 "file object required for import (type code %d)",
2145 type);
2146 return NULL;
2147 }
2148 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 case PY_SOURCE:
2153 m = load_source_module(name, pathname, fp);
2154 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 case PY_COMPILED:
2157 m = load_compiled_module(name, pathname, fp);
2158 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002159
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002160#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 case C_EXTENSION:
2162 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2163 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002164#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 case PKG_DIRECTORY:
2167 m = load_package(name, pathname);
2168 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 case C_BUILTIN:
2171 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002172 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 case IMP_HOOK: {
2176 if (loader == NULL) {
2177 PyErr_SetString(PyExc_ImportError,
2178 "import hook without loader");
2179 return NULL;
2180 }
2181 m = PyObject_CallMethod(loader, "load_module", "s", name);
2182 break;
2183 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 default:
2186 PyErr_Format(PyExc_ImportError,
2187 "Don't know how to import %.200s (type code %d)",
2188 name, type);
2189 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002194}
2195
2196
2197/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002198 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002199 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002200
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002201static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002202init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002205
Victor Stinner49d3f252010-10-17 01:24:53 +00002206 if (_PyImport_FindBuiltin(name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 for (p = PyImport_Inittab; p->name != NULL; p++) {
2210 PyObject *mod;
2211 if (strcmp(name, p->name) == 0) {
2212 if (p->initfunc == NULL) {
2213 PyErr_Format(PyExc_ImportError,
2214 "Cannot re-init internal module %.200s",
2215 name);
2216 return -1;
2217 }
2218 if (Py_VerboseFlag)
2219 PySys_WriteStderr("import %s # builtin\n", name);
2220 mod = (*p->initfunc)();
2221 if (mod == 0)
2222 return -1;
Victor Stinner49d3f252010-10-17 01:24:53 +00002223 if (_PyImport_FixupBuiltin(mod, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 return -1;
2225 /* FixupExtension has put the module into sys.modules,
2226 so we can release our own reference. */
2227 Py_DECREF(mod);
2228 return 1;
2229 }
2230 }
2231 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002232}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002233
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002234
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002235/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002236
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002237static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002238find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002241
Victor Stinner53dc7352011-03-20 01:50:21 +01002242 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 for (p = PyImport_FrozenModules; ; p++) {
2246 if (p->name == NULL)
2247 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002248 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 break;
2250 }
2251 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002252}
2253
Guido van Rossum79f25d91997-04-29 20:08:16 +00002254static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002255get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 struct _frozen *p = find_frozen(name);
2258 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if (p == NULL) {
2261 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002262 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 name);
2264 return NULL;
2265 }
2266 if (p->code == NULL) {
2267 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002268 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 name);
2270 return NULL;
2271 }
2272 size = p->size;
2273 if (size < 0)
2274 size = -size;
2275 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002276}
2277
Brett Cannon8d110132009-03-15 02:20:16 +00002278static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002279is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 struct _frozen *p = find_frozen(name);
2282 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (p == NULL) {
2285 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002286 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 name);
2288 return NULL;
2289 }
Brett Cannon8d110132009-03-15 02:20:16 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 if (size < 0)
2294 Py_RETURN_TRUE;
2295 else
2296 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002297}
2298
2299
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002300/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002301 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002302 an exception set if the initialization failed.
2303 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002304
2305int
Victor Stinner53dc7352011-03-20 01:50:21 +01002306PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002307{
Victor Stinner53dc7352011-03-20 01:50:21 +01002308 struct _frozen *p;
2309 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 int ispackage;
2311 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002312
Victor Stinner53dc7352011-03-20 01:50:21 +01002313 p = find_frozen(name);
2314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (p == NULL)
2316 return 0;
2317 if (p->code == NULL) {
2318 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002319 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 name);
2321 return -1;
2322 }
2323 size = p->size;
2324 ispackage = (size < 0);
2325 if (ispackage)
2326 size = -size;
2327 if (Py_VerboseFlag)
Victor Stinner53dc7352011-03-20 01:50:21 +01002328 PySys_FormatStderr("import %U # frozen%s\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 name, ispackage ? " package" : "");
2330 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2331 if (co == NULL)
2332 return -1;
2333 if (!PyCode_Check(co)) {
2334 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002335 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 name);
2337 goto err_return;
2338 }
2339 if (ispackage) {
2340 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002341 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002343 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (m == NULL)
2345 goto err_return;
2346 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 l = PyList_New(1);
2348 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 goto err_return;
2350 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002351 Py_INCREF(name);
2352 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 err = PyDict_SetItemString(d, "__path__", l);
2354 Py_DECREF(l);
2355 if (err != 0)
2356 goto err_return;
2357 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002358 path = PyUnicode_FromString("<frozen>");
2359 if (path == NULL)
2360 goto err_return;
2361 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2362 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (m == NULL)
2364 goto err_return;
2365 Py_DECREF(co);
2366 Py_DECREF(m);
2367 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002368err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 Py_DECREF(co);
2370 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002371}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002372
Victor Stinner53dc7352011-03-20 01:50:21 +01002373int
2374PyImport_ImportFrozenModule(char *name)
2375{
2376 PyObject *nameobj;
2377 int ret;
2378 nameobj = PyUnicode_InternFromString(name);
2379 if (nameobj == NULL)
2380 return -1;
2381 ret = PyImport_ImportFrozenModuleObject(nameobj);
2382 Py_DECREF(nameobj);
2383 return ret;
2384}
2385
Guido van Rossum74e6a111994-08-29 12:54:38 +00002386
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002387/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002388 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002389
Guido van Rossum79f25d91997-04-29 20:08:16 +00002390PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002391PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 PyObject *pname;
2394 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 pname = PyUnicode_FromString(name);
2397 if (pname == NULL)
2398 return NULL;
2399 result = PyImport_Import(pname);
2400 Py_DECREF(pname);
2401 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002402}
2403
Christian Heimes072c0f12008-01-03 23:01:04 +00002404/* Import a module without blocking
2405 *
2406 * At first it tries to fetch the module from sys.modules. If the module was
2407 * never loaded before it loads it with PyImport_ImportModule() unless another
2408 * thread holds the import lock. In the latter case the function raises an
2409 * ImportError instead of blocking.
2410 *
2411 * Returns the module object with incremented ref count.
2412 */
2413PyObject *
2414PyImport_ImportModuleNoBlock(const char *name)
2415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 PyObject *result;
2417 PyObject *modules;
2418 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 /* Try to get the module from sys.modules[name] */
2421 modules = PyImport_GetModuleDict();
2422 if (modules == NULL)
2423 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 result = PyDict_GetItemString(modules, name);
2426 if (result != NULL) {
2427 Py_INCREF(result);
2428 return result;
2429 }
2430 else {
2431 PyErr_Clear();
2432 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002433#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 /* check the import lock
2435 * me might be -1 but I ignore the error here, the lock function
2436 * takes care of the problem */
2437 me = PyThread_get_thread_ident();
2438 if (import_lock_thread == -1 || import_lock_thread == me) {
2439 /* no thread or me is holding the lock */
2440 return PyImport_ImportModule(name);
2441 }
2442 else {
2443 PyErr_Format(PyExc_ImportError,
2444 "Failed to import %.200s because the import lock"
2445 "is held by another thread.",
2446 name);
2447 return NULL;
2448 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002449#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002451#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002452}
2453
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002454/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002455static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002457static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002459static int mark_miss(char *name);
2460static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002462static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002463
2464/* The Magnum Opus of dotted-name import :-) */
2465
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002466static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002467import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 char buf[MAXPATHLEN+1];
2471 Py_ssize_t buflen = 0;
2472 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002475#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002477#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 ) {
2479 PyErr_SetString(PyExc_ImportError,
2480 "Import by filename is not supported.");
2481 return NULL;
2482 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 parent = get_parent(globals, buf, &buflen, level);
2485 if (parent == NULL)
2486 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002487
Benjamin Peterson556d8002010-06-27 22:37:28 +00002488 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2489 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 if (head == NULL)
2491 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 tail = head;
2494 Py_INCREF(tail);
2495 while (name) {
2496 next = load_next(tail, tail, &name, buf, &buflen);
2497 Py_DECREF(tail);
2498 if (next == NULL) {
2499 Py_DECREF(head);
2500 return NULL;
2501 }
2502 tail = next;
2503 }
2504 if (tail == Py_None) {
2505 /* If tail is Py_None, both get_parent and load_next found
2506 an empty module name: someone called __import__("") or
2507 doctored faulty bytecode */
2508 Py_DECREF(tail);
2509 Py_DECREF(head);
2510 PyErr_SetString(PyExc_ValueError,
2511 "Empty module name");
2512 return NULL;
2513 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 if (fromlist != NULL) {
2516 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2517 fromlist = NULL;
2518 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if (fromlist == NULL) {
2521 Py_DECREF(tail);
2522 return head;
2523 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 Py_DECREF(head);
2526 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2527 Py_DECREF(tail);
2528 return NULL;
2529 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002532}
2533
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002534PyObject *
2535PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 PyObject *result;
2539 _PyImport_AcquireLock();
2540 result = import_module_level(name, globals, locals, fromlist, level);
2541 if (_PyImport_ReleaseLock() < 0) {
2542 Py_XDECREF(result);
2543 PyErr_SetString(PyExc_RuntimeError,
2544 "not holding the import lock");
2545 return NULL;
2546 }
2547 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002548}
2549
Fred Drake87590902004-05-28 20:21:36 +00002550/* Return the package that an import is being performed in. If globals comes
2551 from the module foo.bar.bat (not itself a package), this returns the
2552 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002553 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002554
2555 The *name* of the returned package is returned in buf, with the length of
2556 the name in *p_buflen.
2557
2558 If globals doesn't come from a package or a module in a package, or a
2559 corresponding entry is not found in sys.modules, Py_None is returned.
2560*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002561static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002562get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 static PyObject *namestr = NULL;
2565 static PyObject *pathstr = NULL;
2566 static PyObject *pkgstr = NULL;
2567 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2568 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 if (globals == NULL || !PyDict_Check(globals) || !level)
2571 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (namestr == NULL) {
2574 namestr = PyUnicode_InternFromString("__name__");
2575 if (namestr == NULL)
2576 return NULL;
2577 }
2578 if (pathstr == NULL) {
2579 pathstr = PyUnicode_InternFromString("__path__");
2580 if (pathstr == NULL)
2581 return NULL;
2582 }
2583 if (pkgstr == NULL) {
2584 pkgstr = PyUnicode_InternFromString("__package__");
2585 if (pkgstr == NULL)
2586 return NULL;
2587 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 *buf = '\0';
2590 *p_buflen = 0;
2591 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 if ((pkgname != NULL) && (pkgname != Py_None)) {
2594 /* __package__ is set, so use it */
2595 char *pkgname_str;
2596 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 if (!PyUnicode_Check(pkgname)) {
2599 PyErr_SetString(PyExc_ValueError,
2600 "__package__ set to non-string");
2601 return NULL;
2602 }
2603 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2604 if (len == 0) {
2605 if (level > 0) {
2606 PyErr_SetString(PyExc_ValueError,
2607 "Attempted relative import in non-package");
2608 return NULL;
2609 }
2610 return Py_None;
2611 }
2612 if (len > MAXPATHLEN) {
2613 PyErr_SetString(PyExc_ValueError,
2614 "Package name too long");
2615 return NULL;
2616 }
2617 strcpy(buf, pkgname_str);
2618 } else {
2619 /* __package__ not set, so figure it out and set it */
2620 modname = PyDict_GetItem(globals, namestr);
2621 if (modname == NULL || !PyUnicode_Check(modname))
2622 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 modpath = PyDict_GetItem(globals, pathstr);
2625 if (modpath != NULL) {
2626 /* __path__ is set, so modname is already the package name */
2627 char *modname_str;
2628 Py_ssize_t len;
2629 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2632 if (len > MAXPATHLEN) {
2633 PyErr_SetString(PyExc_ValueError,
2634 "Module name too long");
2635 return NULL;
2636 }
2637 strcpy(buf, modname_str);
2638 error = PyDict_SetItem(globals, pkgstr, modname);
2639 if (error) {
2640 PyErr_SetString(PyExc_ValueError,
2641 "Could not set __package__");
2642 return NULL;
2643 }
2644 } else {
2645 /* Normal module, so work out the package name if any */
2646 char *start = _PyUnicode_AsString(modname);
2647 char *lastdot = strrchr(start, '.');
2648 size_t len;
2649 int error;
2650 if (lastdot == NULL && level > 0) {
2651 PyErr_SetString(PyExc_ValueError,
2652 "Attempted relative import in non-package");
2653 return NULL;
2654 }
2655 if (lastdot == NULL) {
2656 error = PyDict_SetItem(globals, pkgstr, Py_None);
2657 if (error) {
2658 PyErr_SetString(PyExc_ValueError,
2659 "Could not set __package__");
2660 return NULL;
2661 }
2662 return Py_None;
2663 }
2664 len = lastdot - start;
2665 if (len >= MAXPATHLEN) {
2666 PyErr_SetString(PyExc_ValueError,
2667 "Module name too long");
2668 return NULL;
2669 }
2670 strncpy(buf, start, len);
2671 buf[len] = '\0';
2672 pkgname = PyUnicode_FromString(buf);
2673 if (pkgname == NULL) {
2674 return NULL;
2675 }
2676 error = PyDict_SetItem(globals, pkgstr, pkgname);
2677 Py_DECREF(pkgname);
2678 if (error) {
2679 PyErr_SetString(PyExc_ValueError,
2680 "Could not set __package__");
2681 return NULL;
2682 }
2683 }
2684 }
2685 while (--level > 0) {
2686 char *dot = strrchr(buf, '.');
2687 if (dot == NULL) {
2688 PyErr_SetString(PyExc_ValueError,
2689 "Attempted relative import beyond "
2690 "toplevel package");
2691 return NULL;
2692 }
2693 *dot = '\0';
2694 }
2695 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 modules = PyImport_GetModuleDict();
2698 parent = PyDict_GetItemString(modules, buf);
2699 if (parent == NULL) {
2700 if (orig_level < 1) {
2701 PyObject *err_msg = PyBytes_FromFormat(
2702 "Parent module '%.200s' not found "
2703 "while handling absolute import", buf);
2704 if (err_msg == NULL) {
2705 return NULL;
2706 }
2707 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2708 PyBytes_AsString(err_msg), 1)) {
2709 *buf = '\0';
2710 *p_buflen = 0;
2711 parent = Py_None;
2712 }
2713 Py_DECREF(err_msg);
2714 } else {
2715 PyErr_Format(PyExc_SystemError,
2716 "Parent module '%.200s' not loaded, "
2717 "cannot perform relative import", buf);
2718 }
2719 }
2720 return parent;
2721 /* We expect, but can't guarantee, if parent != None, that:
2722 - parent.__name__ == buf
2723 - parent.__dict__ is globals
2724 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002725}
2726
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002727/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002728static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002729load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 char *name = *p_name;
2733 char *dot = strchr(name, '.');
2734 size_t len;
2735 char *p;
2736 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 if (strlen(name) == 0) {
2739 /* completely empty module name should only happen in
2740 'from . import' (or '__import__("")')*/
2741 Py_INCREF(mod);
2742 *p_name = NULL;
2743 return mod;
2744 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 if (dot == NULL) {
2747 *p_name = NULL;
2748 len = strlen(name);
2749 }
2750 else {
2751 *p_name = dot+1;
2752 len = dot-name;
2753 }
2754 if (len == 0) {
2755 PyErr_SetString(PyExc_ValueError,
2756 "Empty module name");
2757 return NULL;
2758 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 p = buf + *p_buflen;
2761 if (p != buf)
2762 *p++ = '.';
2763 if (p+len-buf >= MAXPATHLEN) {
2764 PyErr_SetString(PyExc_ValueError,
2765 "Module name too long");
2766 return NULL;
2767 }
2768 strncpy(p, name, len);
2769 p[len] = '\0';
2770 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 result = import_submodule(mod, p, buf);
2773 if (result == Py_None && altmod != mod) {
2774 Py_DECREF(result);
2775 /* Here, altmod must be None and mod must not be None */
2776 result = import_submodule(altmod, p, p);
2777 if (result != NULL && result != Py_None) {
2778 if (mark_miss(buf) != 0) {
2779 Py_DECREF(result);
2780 return NULL;
2781 }
2782 strncpy(buf, name, len);
2783 buf[len] = '\0';
2784 *p_buflen = len;
2785 }
2786 }
2787 if (result == NULL)
2788 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 if (result == Py_None) {
2791 Py_DECREF(result);
2792 PyErr_Format(PyExc_ImportError,
2793 "No module named %.200s", name);
2794 return NULL;
2795 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002798}
2799
2800static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002801mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 PyObject *modules = PyImport_GetModuleDict();
2804 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002805}
2806
2807static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002808ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 if (!PyObject_HasAttrString(mod, "__path__"))
2814 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 for (i = 0; ; i++) {
2817 PyObject *item = PySequence_GetItem(fromlist, i);
2818 int hasit;
2819 if (item == NULL) {
2820 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2821 PyErr_Clear();
2822 return 1;
2823 }
2824 return 0;
2825 }
2826 if (!PyUnicode_Check(item)) {
2827 PyErr_SetString(PyExc_TypeError,
2828 "Item in ``from list'' not a string");
2829 Py_DECREF(item);
2830 return 0;
2831 }
2832 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2833 PyObject *all;
2834 Py_DECREF(item);
2835 /* See if the package defines __all__ */
2836 if (recursive)
2837 continue; /* Avoid endless recursion */
2838 all = PyObject_GetAttrString(mod, "__all__");
2839 if (all == NULL)
2840 PyErr_Clear();
2841 else {
2842 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2843 Py_DECREF(all);
2844 if (!ret)
2845 return 0;
2846 }
2847 continue;
2848 }
2849 hasit = PyObject_HasAttr(mod, item);
2850 if (!hasit) {
2851 PyObject *item8;
2852 char *subname;
2853 PyObject *submod;
2854 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002855 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 if (!item8) {
2857 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2858 return 0;
2859 }
2860 subname = PyBytes_AS_STRING(item8);
2861 if (buflen + strlen(subname) >= MAXPATHLEN) {
2862 PyErr_SetString(PyExc_ValueError,
2863 "Module name too long");
2864 Py_DECREF(item);
2865 return 0;
2866 }
2867 p = buf + buflen;
2868 *p++ = '.';
2869 strcpy(p, subname);
2870 submod = import_submodule(mod, subname, buf);
2871 Py_DECREF(item8);
2872 Py_XDECREF(submod);
2873 if (submod == NULL) {
2874 Py_DECREF(item);
2875 return 0;
2876 }
2877 }
2878 Py_DECREF(item);
2879 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002882}
2883
Neil Schemenauer00b09662003-06-16 21:03:07 +00002884static int
2885add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (mod == Py_None)
2889 return 1;
2890 /* Irrespective of the success of this load, make a
2891 reference to it in the parent package module. A copy gets
2892 saved in the modules dictionary under the full name, so get a
2893 reference from there, if need be. (The exception is when the
2894 load failed with a SyntaxError -- then there's no trace in
2895 sys.modules. In that case, of course, do nothing extra.) */
2896 if (submod == NULL) {
2897 submod = PyDict_GetItemString(modules, fullname);
2898 if (submod == NULL)
2899 return 1;
2900 }
2901 if (PyModule_Check(mod)) {
2902 /* We can't use setattr here since it can give a
2903 * spurious warning if the submodule name shadows a
2904 * builtin name */
2905 PyObject *dict = PyModule_GetDict(mod);
2906 if (!dict)
2907 return 0;
2908 if (PyDict_SetItemString(dict, subname, submod) < 0)
2909 return 0;
2910 }
2911 else {
2912 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2913 return 0;
2914 }
2915 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002916}
2917
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002918static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002919import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 PyObject *modules = PyImport_GetModuleDict();
2922 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* Require:
2925 if mod == None: subname == fullname
2926 else: mod.__name__ + "." + subname == fullname
2927 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2930 Py_INCREF(m);
2931 }
2932 else {
2933 PyObject *path, *loader = NULL;
2934 char buf[MAXPATHLEN+1];
2935 struct filedescr *fdp;
2936 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 if (mod == Py_None)
2939 path = NULL;
2940 else {
2941 path = PyObject_GetAttrString(mod, "__path__");
2942 if (path == NULL) {
2943 PyErr_Clear();
2944 Py_INCREF(Py_None);
2945 return Py_None;
2946 }
2947 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 buf[0] = '\0';
2950 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2951 &fp, &loader);
2952 Py_XDECREF(path);
2953 if (fdp == NULL) {
2954 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2955 return NULL;
2956 PyErr_Clear();
2957 Py_INCREF(Py_None);
2958 return Py_None;
2959 }
2960 m = load_module(fullname, fp, buf, fdp->type, loader);
2961 Py_XDECREF(loader);
2962 if (fp)
2963 fclose(fp);
2964 if (!add_submodule(mod, m, fullname, subname, modules)) {
2965 Py_XDECREF(m);
2966 m = NULL;
2967 }
2968 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002971}
2972
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002973
2974/* Re-import a module of any kind and return its module object, WITH
2975 INCREMENTED REFERENCE COUNT */
2976
Guido van Rossum79f25d91997-04-29 20:08:16 +00002977PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002978PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 PyInterpreterState *interp = PyThreadState_Get()->interp;
2981 PyObject *modules_reloading = interp->modules_reloading;
2982 PyObject *modules = PyImport_GetModuleDict();
2983 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2984 char *name, *subname;
2985 char buf[MAXPATHLEN+1];
2986 struct filedescr *fdp;
2987 FILE *fp = NULL;
2988 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 if (modules_reloading == NULL) {
2991 Py_FatalError("PyImport_ReloadModule: "
2992 "no modules_reloading dictionary!");
2993 return NULL;
2994 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 if (m == NULL || !PyModule_Check(m)) {
2997 PyErr_SetString(PyExc_TypeError,
2998 "reload() argument must be module");
2999 return NULL;
3000 }
3001 name = (char*)PyModule_GetName(m);
3002 if (name == NULL)
3003 return NULL;
3004 if (m != PyDict_GetItemString(modules, name)) {
3005 PyErr_Format(PyExc_ImportError,
3006 "reload(): module %.200s not in sys.modules",
3007 name);
3008 return NULL;
3009 }
3010 existing_m = PyDict_GetItemString(modules_reloading, name);
3011 if (existing_m != NULL) {
3012 /* Due to a recursive reload, this module is already
3013 being reloaded. */
3014 Py_INCREF(existing_m);
3015 return existing_m;
3016 }
3017 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
3018 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 subname = strrchr(name, '.');
3021 if (subname == NULL)
3022 subname = name;
3023 else {
3024 PyObject *parentname, *parent;
3025 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
3026 if (parentname == NULL) {
3027 imp_modules_reloading_clear();
3028 return NULL;
3029 }
3030 parent = PyDict_GetItem(modules, parentname);
3031 if (parent == NULL) {
3032 PyErr_Format(PyExc_ImportError,
3033 "reload(): parent %U not in sys.modules",
3034 parentname);
3035 Py_DECREF(parentname);
3036 imp_modules_reloading_clear();
3037 return NULL;
3038 }
3039 Py_DECREF(parentname);
3040 subname++;
3041 path = PyObject_GetAttrString(parent, "__path__");
3042 if (path == NULL)
3043 PyErr_Clear();
3044 }
3045 buf[0] = '\0';
3046 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3047 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 if (fdp == NULL) {
3050 Py_XDECREF(loader);
3051 imp_modules_reloading_clear();
3052 return NULL;
3053 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 newm = load_module(name, fp, buf, fdp->type, loader);
3056 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 if (fp)
3059 fclose(fp);
3060 if (newm == NULL) {
3061 /* load_module probably removed name from modules because of
3062 * the error. Put back the original module object. We're
3063 * going to return NULL in this case regardless of whether
3064 * replacing name succeeds, so the return value is ignored.
3065 */
3066 PyDict_SetItemString(modules, name, m);
3067 }
3068 imp_modules_reloading_clear();
3069 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003070}
3071
3072
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003073/* Higher-level import emulator which emulates the "import" statement
3074 more accurately -- it invokes the __import__() function from the
3075 builtins of the current globals. This means that the import is
3076 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003077 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003078 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003079 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003080 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003081
3082PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003083PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 static PyObject *silly_list = NULL;
3086 static PyObject *builtins_str = NULL;
3087 static PyObject *import_str = NULL;
3088 PyObject *globals = NULL;
3089 PyObject *import = NULL;
3090 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003091 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 /* Initialize constant string objects */
3095 if (silly_list == NULL) {
3096 import_str = PyUnicode_InternFromString("__import__");
3097 if (import_str == NULL)
3098 return NULL;
3099 builtins_str = PyUnicode_InternFromString("__builtins__");
3100 if (builtins_str == NULL)
3101 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003102 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 if (silly_list == NULL)
3104 return NULL;
3105 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 /* Get the builtins from current globals */
3108 globals = PyEval_GetGlobals();
3109 if (globals != NULL) {
3110 Py_INCREF(globals);
3111 builtins = PyObject_GetItem(globals, builtins_str);
3112 if (builtins == NULL)
3113 goto err;
3114 }
3115 else {
3116 /* No globals -- use standard builtins, and fake globals */
3117 builtins = PyImport_ImportModuleLevel("builtins",
3118 NULL, NULL, NULL, 0);
3119 if (builtins == NULL)
3120 return NULL;
3121 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3122 if (globals == NULL)
3123 goto err;
3124 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 /* Get the __import__ function from the builtins */
3127 if (PyDict_Check(builtins)) {
3128 import = PyObject_GetItem(builtins, import_str);
3129 if (import == NULL)
3130 PyErr_SetObject(PyExc_KeyError, import_str);
3131 }
3132 else
3133 import = PyObject_GetAttr(builtins, import_str);
3134 if (import == NULL)
3135 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003138 Always use absolute import here.
3139 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3141 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003142 if (r == NULL)
3143 goto err;
3144 Py_DECREF(r);
3145
3146 modules = PyImport_GetModuleDict();
3147 r = PyDict_GetItem(modules, module_name);
3148 if (r != NULL)
3149 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003150
3151 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 Py_XDECREF(globals);
3153 Py_XDECREF(builtins);
3154 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003157}
3158
3159
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003160/* Module 'imp' provides Python access to the primitives used for
3161 importing modules.
3162*/
3163
Guido van Rossum79f25d91997-04-29 20:08:16 +00003164static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003165imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 buf[0] = (char) ((magic >> 0) & 0xff);
3170 buf[1] = (char) ((magic >> 8) & 0xff);
3171 buf[2] = (char) ((magic >> 16) & 0xff);
3172 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003175}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003176
3177static PyObject *
3178imp_get_magic(PyObject *self, PyObject *noargs)
3179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003181}
3182
3183static PyObject *
3184imp_get_tag(PyObject *self, PyObject *noargs)
3185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003187}
3188
Guido van Rossum79f25d91997-04-29 20:08:16 +00003189static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003190imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 PyObject *list;
3193 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 list = PyList_New(0);
3196 if (list == NULL)
3197 return NULL;
3198 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3199 PyObject *item = Py_BuildValue("ssi",
3200 fdp->suffix, fdp->mode, fdp->type);
3201 if (item == NULL) {
3202 Py_DECREF(list);
3203 return NULL;
3204 }
3205 if (PyList_Append(list, item) < 0) {
3206 Py_DECREF(list);
3207 Py_DECREF(item);
3208 return NULL;
3209 }
3210 Py_DECREF(item);
3211 }
3212 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003213}
3214
Guido van Rossum79f25d91997-04-29 20:08:16 +00003215static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003216call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 extern int fclose(FILE *);
3219 PyObject *fob, *ret;
3220 PyObject *pathobj;
3221 struct filedescr *fdp;
3222 char pathname[MAXPATHLEN+1];
3223 FILE *fp = NULL;
3224 int fd = -1;
3225 char *found_encoding = NULL;
3226 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 pathname[0] = '\0';
3229 if (path == Py_None)
3230 path = NULL;
3231 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3232 if (fdp == NULL)
3233 return NULL;
3234 if (fp != NULL) {
3235 fd = fileno(fp);
3236 if (fd != -1)
3237 fd = dup(fd);
3238 fclose(fp);
3239 fp = NULL;
3240 }
3241 if (fd != -1) {
3242 if (strchr(fdp->mode, 'b') == NULL) {
3243 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3244 memory. */
3245 found_encoding = PyTokenizer_FindEncoding(fd);
3246 lseek(fd, 0, 0); /* Reset position */
3247 if (found_encoding == NULL && PyErr_Occurred())
3248 return NULL;
3249 encoding = (found_encoding != NULL) ? found_encoding :
3250 (char*)PyUnicode_GetDefaultEncoding();
3251 }
3252 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3253 (char*)encoding, NULL, NULL, 1);
3254 if (fob == NULL) {
3255 close(fd);
3256 PyMem_FREE(found_encoding);
3257 return NULL;
3258 }
3259 }
3260 else {
3261 fob = Py_None;
3262 Py_INCREF(fob);
3263 }
3264 pathobj = PyUnicode_DecodeFSDefault(pathname);
3265 ret = Py_BuildValue("NN(ssi)",
3266 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3267 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003270}
3271
Guido van Rossum79f25d91997-04-29 20:08:16 +00003272static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003273imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003274{
Victor Stinnerebc00522010-12-03 17:06:43 +00003275 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 PyObject *ret, *path = NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003277 if (!PyArg_ParseTuple(args, "O&|O:find_module",
3278 PyUnicode_FSConverter, &name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 &path))
3280 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003281 ret = call_find_module(PyBytes_AS_STRING(name), path);
3282 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003284}
3285
3286static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003287imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 char *name;
3290 int ret;
3291 PyObject *m;
3292 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3293 return NULL;
3294 ret = init_builtin(name);
3295 if (ret < 0)
3296 return NULL;
3297 if (ret == 0) {
3298 Py_INCREF(Py_None);
3299 return Py_None;
3300 }
3301 m = PyImport_AddModule(name);
3302 Py_XINCREF(m);
3303 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003304}
3305
Guido van Rossum79f25d91997-04-29 20:08:16 +00003306static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003307imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003308{
Victor Stinner53dc7352011-03-20 01:50:21 +01003309 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 int ret;
3311 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003312 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003314 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 if (ret < 0)
3316 return NULL;
3317 if (ret == 0) {
3318 Py_INCREF(Py_None);
3319 return Py_None;
3320 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003321 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 Py_XINCREF(m);
3323 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003324}
3325
Guido van Rossum79f25d91997-04-29 20:08:16 +00003326static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003327imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003328{
Victor Stinner53dc7352011-03-20 01:50:21 +01003329 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003330
Victor Stinner53dc7352011-03-20 01:50:21 +01003331 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 return NULL;
3333 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003334}
3335
Guido van Rossum79f25d91997-04-29 20:08:16 +00003336static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003337imp_is_frozen_package(PyObject *self, PyObject *args)
3338{
Victor Stinner53dc7352011-03-20 01:50:21 +01003339 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003340
Victor Stinner53dc7352011-03-20 01:50:21 +01003341 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 return NULL;
3343 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003344}
3345
3346static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003347imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 char *name;
3350 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3351 return NULL;
3352 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003353}
3354
Guido van Rossum79f25d91997-04-29 20:08:16 +00003355static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003356imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003357{
Victor Stinner53dc7352011-03-20 01:50:21 +01003358 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003360 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 return NULL;
3362 p = find_frozen(name);
3363 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003364}
3365
3366static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003367get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 FILE *fp;
3370 if (mode[0] == 'U')
3371 mode = "r" PY_STDIOTEXTMODE;
3372 if (fob == NULL) {
3373 fp = fopen(pathname, mode);
3374 }
3375 else {
3376 int fd = PyObject_AsFileDescriptor(fob);
3377 if (fd == -1)
3378 return NULL;
3379 if (!_PyVerify_fd(fd))
3380 goto error;
3381 /* the FILE struct gets a new fd, so that it can be closed
3382 * independently of the file descriptor given
3383 */
3384 fd = dup(fd);
3385 if (fd == -1)
3386 goto error;
3387 fp = fdopen(fd, mode);
3388 }
3389 if (fp)
3390 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003391error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 PyErr_SetFromErrno(PyExc_IOError);
3393 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003394}
3395
Guido van Rossum79f25d91997-04-29 20:08:16 +00003396static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003397imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003400 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 PyObject *fob = NULL;
3402 PyObject *m;
3403 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003404 if (!PyArg_ParseTuple(args, "sO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003406 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 &fob))
3408 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003409 fp = get_file(PyBytes_AS_STRING(pathname), fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003411 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 return NULL;
3413 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003414 m = load_compiled_module(name, PyBytes_AS_STRING(pathname), fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003416 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003418}
3419
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003420#ifdef HAVE_DYNAMIC_LOADING
3421
Guido van Rossum79f25d91997-04-29 20:08:16 +00003422static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003423imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003426 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 char *pathname;
3428 PyObject *fob = NULL;
3429 PyObject *m;
3430 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003431 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3432 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003434 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 if (fob) {
3436 fp = get_file(pathname, fob, "r");
3437 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003438 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 return NULL;
3440 }
3441 }
3442 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003443 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (fp)
3445 fclose(fp);
3446 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003447}
3448
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003449#endif /* HAVE_DYNAMIC_LOADING */
3450
Guido van Rossum79f25d91997-04-29 20:08:16 +00003451static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003452imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003455 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 PyObject *fob = NULL;
3457 PyObject *m;
3458 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003459 if (!PyArg_ParseTuple(args, "sO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003461 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 &fob))
3463 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003464 fp = get_file(PyBytes_AS_STRING(pathname), fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003466 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 return NULL;
3468 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003469 m = load_source_module(name, PyBytes_AS_STRING(pathname), fp);
3470 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 fclose(fp);
3472 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003473}
3474
Guido van Rossum79f25d91997-04-29 20:08:16 +00003475static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003476imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 char *name;
3479 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003480 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 PyObject * ret;
3482 char *suffix; /* Unused */
3483 char *mode;
3484 int type;
3485 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003486
Victor Stinner1a563032010-10-15 22:43:10 +00003487 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003489 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 &suffix, &mode, &type))
3491 return NULL;
3492 if (*mode) {
3493 /* Mode must start with 'r' or 'U' and must not contain '+'.
3494 Implicit in this test is the assumption that the mode
3495 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3498 PyErr_Format(PyExc_ValueError,
3499 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003500 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 return NULL;
3502 }
3503 }
3504 if (fob == Py_None)
3505 fp = NULL;
3506 else {
3507 fp = get_file(NULL, fob, mode);
3508 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003509 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 return NULL;
3511 }
3512 }
Victor Stinner1a563032010-10-15 22:43:10 +00003513 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3514 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 if (fp)
3516 fclose(fp);
3517 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003518}
3519
3520static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003521imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003524 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 PyObject * ret;
Victor Stinnerebc00522010-12-03 17:06:43 +00003526 if (!PyArg_ParseTuple(args, "sO&:load_package",
3527 &name, PyUnicode_FSConverter, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003529 ret = load_package(name, PyBytes_AS_STRING(pathname));
3530 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003532}
3533
3534static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003535imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 char *name;
3538 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3539 return NULL;
3540 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003541}
3542
Christian Heimes13a7a212008-01-07 17:13:09 +00003543static PyObject *
3544imp_reload(PyObject *self, PyObject *v)
3545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003547}
3548
3549PyDoc_STRVAR(doc_reload,
3550"reload(module) -> module\n\
3551\n\
3552Reload the module. The module must have been successfully imported before.");
3553
Barry Warsaw28a691b2010-04-17 00:19:56 +00003554static PyObject *
3555imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003560 PyObject *pathbytes;
3561 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003562 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003566 args, kws, "O&|O", kwlist,
3567 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003569
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003570 if (debug_override != NULL &&
3571 (debug = PyObject_IsTrue(debug_override)) < 0) {
3572 Py_DECREF(pathbytes);
3573 return NULL;
3574 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003575
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003576 cpathname = make_compiled_pathname(
3577 PyBytes_AS_STRING(pathbytes),
3578 buf, MAXPATHLEN+1, debug);
3579 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 if (cpathname == NULL) {
3582 PyErr_Format(PyExc_SystemError, "path buffer too short");
3583 return NULL;
3584 }
Victor Stinner88bd8912010-10-15 22:46:07 +00003585 return PyUnicode_DecodeFSDefault(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003586}
3587
3588PyDoc_STRVAR(doc_cache_from_source,
3589"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3590\n\
3591The .py file does not need to exist; this simply returns the path to the\n\
3592.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3593will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3594\n\
3595If debug_override is not None, then it must be a boolean and is taken as\n\
3596the value of __debug__ instead.");
3597
3598static PyObject *
3599imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003602
Victor Stinnerebc00522010-12-03 17:06:43 +00003603 PyObject *pathname_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 char *pathname;
3605 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003608 args, kws, "O&", kwlist,
3609 PyUnicode_FSConverter, &pathname_obj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003611
Victor Stinnerebc00522010-12-03 17:06:43 +00003612 pathname = PyBytes_AS_STRING(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 if (make_source_pathname(pathname, buf) == NULL) {
3614 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3615 pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003616 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return NULL;
3618 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003619 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003621}
3622
3623PyDoc_STRVAR(doc_source_from_cache,
3624"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3625\n\
3626The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3627the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3628does not conform to PEP 3147 format, ValueError will be raised.");
3629
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003630/* Doc strings */
3631
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003632PyDoc_STRVAR(doc_imp,
3633"This module provides the components needed to build your own\n\
3634__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003635
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003636PyDoc_STRVAR(doc_find_module,
3637"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003638Search for a module. If path is omitted or None, search for a\n\
3639built-in, frozen or special module and continue search in sys.path.\n\
3640The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003641package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003643PyDoc_STRVAR(doc_load_module,
3644"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003645Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003646The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003648PyDoc_STRVAR(doc_get_magic,
3649"get_magic() -> string\n\
3650Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003651
Barry Warsaw28a691b2010-04-17 00:19:56 +00003652PyDoc_STRVAR(doc_get_tag,
3653"get_tag() -> string\n\
3654Return the magic tag for .pyc or .pyo files.");
3655
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003656PyDoc_STRVAR(doc_get_suffixes,
3657"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003658Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003659that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003660
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003661PyDoc_STRVAR(doc_new_module,
3662"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003663Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003664The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003666PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003667"lock_held() -> boolean\n\
3668Return True if the import lock is currently held, else False.\n\
3669On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003670
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003671PyDoc_STRVAR(doc_acquire_lock,
3672"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003673Acquires the interpreter's import lock for the current thread.\n\
3674This lock should be used by import hooks to ensure thread-safety\n\
3675when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003676On platforms without threads, this function does nothing.");
3677
3678PyDoc_STRVAR(doc_release_lock,
3679"release_lock() -> None\n\
3680Release the interpreter's import lock.\n\
3681On platforms without threads, this function does nothing.");
3682
Guido van Rossum79f25d91997-04-29 20:08:16 +00003683static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3685 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3686 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3687 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3688 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3689 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3690 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3691 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3692 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3693 {"reload", imp_reload, METH_O, doc_reload},
3694 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3695 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3696 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3697 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3698 /* The rest are obsolete */
3699 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3700 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3701 {"init_builtin", imp_init_builtin, METH_VARARGS},
3702 {"init_frozen", imp_init_frozen, METH_VARARGS},
3703 {"is_builtin", imp_is_builtin, METH_VARARGS},
3704 {"is_frozen", imp_is_frozen, METH_VARARGS},
3705 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003706#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003708#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 {"load_package", imp_load_package, METH_VARARGS},
3710 {"load_source", imp_load_source, METH_VARARGS},
3711 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003712};
3713
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003714static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003715setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 PyObject *v;
3718 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 v = PyLong_FromLong((long)value);
3721 err = PyDict_SetItemString(d, name, v);
3722 Py_XDECREF(v);
3723 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003724}
3725
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003726typedef struct {
3727 PyObject_HEAD
3728} NullImporter;
3729
3730static int
3731NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3732{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003733#ifndef MS_WINDOWS
3734 PyObject *path;
3735 struct stat statbuf;
3736 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3739 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003740
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003741 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3742 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003744
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003745 if (PyBytes_GET_SIZE(path) == 0) {
3746 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 PyErr_SetString(PyExc_ImportError, "empty pathname");
3748 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003750
3751 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3752 Py_DECREF(path);
3753 if (rv == 0) {
3754 /* it exists */
3755 if (S_ISDIR(statbuf.st_mode)) {
3756 /* it's a directory */
3757 PyErr_SetString(PyExc_ImportError, "existing directory");
3758 return -1;
3759 }
3760 }
3761#else /* MS_WINDOWS */
3762 PyObject *pathobj;
3763 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003764 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003765
3766 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3767 return -1;
3768
3769 if (!PyArg_ParseTuple(args, "U:NullImporter",
3770 &pathobj))
3771 return -1;
3772
3773 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3774 PyErr_SetString(PyExc_ImportError, "empty pathname");
3775 return -1;
3776 }
3777
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003778 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003779 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003780 return -1;
3781 /* see issue1293 and issue3677:
3782 * stat() on Windows doesn't recognise paths like
3783 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3784 */
3785 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003786 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003787 if (rv != INVALID_FILE_ATTRIBUTES) {
3788 /* it exists */
3789 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3790 /* it's a directory */
3791 PyErr_SetString(PyExc_ImportError, "existing directory");
3792 return -1;
3793 }
3794 }
3795#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003797}
3798
3799static PyObject *
3800NullImporter_find_module(NullImporter *self, PyObject *args)
3801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003803}
3804
3805static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3807 "Always return None"
3808 },
3809 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003810};
3811
3812
Christian Heimes9cd17752007-11-18 19:35:23 +00003813PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 PyVarObject_HEAD_INIT(NULL, 0)
3815 "imp.NullImporter", /*tp_name*/
3816 sizeof(NullImporter), /*tp_basicsize*/
3817 0, /*tp_itemsize*/
3818 0, /*tp_dealloc*/
3819 0, /*tp_print*/
3820 0, /*tp_getattr*/
3821 0, /*tp_setattr*/
3822 0, /*tp_reserved*/
3823 0, /*tp_repr*/
3824 0, /*tp_as_number*/
3825 0, /*tp_as_sequence*/
3826 0, /*tp_as_mapping*/
3827 0, /*tp_hash */
3828 0, /*tp_call*/
3829 0, /*tp_str*/
3830 0, /*tp_getattro*/
3831 0, /*tp_setattro*/
3832 0, /*tp_as_buffer*/
3833 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3834 "Null importer object", /* tp_doc */
3835 0, /* tp_traverse */
3836 0, /* tp_clear */
3837 0, /* tp_richcompare */
3838 0, /* tp_weaklistoffset */
3839 0, /* tp_iter */
3840 0, /* tp_iternext */
3841 NullImporter_methods, /* tp_methods */
3842 0, /* tp_members */
3843 0, /* tp_getset */
3844 0, /* tp_base */
3845 0, /* tp_dict */
3846 0, /* tp_descr_get */
3847 0, /* tp_descr_set */
3848 0, /* tp_dictoffset */
3849 (initproc)NullImporter_init, /* tp_init */
3850 0, /* tp_alloc */
3851 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003852};
3853
Martin v. Löwis1a214512008-06-11 05:26:20 +00003854static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 PyModuleDef_HEAD_INIT,
3856 "imp",
3857 doc_imp,
3858 0,
3859 imp_methods,
3860 NULL,
3861 NULL,
3862 NULL,
3863 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003864};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003865
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003866PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003867PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (PyType_Ready(&PyNullImporter_Type) < 0)
3872 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 m = PyModule_Create(&impmodule);
3875 if (m == NULL)
3876 goto failure;
3877 d = PyModule_GetDict(m);
3878 if (d == NULL)
3879 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3882 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3883 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3884 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3885 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3886 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3887 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3888 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3889 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3890 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 Py_INCREF(&PyNullImporter_Type);
3893 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3894 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003895 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 Py_XDECREF(m);
3897 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003898}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003899
3900
Guido van Rossumb18618d2000-05-03 23:44:39 +00003901/* API for embedding applications that want to add their own entries
3902 to the table of built-in modules. This should normally be called
3903 *before* Py_Initialize(). When the table resize fails, -1 is
3904 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003905
3906 After a similar function by Just van Rossum. */
3907
3908int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003909PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 static struct _inittab *our_copy = NULL;
3912 struct _inittab *p;
3913 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 /* Count the number of entries in both tables */
3916 for (n = 0; newtab[n].name != NULL; n++)
3917 ;
3918 if (n == 0)
3919 return 0; /* Nothing to do */
3920 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3921 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 /* Allocate new memory for the combined table */
3924 p = our_copy;
3925 PyMem_RESIZE(p, struct _inittab, i+n+1);
3926 if (p == NULL)
3927 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 /* Copy the tables into the new memory */
3930 if (our_copy != PyImport_Inittab)
3931 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3932 PyImport_Inittab = our_copy = p;
3933 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003936}
3937
3938/* Shorthand to add a single entry given a name and a function */
3939
3940int
Brett Cannona826f322009-04-02 03:41:46 +00003941PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 newtab[0].name = (char *)name;
3948 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003951}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003952
3953#ifdef __cplusplus
3954}
3955#endif