blob: b2757dffdcfec6504dc8225c324dec6e94499521 [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;
421 char *name;
422 PyObject *key, *value, *dict;
423 PyInterpreterState *interp = PyThreadState_GET()->interp;
424 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (modules == NULL)
427 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Delete some special variables first. These are common
430 places where user values hide and people complain when their
431 destructors fail. Since the modules containing them are
432 deleted *last* of all, they would come too late in the normal
433 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 value = PyDict_GetItemString(modules, "builtins");
436 if (value != NULL && PyModule_Check(value)) {
437 dict = PyModule_GetDict(value);
438 if (Py_VerboseFlag)
439 PySys_WriteStderr("# clear builtins._\n");
440 PyDict_SetItemString(dict, "_", Py_None);
441 }
442 value = PyDict_GetItemString(modules, "sys");
443 if (value != NULL && PyModule_Check(value)) {
444 char **p;
445 PyObject *v;
446 dict = PyModule_GetDict(value);
447 for (p = sys_deletes; *p != NULL; p++) {
448 if (Py_VerboseFlag)
449 PySys_WriteStderr("# clear sys.%s\n", *p);
450 PyDict_SetItemString(dict, *p, Py_None);
451 }
452 for (p = sys_files; *p != NULL; p+=2) {
453 if (Py_VerboseFlag)
454 PySys_WriteStderr("# restore sys.%s\n", *p);
455 v = PyDict_GetItemString(dict, *(p+1));
456 if (v == NULL)
457 v = Py_None;
458 PyDict_SetItemString(dict, *p, v);
459 }
460 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* First, delete __main__ */
463 value = PyDict_GetItemString(modules, "__main__");
464 if (value != NULL && PyModule_Check(value)) {
465 if (Py_VerboseFlag)
466 PySys_WriteStderr("# cleanup __main__\n");
467 _PyModule_Clear(value);
468 PyDict_SetItemString(modules, "__main__", Py_None);
469 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* The special treatment of "builtins" here is because even
472 when it's not referenced as a module, its dictionary is
473 referenced by almost every module's __builtins__. Since
474 deleting a module clears its dictionary (even if there are
475 references left to it), we need to delete the "builtins"
476 module last. Likewise, we don't delete sys until the very
477 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Also note that we 'delete' modules by replacing their entry
480 in the modules dict with None, rather than really deleting
481 them; this avoids a rehash of the modules dictionary and
482 also marks them as "non existent" so they won't be
483 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Next, repeatedly delete modules with a reference count of
486 one (skipping builtins and sys) and delete them */
487 do {
488 ndone = 0;
489 pos = 0;
490 while (PyDict_Next(modules, &pos, &key, &value)) {
491 if (value->ob_refcnt != 1)
492 continue;
493 if (PyUnicode_Check(key) && PyModule_Check(value)) {
494 name = _PyUnicode_AsString(key);
495 if (strcmp(name, "builtins") == 0)
496 continue;
497 if (strcmp(name, "sys") == 0)
498 continue;
499 if (Py_VerboseFlag)
500 PySys_WriteStderr(
501 "# cleanup[1] %s\n", name);
502 _PyModule_Clear(value);
503 PyDict_SetItem(modules, key, Py_None);
504 ndone++;
505 }
506 }
507 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Next, delete all modules (still skipping builtins and sys) */
510 pos = 0;
511 while (PyDict_Next(modules, &pos, &key, &value)) {
512 if (PyUnicode_Check(key) && PyModule_Check(value)) {
513 name = _PyUnicode_AsString(key);
514 if (strcmp(name, "builtins") == 0)
515 continue;
516 if (strcmp(name, "sys") == 0)
517 continue;
518 if (Py_VerboseFlag)
519 PySys_WriteStderr("# cleanup[2] %s\n", name);
520 _PyModule_Clear(value);
521 PyDict_SetItem(modules, key, Py_None);
522 }
523 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Next, delete sys and builtins (in that order) */
526 value = PyDict_GetItemString(modules, "sys");
527 if (value != NULL && PyModule_Check(value)) {
528 if (Py_VerboseFlag)
529 PySys_WriteStderr("# cleanup sys\n");
530 _PyModule_Clear(value);
531 PyDict_SetItemString(modules, "sys", Py_None);
532 }
533 value = PyDict_GetItemString(modules, "builtins");
534 if (value != NULL && PyModule_Check(value)) {
535 if (Py_VerboseFlag)
536 PySys_WriteStderr("# cleanup builtins\n");
537 _PyModule_Clear(value);
538 PyDict_SetItemString(modules, "builtins", Py_None);
539 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 /* Finally, clear and delete the modules directory */
542 PyDict_Clear(modules);
543 interp->modules = NULL;
544 Py_DECREF(modules);
545 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000546}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000547
548
Barry Warsaw28a691b2010-04-17 00:19:56 +0000549/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550
551long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000552PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555}
556
557
Barry Warsaw28a691b2010-04-17 00:19:56 +0000558const char *
559PyImport_GetMagicTag(void)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000562}
563
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564/* Magic for extension modules (built-in as well as dynamically
565 loaded). To prevent initializing an extension module more than
566 once, we keep a static dictionary 'extensions' keyed by module name
567 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000568 modules), containing these modules. A copy of the module's
Victor Stinner49d3f252010-10-17 01:24:53 +0000569 dictionary is stored by calling _PyImport_FixupExtensionUnicode()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570 immediately after the module initialization function succeeds. A
571 copy can be retrieved from there by calling
Victor Stinner49d3f252010-10-17 01:24:53 +0000572 _PyImport_FindExtensionUnicode().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000574 Modules which do support multiple initialization set their m_size
575 field to a non-negative number (indicating the size of the
576 module-specific state). They are still recorded in the extensions
577 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000578*/
579
580int
Victor Stinner49d3f252010-10-17 01:24:53 +0000581_PyImport_FixupExtensionUnicode(PyObject *mod, char *name, PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyObject *modules, *dict;
584 struct PyModuleDef *def;
585 if (extensions == NULL) {
586 extensions = PyDict_New();
587 if (extensions == NULL)
588 return -1;
589 }
590 if (mod == NULL || !PyModule_Check(mod)) {
591 PyErr_BadInternalCall();
592 return -1;
593 }
594 def = PyModule_GetDef(mod);
595 if (!def) {
596 PyErr_BadInternalCall();
597 return -1;
598 }
599 modules = PyImport_GetModuleDict();
600 if (PyDict_SetItemString(modules, name, mod) < 0)
601 return -1;
602 if (_PyState_AddModule(mod, def) < 0) {
603 PyDict_DelItemString(modules, name);
604 return -1;
605 }
606 if (def->m_size == -1) {
607 if (def->m_base.m_copy) {
608 /* Somebody already imported the module,
609 likely under a different name.
610 XXX this should really not happen. */
611 Py_DECREF(def->m_base.m_copy);
612 def->m_base.m_copy = NULL;
613 }
614 dict = PyModule_GetDict(mod);
615 if (dict == NULL)
616 return -1;
617 def->m_base.m_copy = PyDict_Copy(dict);
618 if (def->m_base.m_copy == NULL)
619 return -1;
620 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000621 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623}
624
Victor Stinner49d3f252010-10-17 01:24:53 +0000625int
626_PyImport_FixupBuiltin(PyObject *mod, char *name)
627{
628 int res;
629 PyObject *filename;
630 filename = PyUnicode_FromString(name);
631 if (filename == NULL)
632 return -1;
633 res = _PyImport_FixupExtensionUnicode(mod, name, filename);
634 Py_DECREF(filename);
635 return res;
636}
637
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000639_PyImport_FindExtensionUnicode(const char *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyObject *mod, *mdict;
642 PyModuleDef* def;
643 if (extensions == NULL)
644 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000645 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (def == NULL)
647 return NULL;
648 if (def->m_size == -1) {
649 /* Module does not support repeated initialization */
650 if (def->m_base.m_copy == NULL)
651 return NULL;
652 mod = PyImport_AddModule(name);
653 if (mod == NULL)
654 return NULL;
655 mdict = PyModule_GetDict(mod);
656 if (mdict == NULL)
657 return NULL;
658 if (PyDict_Update(mdict, def->m_base.m_copy))
659 return NULL;
660 }
661 else {
662 if (def->m_base.m_init == NULL)
663 return NULL;
664 mod = def->m_base.m_init();
665 if (mod == NULL)
666 return NULL;
667 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
668 Py_DECREF(mod);
669 }
670 if (_PyState_AddModule(mod, def) < 0) {
671 PyDict_DelItemString(PyImport_GetModuleDict(), name);
672 Py_DECREF(mod);
673 return NULL;
674 }
675 if (Py_VerboseFlag)
Victor Stinner49d3f252010-10-17 01:24:53 +0000676 PySys_FormatStderr("import %s # previously loaded (%U)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 name, filename);
678 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000679
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680}
681
Victor Stinner49d3f252010-10-17 01:24:53 +0000682PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000683_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000684{
685 PyObject *res, *filename;
686 filename = PyUnicode_FromString(name);
687 if (filename == NULL)
688 return NULL;
689 res = _PyImport_FindExtensionUnicode(name, filename);
690 Py_DECREF(filename);
691 return res;
692}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693
694/* Get the module object corresponding to a module name.
695 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000696 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000697 Because the former action is most common, THIS DOES NOT RETURN A
698 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000699
Guido van Rossum79f25d91997-04-29 20:08:16 +0000700PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000701PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyObject *modules = PyImport_GetModuleDict();
704 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705
Victor Stinner27ee0892011-03-04 12:57:09 +0000706 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyModule_Check(m))
708 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000709 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (m == NULL)
711 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000712 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 Py_DECREF(m);
714 return NULL;
715 }
716 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000719}
720
Victor Stinner27ee0892011-03-04 12:57:09 +0000721PyObject *
722PyImport_AddModule(const char *name)
723{
724 PyObject *nameobj, *module;
725 nameobj = PyUnicode_FromString(name);
726 if (nameobj == NULL)
727 return NULL;
728 module = PyImport_AddModuleObject(nameobj);
729 Py_DECREF(nameobj);
730 return module;
731}
732
733
Tim Peters1cd70172004-08-02 03:52:12 +0000734/* Remove name from sys.modules, if it's there. */
735static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000736remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000739 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000741 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 Py_FatalError("import: deleting existing key in"
743 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000744}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000745
Barry Warsaw28a691b2010-04-17 00:19:56 +0000746static PyObject * get_sourcefile(char *file);
747static char *make_source_pathname(char *pathname, char *buf);
748static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000750
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000751/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000752 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
753 * removed from sys.modules, to avoid leaving damaged module objects
754 * in sys.modules. The caller may wish to restore the original
755 * module object (if any) in this case; PyImport_ReloadModule is an
756 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000757 *
758 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
759 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000760 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000761PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000762PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 return PyImport_ExecCodeModuleWithPathnames(
765 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000766}
767
768PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000769PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return PyImport_ExecCodeModuleWithPathnames(
772 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000773}
774
775PyObject *
776PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000778{
Victor Stinner27ee0892011-03-04 12:57:09 +0000779 PyObject *m = NULL;
780 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
781
782 nameobj = PyUnicode_FromString(name);
783 if (nameobj == NULL)
784 return NULL;
785
786 if (pathname != NULL) {
787 pathobj = PyUnicode_DecodeFSDefault(pathname);
788 if (pathobj == NULL)
789 goto error;
790 } else
791 pathobj = NULL;
792 if (cpathname != NULL) {
793 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
794 if (cpathobj == NULL)
795 goto error;
796 } else
797 cpathobj = NULL;
798 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
799error:
800 Py_DECREF(nameobj);
801 Py_XDECREF(pathobj);
802 Py_XDECREF(cpathobj);
803 return m;
804}
805
806PyObject*
807PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
808 PyObject *cpathname)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyObject *modules = PyImport_GetModuleDict();
811 PyObject *m, *d, *v;
Victor Stinner27ee0892011-03-04 12:57:09 +0000812 PyObject *pathbytes;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000813
Victor Stinner27ee0892011-03-04 12:57:09 +0000814 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (m == NULL)
816 return NULL;
817 /* If the module is being reloaded, we get the old module back
818 and re-use its dict to exec the new code. */
819 d = PyModule_GetDict(m);
820 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
821 if (PyDict_SetItemString(d, "__builtins__",
822 PyEval_GetBuiltins()) != 0)
823 goto error;
824 }
825 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (pathname != NULL) {
Victor Stinner27ee0892011-03-04 12:57:09 +0000827 pathbytes = PyUnicode_EncodeFSDefault(pathname);
828 if (pathbytes != NULL) {
829 v = get_sourcefile(PyBytes_AS_STRING(pathbytes));
830 Py_DECREF(pathbytes);
831 } else
832 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (v == NULL)
834 PyErr_Clear();
835 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000836 else
837 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (v == NULL) {
839 v = ((PyCodeObject *)co)->co_filename;
840 Py_INCREF(v);
841 }
842 if (PyDict_SetItemString(d, "__file__", v) != 0)
843 PyErr_Clear(); /* Not important enough to report */
844 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000847 if (cpathname != NULL)
848 v = cpathname;
849 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (PyDict_SetItemString(d, "__cached__", v) != 0)
852 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000853
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000854 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (v == NULL)
856 goto error;
857 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000858
Victor Stinner27ee0892011-03-04 12:57:09 +0000859 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000861 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 name);
863 return NULL;
864 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000869
870 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 remove_module(name);
872 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000873}
874
875
Barry Warsaw28a691b2010-04-17 00:19:56 +0000876/* Like strrchr(string, '/') but searches for the rightmost of either SEP
877 or ALTSEP, if the latter is defined.
878*/
879static char *
880rightmost_sep(char *s)
881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 char *found, c;
883 for (found = NULL; (c = *s); s++) {
884 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000885#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000887#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 )
889 {
890 found = s;
891 }
892 }
893 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000894}
895
896
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000897/* Given a pathname for a Python source file, fill a buffer with the
898 pathname for the corresponding compiled file. Return the pathname
899 for the compiled file, or NULL if there's no space in the buffer.
900 Doesn't set an exception. */
901
902static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000903make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 /* foo.py -> __pycache__/foo.<tag>.pyc */
906 size_t len = strlen(pathname);
907 size_t i, save;
908 char *pos;
909 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* Sanity check that the buffer has roughly enough space to hold what
912 will eventually be the full path to the compiled file. The 5 extra
913 bytes include the slash afer __pycache__, the two extra dots, the
914 extra trailing character ('c' or 'o') and null. This isn't exact
915 because the contents of the buffer can affect how many actual
916 characters of the string get into the buffer. We'll do a final
917 sanity check before writing the extension to ensure we do not
918 overflow the buffer.
919 */
920 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
921 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Find the last path separator and copy everything from the start of
924 the source string up to and including the separator.
925 */
926 if ((pos = rightmost_sep(pathname)) == NULL) {
927 i = 0;
928 }
929 else {
930 sep = *pos;
931 i = pos - pathname + 1;
932 strncpy(buf, pathname, i);
933 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 save = i;
936 buf[i++] = '\0';
937 /* Add __pycache__/ */
938 strcat(buf, CACHEDIR);
939 i += strlen(CACHEDIR) - 1;
940 buf[i++] = sep;
941 buf[i++] = '\0';
942 /* Add the base filename, but remove the .py or .pyw extension, since
943 the tag name must go before the extension.
944 */
945 strcat(buf, pathname + save);
946 if ((pos = strrchr(buf, '.')) != NULL)
947 *++pos = '\0';
948 strcat(buf, pyc_tag);
949 /* The length test above assumes that we're only adding one character
950 to the end of what would normally be the extension. What if there
951 is no extension, or the string ends in '.' or '.p', and otherwise
952 fills the buffer? By appending 4 more characters onto the string
953 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 As a simple example, let's say buflen=32 and the input string is
956 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 which is false and so the name mangling would continue. This would
961 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
966 We can even handle an input string of say 'xxxxx' above because
967 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
968 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 which is 32 characters including the nul, and thus fits in the
973 buffer. However, an input string of 'xxxxxx' would yield a result
974 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 which is 33 characters long (including the nul), thus overflowing
979 the buffer, even though the first test would fail, i.e.: the input
980 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 The reason the first test fails but we still overflow the buffer is
983 that the test above only expects to add one extra character to be
984 added to the extension, and here we're adding three (pyc). We
985 don't add the first dot, so that reclaims one of expected
986 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
987 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 The best we can do is ensure that we still have enough room in the
990 target buffer before we write the extension. Because it's always
991 only the extension that can cause the overflow, and never the other
992 path bytes we've written, it's sufficient to just do one more test
993 here. Still, the assertion that follows can't hurt.
994 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000995#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000997#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (strlen(buf) + 5 > buflen)
999 return NULL;
1000 strcat(buf, debug ? ".pyc" : ".pyo");
1001 assert(strlen(buf) < buflen);
1002 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001003}
1004
1005
Barry Warsaw28a691b2010-04-17 00:19:56 +00001006/* Given a pathname to a Python byte compiled file, return the path to the
1007 source file, if the path matches the PEP 3147 format. This does not check
1008 for any file existence, however, if the pyc file name does not match PEP
1009 3147 style, NULL is returned. buf must be at least as big as pathname;
1010 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011
Barry Warsaw28a691b2010-04-17 00:19:56 +00001012static char *
1013make_source_pathname(char *pathname, char *buf)
1014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 /* __pycache__/foo.<tag>.pyc -> foo.py */
1016 size_t i, j;
1017 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* Look back two slashes from the end. In between these two slashes
1020 must be the string __pycache__ or this is not a PEP 3147 style
1021 path. It's possible for there to be only one slash.
1022 */
1023 if ((right = rightmost_sep(pathname)) == NULL)
1024 return NULL;
1025 sep = *right;
1026 *right = '\0';
1027 left = rightmost_sep(pathname);
1028 *right = sep;
1029 if (left == NULL)
1030 left = pathname;
1031 else
1032 left++;
1033 if (right-left != strlen(CACHEDIR) ||
1034 strncmp(left, CACHEDIR, right-left) != 0)
1035 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Now verify that the path component to the right of the last slash
1038 has two dots in it.
1039 */
1040 if ((dot0 = strchr(right + 1, '.')) == NULL)
1041 return NULL;
1042 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
1043 return NULL;
1044 /* Too many dots? */
1045 if (strchr(dot1 + 1, '.') != NULL)
1046 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* This is a PEP 3147 path. Start by copying everything from the
1049 start of pathname up to and including the leftmost slash. Then
1050 copy the file's basename, removing the magic tag and adding a .py
1051 suffix.
1052 */
1053 strncpy(buf, pathname, (i=left-pathname));
1054 strncpy(buf+i, right+1, (j=dot0-right));
1055 strcpy(buf+i+j, "py");
1056 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001057}
1058
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001059/* Given a pathname for a Python source file, its time of last
1060 modification, and a pathname for a compiled file, check whether the
1061 compiled file represents the same version of the source. If so,
1062 return a FILE pointer for the compiled file, positioned just after
1063 the header; if not, return NULL.
1064 Doesn't set an exception. */
1065
1066static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 FILE *fp;
1070 long magic;
1071 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 fp = fopen(cpathname, "rb");
1074 if (fp == NULL)
1075 return NULL;
1076 magic = PyMarshal_ReadLongFromFile(fp);
1077 if (magic != pyc_magic) {
1078 if (Py_VerboseFlag)
1079 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1080 fclose(fp);
1081 return NULL;
1082 }
1083 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1084 if (pyc_mtime != mtime) {
1085 if (Py_VerboseFlag)
1086 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1087 fclose(fp);
1088 return NULL;
1089 }
1090 if (Py_VerboseFlag)
1091 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1092 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001093}
1094
1095
1096/* Read a code object from a file and check it for validity */
1097
Guido van Rossum79f25d91997-04-29 20:08:16 +00001098static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001099read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 co = PyMarshal_ReadLastObjectFromFile(fp);
1104 if (co == NULL)
1105 return NULL;
1106 if (!PyCode_Check(co)) {
1107 PyErr_Format(PyExc_ImportError,
1108 "Non-code object in %.200s", cpathname);
1109 Py_DECREF(co);
1110 return NULL;
1111 }
1112 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001113}
1114
1115
1116/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001117 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001118
Guido van Rossum79f25d91997-04-29 20:08:16 +00001119static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001120load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 long magic;
1123 PyCodeObject *co;
1124 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 magic = PyMarshal_ReadLongFromFile(fp);
1127 if (magic != pyc_magic) {
1128 PyErr_Format(PyExc_ImportError,
1129 "Bad magic number in %.200s", cpathname);
1130 return NULL;
1131 }
1132 (void) PyMarshal_ReadLongFromFile(fp);
1133 co = read_compiled_module(cpathname, fp);
1134 if (co == NULL)
1135 return NULL;
1136 if (Py_VerboseFlag)
1137 PySys_WriteStderr("import %s # precompiled from %s\n",
1138 name, cpathname);
1139 m = PyImport_ExecCodeModuleWithPathnames(
1140 name, (PyObject *)co, cpathname, cpathname);
1141 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001144}
1145
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001146/* Parse a source file and return the corresponding code object */
1147
Guido van Rossum79f25d91997-04-29 20:08:16 +00001148static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001149parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyCodeObject *co = NULL;
1152 mod_ty mod;
1153 PyCompilerFlags flags;
1154 PyArena *arena = PyArena_New();
1155 if (arena == NULL)
1156 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 flags.cf_flags = 0;
1159 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1160 Py_file_input, 0, 0, &flags,
1161 NULL, arena);
1162 if (mod) {
1163 co = PyAST_Compile(mod, pathname, NULL, arena);
1164 }
1165 PyArena_Free(arena);
1166 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001167}
1168
1169
Guido van Rossum55a83382000-09-20 20:31:38 +00001170/* Helper to open a bytecode file for writing in exclusive mode */
1171
1172static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001173open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001174{
1175#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 /* Use O_EXCL to avoid a race condition when another process tries to
1177 write the same file. When that happens, our open() call fails,
1178 which is just fine (since it's only a cache).
1179 XXX If the file exists and is writable but the directory is not
1180 writable, the file will never be written. Oh well.
1181 */
1182 int fd;
1183 (void) unlink(filename);
1184 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001185#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001187#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001188#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001190#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001192#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 );
1194 if (fd < 0)
1195 return NULL;
1196 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001197#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 /* Best we can do -- on Windows this can't happen anyway */
1199 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001200#endif
1201}
1202
1203
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001204/* Write a compiled module to a file, placing the time of last
1205 modification of its source into the header.
1206 Errors are ignored, if a write error occurs an attempt is made to
1207 remove the file. */
1208
1209static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001210write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 FILE *fp;
1213 char *dirpath;
1214 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001215#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001217#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1219 mode_t dirmode = (srcstat->st_mode |
1220 S_IXUSR | S_IXGRP | S_IXOTH |
1221 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001222#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* Ensure that the __pycache__ directory exists. */
1226 dirpath = rightmost_sep(cpathname);
1227 if (dirpath == NULL) {
1228 if (Py_VerboseFlag)
1229 PySys_WriteStderr(
1230 "# no %s path found %s\n",
1231 CACHEDIR, cpathname);
1232 return;
1233 }
1234 saved = *dirpath;
1235 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001236
1237#ifdef MS_WINDOWS
1238 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1239#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001241#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 *dirpath = saved;
1243 if (Py_VerboseFlag)
1244 PySys_WriteStderr(
1245 "# cannot create cache dir %s\n", cpathname);
1246 return;
1247 }
1248 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 fp = open_exclusive(cpathname, mode);
1251 if (fp == NULL) {
1252 if (Py_VerboseFlag)
1253 PySys_WriteStderr(
1254 "# can't create %s\n", cpathname);
1255 return;
1256 }
1257 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1258 /* First write a 0 for mtime */
1259 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1260 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1261 if (fflush(fp) != 0 || ferror(fp)) {
1262 if (Py_VerboseFlag)
1263 PySys_WriteStderr("# can't write %s\n", cpathname);
1264 /* Don't keep partial file */
1265 fclose(fp);
1266 (void) unlink(cpathname);
1267 return;
1268 }
1269 /* Now write the true mtime */
1270 fseek(fp, 4L, 0);
1271 assert(mtime < LONG_MAX);
1272 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1273 fflush(fp);
1274 fclose(fp);
1275 if (Py_VerboseFlag)
1276 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001277}
1278
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001279static void
1280update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyObject *constants, *tmp;
1283 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (PyUnicode_Compare(co->co_filename, oldname))
1286 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 tmp = co->co_filename;
1289 co->co_filename = newname;
1290 Py_INCREF(co->co_filename);
1291 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 constants = co->co_consts;
1294 n = PyTuple_GET_SIZE(constants);
1295 for (i = 0; i < n; i++) {
1296 tmp = PyTuple_GET_ITEM(constants, i);
1297 if (PyCode_Check(tmp))
1298 update_code_filenames((PyCodeObject *)tmp,
1299 oldname, newname);
1300 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001301}
1302
1303static int
1304update_compiled_module(PyCodeObject *co, char *pathname)
1305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 newname = PyUnicode_DecodeFSDefault(pathname);
1309 if (newname == NULL)
1310 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (!PyUnicode_Compare(co->co_filename, newname)) {
1313 Py_DECREF(newname);
1314 return 0;
1315 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 oldname = co->co_filename;
1318 Py_INCREF(oldname);
1319 update_code_filenames(co, oldname, newname);
1320 Py_DECREF(oldname);
1321 Py_DECREF(newname);
1322 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001323}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001324
1325/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001326 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1327 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001328
Guido van Rossum79f25d91997-04-29 20:08:16 +00001329static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001330load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 struct stat st;
1333 FILE *fpc;
1334 char buf[MAXPATHLEN+1];
1335 char *cpathname;
1336 PyCodeObject *co;
1337 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 if (fstat(fileno(fp), &st) != 0) {
1340 PyErr_Format(PyExc_RuntimeError,
1341 "unable to get file status from '%s'",
1342 pathname);
1343 return NULL;
1344 }
Fred Drake4c82b232000-06-30 16:18:57 +00001345#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* Python's .pyc timestamp handling presumes that the timestamp fits
1347 in 4 bytes. This will be fine until sometime in the year 2038,
1348 when a 4-byte signed time_t will overflow.
1349 */
1350 if (st.st_mtime >> 32) {
1351 PyErr_SetString(PyExc_OverflowError,
1352 "modification time overflows a 4 byte field");
1353 return NULL;
1354 }
Fred Drake4c82b232000-06-30 16:18:57 +00001355#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 cpathname = make_compiled_pathname(
1357 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1358 if (cpathname != NULL &&
1359 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1360 co = read_compiled_module(cpathname, fpc);
1361 fclose(fpc);
1362 if (co == NULL)
1363 return NULL;
1364 if (update_compiled_module(co, pathname) < 0)
1365 return NULL;
1366 if (Py_VerboseFlag)
1367 PySys_WriteStderr("import %s # precompiled from %s\n",
1368 name, cpathname);
1369 pathname = cpathname;
1370 }
1371 else {
1372 co = parse_source_module(pathname, fp);
1373 if (co == NULL)
1374 return NULL;
1375 if (Py_VerboseFlag)
1376 PySys_WriteStderr("import %s # from %s\n",
1377 name, pathname);
1378 if (cpathname) {
1379 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1380 if (ro == NULL || !PyObject_IsTrue(ro))
1381 write_compiled_module(co, cpathname, &st);
1382 }
1383 }
1384 m = PyImport_ExecCodeModuleWithPathnames(
1385 name, (PyObject *)co, pathname, cpathname);
1386 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001389}
1390
Christian Heimes3b06e532008-01-07 20:12:44 +00001391/* Get source file -> unicode or None
1392 * Returns the path to the py file if available, else the given path
1393 */
1394static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001395get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 char py[MAXPATHLEN + 1];
1398 Py_ssize_t len;
1399 PyObject *u;
1400 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (!file || !*file) {
1403 Py_RETURN_NONE;
1404 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 len = strlen(file);
1407 /* match '*.py?' */
1408 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1409 return PyUnicode_DecodeFSDefault(file);
1410 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* Start by trying to turn PEP 3147 path into source path. If that
1413 * fails, just chop off the trailing character, i.e. legacy pyc path
1414 * to py.
1415 */
1416 if (make_source_pathname(file, py) == NULL) {
1417 strncpy(py, file, len-1);
1418 py[len-1] = '\0';
1419 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (stat(py, &statbuf) == 0 &&
1422 S_ISREG(statbuf.st_mode)) {
1423 u = PyUnicode_DecodeFSDefault(py);
1424 }
1425 else {
1426 u = PyUnicode_DecodeFSDefault(file);
1427 }
1428 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001429}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001430
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001431/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001432static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1433static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001435static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001436
1437/* Load a package and return its module object WITH INCREMENTED
1438 REFERENCE COUNT */
1439
1440static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001441load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyObject *m, *d;
1444 PyObject *file = NULL;
1445 PyObject *path = NULL;
1446 int err;
1447 char buf[MAXPATHLEN+1];
1448 FILE *fp = NULL;
1449 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 m = PyImport_AddModule(name);
1452 if (m == NULL)
1453 return NULL;
1454 if (Py_VerboseFlag)
1455 PySys_WriteStderr("import %s # directory %s\n",
1456 name, pathname);
1457 d = PyModule_GetDict(m);
1458 file = get_sourcefile(pathname);
1459 if (file == NULL)
1460 goto error;
1461 path = Py_BuildValue("[O]", file);
1462 if (path == NULL)
1463 goto error;
1464 err = PyDict_SetItemString(d, "__file__", file);
1465 if (err == 0)
1466 err = PyDict_SetItemString(d, "__path__", path);
1467 if (err != 0)
1468 goto error;
1469 buf[0] = '\0';
1470 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1471 if (fdp == NULL) {
1472 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1473 PyErr_Clear();
1474 Py_INCREF(m);
1475 }
1476 else
1477 m = NULL;
1478 goto cleanup;
1479 }
1480 m = load_module(name, fp, buf, fdp->type, NULL);
1481 if (fp != NULL)
1482 fclose(fp);
1483 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001484
1485 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001487 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 Py_XDECREF(path);
1489 Py_XDECREF(file);
1490 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001491}
1492
1493
1494/* Helper to test for built-in module */
1495
1496static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001497is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 int i;
1500 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1501 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1502 if (PyImport_Inittab[i].initfunc == NULL)
1503 return -1;
1504 else
1505 return 1;
1506 }
1507 }
1508 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001509}
1510
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001511
Just van Rossum52e14d62002-12-30 22:08:05 +00001512/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1513 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001514 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001515 that can handle the path item. Return None if no hook could;
1516 this tells our caller it should fall back to the builtin
1517 import mechanism. Cache the result in path_importer_cache.
1518 Returns a borrowed reference. */
1519
1520static PyObject *
1521get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyObject *importer;
1525 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 /* These conditions are the caller's responsibility: */
1528 assert(PyList_Check(path_hooks));
1529 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 nhooks = PyList_Size(path_hooks);
1532 if (nhooks < 0)
1533 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 importer = PyDict_GetItem(path_importer_cache, p);
1536 if (importer != NULL)
1537 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 /* set path_importer_cache[p] to None to avoid recursion */
1540 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1541 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 for (j = 0; j < nhooks; j++) {
1544 PyObject *hook = PyList_GetItem(path_hooks, j);
1545 if (hook == NULL)
1546 return NULL;
1547 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1548 if (importer != NULL)
1549 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1552 return NULL;
1553 }
1554 PyErr_Clear();
1555 }
1556 if (importer == NULL) {
1557 importer = PyObject_CallFunctionObjArgs(
1558 (PyObject *)&PyNullImporter_Type, p, NULL
1559 );
1560 if (importer == NULL) {
1561 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1562 PyErr_Clear();
1563 return Py_None;
1564 }
1565 }
1566 }
1567 if (importer != NULL) {
1568 int err = PyDict_SetItem(path_importer_cache, p, importer);
1569 Py_DECREF(importer);
1570 if (err != 0)
1571 return NULL;
1572 }
1573 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001574}
1575
Christian Heimes9cd17752007-11-18 19:35:23 +00001576PyAPI_FUNC(PyObject *)
1577PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1581 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1582 importer = get_path_importer(path_importer_cache,
1583 path_hooks, path);
1584 }
1585 }
1586 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1587 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001588}
1589
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001590/* Search the path (default sys.path) for a module. Return the
1591 corresponding filedescr struct, and (via return arguments) the
1592 pathname and an open file. Return NULL if the module is not found. */
1593
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001594#ifdef MS_COREDLL
Victor Stinner9b99b442011-02-22 23:12:28 +00001595extern FILE *_PyWin_FindRegisteredModule(const char *, struct filedescr **,
1596 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001597#endif
1598
Martin v. Löwis18e16552006-02-15 17:27:45 +00001599static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001600static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001601static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001602
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001603static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001604find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 Py_ssize_t i, npath;
1608 size_t len, namelen;
1609 struct filedescr *fdp = NULL;
1610 char *filemode;
1611 FILE *fp = NULL;
1612 PyObject *path_hooks, *path_importer_cache;
1613 struct stat statbuf;
1614 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1615 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1616 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1617 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001618#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 size_t saved_len;
1620 size_t saved_namelen;
1621 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001622#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (p_loader != NULL)
1624 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 if (strlen(subname) > MAXPATHLEN) {
1627 PyErr_SetString(PyExc_OverflowError,
1628 "module name is too long");
1629 return NULL;
1630 }
1631 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 /* sys.meta_path import hook */
1634 if (p_loader != NULL) {
1635 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 meta_path = PySys_GetObject("meta_path");
1638 if (meta_path == NULL || !PyList_Check(meta_path)) {
1639 PyErr_SetString(PyExc_ImportError,
1640 "sys.meta_path must be a list of "
1641 "import hooks");
1642 return NULL;
1643 }
1644 Py_INCREF(meta_path); /* zap guard */
1645 npath = PyList_Size(meta_path);
1646 for (i = 0; i < npath; i++) {
1647 PyObject *loader;
1648 PyObject *hook = PyList_GetItem(meta_path, i);
1649 loader = PyObject_CallMethod(hook, "find_module",
1650 "sO", fullname,
1651 path != NULL ?
1652 path : Py_None);
1653 if (loader == NULL) {
1654 Py_DECREF(meta_path);
1655 return NULL; /* true error */
1656 }
1657 if (loader != Py_None) {
1658 /* a loader was found */
1659 *p_loader = loader;
1660 Py_DECREF(meta_path);
1661 return &importhookdescr;
1662 }
1663 Py_DECREF(loader);
1664 }
1665 Py_DECREF(meta_path);
1666 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (find_frozen(fullname) != NULL) {
1669 strcpy(buf, fullname);
1670 return &fd_frozen;
1671 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (path == NULL) {
1674 if (is_builtin(name)) {
1675 strcpy(buf, name);
1676 return &fd_builtin;
1677 }
Guido van Rossumac279101996-08-22 23:10:58 +00001678#ifdef MS_COREDLL
Victor Stinner9b99b442011-02-22 23:12:28 +00001679 fp = _PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (fp != NULL) {
1681 *p_fp = fp;
1682 return fdp;
1683 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001684#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 path = PySys_GetObject("path");
1686 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (path == NULL || !PyList_Check(path)) {
1689 PyErr_SetString(PyExc_ImportError,
1690 "sys.path must be a list of directory names");
1691 return NULL;
1692 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 path_hooks = PySys_GetObject("path_hooks");
1695 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1696 PyErr_SetString(PyExc_ImportError,
1697 "sys.path_hooks must be a list of "
1698 "import hooks");
1699 return NULL;
1700 }
1701 path_importer_cache = PySys_GetObject("path_importer_cache");
1702 if (path_importer_cache == NULL ||
1703 !PyDict_Check(path_importer_cache)) {
1704 PyErr_SetString(PyExc_ImportError,
1705 "sys.path_importer_cache must be a dict");
1706 return NULL;
1707 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 npath = PyList_Size(path);
1710 namelen = strlen(name);
1711 for (i = 0; i < npath; i++) {
1712 PyObject *v = PyList_GetItem(path, i);
1713 PyObject *origv = v;
1714 const char *base;
1715 Py_ssize_t size;
1716 if (!v)
1717 return NULL;
1718 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001719 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (v == NULL)
1721 return NULL;
1722 }
1723 else if (!PyBytes_Check(v))
1724 continue;
1725 else
1726 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 base = PyBytes_AS_STRING(v);
1729 size = PyBytes_GET_SIZE(v);
1730 len = size;
1731 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1732 Py_DECREF(v);
1733 continue; /* Too long */
1734 }
1735 strcpy(buf, base);
1736 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (strlen(buf) != len) {
1739 continue; /* v contains '\0' */
1740 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 /* sys.path_hooks import hook */
1743 if (p_loader != NULL) {
1744 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 importer = get_path_importer(path_importer_cache,
1747 path_hooks, origv);
1748 if (importer == NULL) {
1749 return NULL;
1750 }
1751 /* Note: importer is a borrowed reference */
1752 if (importer != Py_None) {
1753 PyObject *loader;
1754 loader = PyObject_CallMethod(importer,
1755 "find_module",
1756 "s", fullname);
1757 if (loader == NULL)
1758 return NULL; /* error */
1759 if (loader != Py_None) {
1760 /* a loader was found */
1761 *p_loader = loader;
1762 return &importhookdescr;
1763 }
1764 Py_DECREF(loader);
1765 continue;
1766 }
1767 }
1768 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001771#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001773#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 )
1775 buf[len++] = SEP;
1776 strcpy(buf+len, name);
1777 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 /* Check for package import (buf holds a directory name,
1780 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001781#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (stat(buf, &statbuf) == 0 && /* it exists */
1783 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1784 case_ok(buf, len, namelen, name)) { /* case matches */
1785 if (find_init_module(buf)) { /* and has __init__.py */
1786 return &fd_package;
1787 }
1788 else {
Victor Stinnered7916d2010-10-17 02:07:09 +00001789 int err;
1790 PyObject *unicode = PyUnicode_DecodeFSDefault(buf);
1791 if (unicode == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 return NULL;
Victor Stinnered7916d2010-10-17 02:07:09 +00001793 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
1794 "Not importing directory '%U': missing __init__.py",
1795 unicode);
1796 Py_DECREF(unicode);
1797 if (err)
1798 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 }
1800 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001801#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001802#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 /* take a snapshot of the module spec for restoration
1804 * after the 8 character DLL hackery
1805 */
1806 saved_buf = strdup(buf);
1807 saved_len = len;
1808 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001809#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001811#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* OS/2 limits DLLs to 8 character names (w/o
1813 extension)
1814 * so if the name is longer than that and its a
1815 * dynamically loaded module we're going to try,
1816 * truncate the name before trying
1817 */
1818 if (strlen(subname) > 8) {
1819 /* is this an attempt to load a C extension? */
1820 const struct filedescr *scan;
1821 scan = _PyImport_DynLoadFiletab;
1822 while (scan->suffix != NULL) {
1823 if (!strcmp(scan->suffix, fdp->suffix))
1824 break;
1825 else
1826 scan++;
1827 }
1828 if (scan->suffix != NULL) {
1829 /* yes, so truncate the name */
1830 namelen = 8;
1831 len -= strlen(subname) - namelen;
1832 buf[len] = '\0';
1833 }
1834 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001835#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 strcpy(buf+len, fdp->suffix);
1837 if (Py_VerboseFlag > 1)
1838 PySys_WriteStderr("# trying %s\n", buf);
1839 filemode = fdp->mode;
1840 if (filemode[0] == 'U')
1841 filemode = "r" PY_STDIOTEXTMODE;
1842 fp = fopen(buf, filemode);
1843 if (fp != NULL) {
1844 if (case_ok(buf, len, namelen, name))
1845 break;
1846 else { /* continue search */
1847 fclose(fp);
1848 fp = NULL;
1849 }
1850 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001851#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 /* restore the saved snapshot */
1853 strcpy(buf, saved_buf);
1854 len = saved_len;
1855 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001856#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001858#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* don't need/want the module name snapshot anymore */
1860 if (saved_buf)
1861 {
1862 free(saved_buf);
1863 saved_buf = NULL;
1864 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001865#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (fp != NULL)
1867 break;
1868 }
1869 if (fp == NULL) {
1870 PyErr_Format(PyExc_ImportError,
1871 "No module named %.200s", name);
1872 return NULL;
1873 }
1874 *p_fp = fp;
1875 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001876}
1877
Martin v. Löwis18e16552006-02-15 17:27:45 +00001878/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001879 * The arguments here are tricky, best shown by example:
1880 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1881 * ^ ^ ^ ^
1882 * |--------------------- buf ---------------------|
1883 * |------------------- len ------------------|
1884 * |------ name -------|
1885 * |----- namelen -----|
1886 * buf is the full path, but len only counts up to (& exclusive of) the
1887 * extension. name is the module name, also exclusive of extension.
1888 *
1889 * We've already done a successful stat() or fopen() on buf, so know that
1890 * there's some match, possibly case-insensitive.
1891 *
Tim Peters50d8d372001-02-28 05:34:27 +00001892 * case_ok() is to return 1 if there's a case-sensitive match for
1893 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1894 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001895 *
Tim Peters50d8d372001-02-28 05:34:27 +00001896 * case_ok() is used to implement case-sensitive import semantics even
1897 * on platforms with case-insensitive filesystems. It's trivial to implement
1898 * for case-sensitive filesystems. It's pretty much a cross-platform
1899 * nightmare for systems with case-insensitive filesystems.
1900 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001901
Tim Peters50d8d372001-02-28 05:34:27 +00001902/* First we may need a pile of platform-specific header files; the sequence
1903 * of #if's here should match the sequence in the body of case_ok().
1904 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001905#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001906#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001907
Tim Peters50d8d372001-02-28 05:34:27 +00001908#elif defined(DJGPP)
1909#include <dir.h>
1910
Jason Tishler7961aa62005-05-20 00:56:54 +00001911#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001912#include <sys/types.h>
1913#include <dirent.h>
1914
Andrew MacIntyred9400542002-02-26 11:41:34 +00001915#elif defined(PYOS_OS2)
1916#define INCL_DOS
1917#define INCL_DOSERRORS
1918#define INCL_NOPMAPI
1919#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001920#endif
1921
Guido van Rossum0980bd91998-02-13 17:18:36 +00001922static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001923case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001924{
Tim Peters50d8d372001-02-28 05:34:27 +00001925/* Pick a platform-specific implementation; the sequence of #if's here should
1926 * match the sequence just above.
1927 */
1928
Jason Tishler7961aa62005-05-20 00:56:54 +00001929/* MS_WINDOWS */
1930#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 WIN32_FIND_DATA data;
1932 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 if (Py_GETENV("PYTHONCASEOK") != NULL)
1935 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 h = FindFirstFile(buf, &data);
1938 if (h == INVALID_HANDLE_VALUE) {
1939 PyErr_Format(PyExc_NameError,
1940 "Can't find file for module %.100s\n(filename %.300s)",
1941 name, buf);
1942 return 0;
1943 }
1944 FindClose(h);
1945 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001946
1947/* DJGPP */
1948#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 struct ffblk ffblk;
1950 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 if (Py_GETENV("PYTHONCASEOK") != NULL)
1953 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1956 if (done) {
1957 PyErr_Format(PyExc_NameError,
1958 "Can't find file for module %.100s\n(filename %.300s)",
1959 name, buf);
1960 return 0;
1961 }
1962 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001963
Jason Tishler7961aa62005-05-20 00:56:54 +00001964/* new-fangled macintosh (macosx) or Cygwin */
1965#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 DIR *dirp;
1967 struct dirent *dp;
1968 char dirname[MAXPATHLEN + 1];
1969 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (Py_GETENV("PYTHONCASEOK") != NULL)
1972 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* Copy the dir component into dirname; substitute "." if empty */
1975 if (dirlen <= 0) {
1976 dirname[0] = '.';
1977 dirname[1] = '\0';
1978 }
1979 else {
1980 assert(dirlen <= MAXPATHLEN);
1981 memcpy(dirname, buf, dirlen);
1982 dirname[dirlen] = '\0';
1983 }
1984 /* Open the directory and search the entries for an exact match. */
1985 dirp = opendir(dirname);
1986 if (dirp) {
1987 char *nameWithExt = buf + len - namelen;
1988 while ((dp = readdir(dirp)) != NULL) {
1989 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001990#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001992#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001994#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (thislen >= namelen &&
1996 strcmp(dp->d_name, nameWithExt) == 0) {
1997 (void)closedir(dirp);
1998 return 1; /* Found */
1999 }
2000 }
2001 (void)closedir(dirp);
2002 }
2003 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002004
Andrew MacIntyred9400542002-02-26 11:41:34 +00002005/* OS/2 */
2006#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 HDIR hdir = 1;
2008 ULONG srchcnt = 1;
2009 FILEFINDBUF3 ffbuf;
2010 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (Py_GETENV("PYTHONCASEOK") != NULL)
2013 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 rc = DosFindFirst(buf,
2016 &hdir,
2017 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2018 &ffbuf, sizeof(ffbuf),
2019 &srchcnt,
2020 FIL_STANDARD);
2021 if (rc != NO_ERROR)
2022 return 0;
2023 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002024
Tim Peters50d8d372001-02-28 05:34:27 +00002025/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2026#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002028
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002029#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002030}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002031
Guido van Rossum197346f1997-10-31 18:38:52 +00002032#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002033
Guido van Rossum197346f1997-10-31 18:38:52 +00002034/* Helper to look for __init__.py or __init__.py[co] in potential package */
2035static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002036find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00002037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 const size_t save_len = strlen(buf);
2039 size_t i = save_len;
2040 char *pname; /* pointer to start of __init__ */
2041 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043/* For calling case_ok(buf, len, namelen, name):
2044 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2045 * ^ ^ ^ ^
2046 * |--------------------- buf ---------------------|
2047 * |------------------- len ------------------|
2048 * |------ name -------|
2049 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00002050 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (save_len + 13 >= MAXPATHLEN)
2052 return 0;
2053 buf[i++] = SEP;
2054 pname = buf + i;
2055 strcpy(pname, "__init__.py");
2056 if (stat(buf, &statbuf) == 0) {
2057 if (case_ok(buf,
2058 save_len + 9, /* len("/__init__") */
2059 8, /* len("__init__") */
2060 pname)) {
2061 buf[save_len] = '\0';
2062 return 1;
2063 }
2064 }
2065 i += strlen(pname);
2066 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
2067 if (stat(buf, &statbuf) == 0) {
2068 if (case_ok(buf,
2069 save_len + 9, /* len("/__init__") */
2070 8, /* len("__init__") */
2071 pname)) {
2072 buf[save_len] = '\0';
2073 return 1;
2074 }
2075 }
2076 buf[save_len] = '\0';
2077 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002078}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002079
Guido van Rossum197346f1997-10-31 18:38:52 +00002080#endif /* HAVE_STAT */
2081
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002082
Tim Petersdbd9ba62000-07-09 03:09:57 +00002083static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002084
Victor Stinner44c6c152010-08-09 00:59:10 +00002085static PyObject*
2086load_builtin(char *name, char *pathname, int type)
2087{
2088 PyObject *m, *modules;
2089 int err;
2090
2091 if (pathname != NULL && pathname[0] != '\0')
2092 name = pathname;
2093
2094 if (type == C_BUILTIN)
2095 err = init_builtin(name);
2096 else
2097 err = PyImport_ImportFrozenModule(name);
2098 if (err < 0)
2099 return NULL;
2100 if (err == 0) {
2101 PyErr_Format(PyExc_ImportError,
2102 "Purported %s module %.200s not found",
2103 type == C_BUILTIN ?
2104 "builtin" : "frozen",
2105 name);
2106 return NULL;
2107 }
2108
2109 modules = PyImport_GetModuleDict();
2110 m = PyDict_GetItemString(modules, name);
2111 if (m == NULL) {
2112 PyErr_Format(
2113 PyExc_ImportError,
2114 "%s module %.200s not properly initialized",
2115 type == C_BUILTIN ?
2116 "builtin" : "frozen",
2117 name);
2118 return NULL;
2119 }
2120 Py_INCREF(m);
2121 return m;
2122}
2123
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002124/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002125 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002126
Guido van Rossum79f25d91997-04-29 20:08:16 +00002127static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002128load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /* First check that there's an open file (if we need one) */
2133 switch (type) {
2134 case PY_SOURCE:
2135 case PY_COMPILED:
2136 if (fp == NULL) {
2137 PyErr_Format(PyExc_ValueError,
2138 "file object required for import (type code %d)",
2139 type);
2140 return NULL;
2141 }
2142 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 case PY_SOURCE:
2147 m = load_source_module(name, pathname, fp);
2148 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 case PY_COMPILED:
2151 m = load_compiled_module(name, pathname, fp);
2152 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002153
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002154#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 case C_EXTENSION:
2156 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2157 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002158#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 case PKG_DIRECTORY:
2161 m = load_package(name, pathname);
2162 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 case C_BUILTIN:
2165 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002166 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 case IMP_HOOK: {
2170 if (loader == NULL) {
2171 PyErr_SetString(PyExc_ImportError,
2172 "import hook without loader");
2173 return NULL;
2174 }
2175 m = PyObject_CallMethod(loader, "load_module", "s", name);
2176 break;
2177 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 default:
2180 PyErr_Format(PyExc_ImportError,
2181 "Don't know how to import %.200s (type code %d)",
2182 name, type);
2183 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002188}
2189
2190
2191/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002192 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002193 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002194
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002195static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002196init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002199
Victor Stinner49d3f252010-10-17 01:24:53 +00002200 if (_PyImport_FindBuiltin(name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 for (p = PyImport_Inittab; p->name != NULL; p++) {
2204 PyObject *mod;
2205 if (strcmp(name, p->name) == 0) {
2206 if (p->initfunc == NULL) {
2207 PyErr_Format(PyExc_ImportError,
2208 "Cannot re-init internal module %.200s",
2209 name);
2210 return -1;
2211 }
2212 if (Py_VerboseFlag)
2213 PySys_WriteStderr("import %s # builtin\n", name);
2214 mod = (*p->initfunc)();
2215 if (mod == 0)
2216 return -1;
Victor Stinner49d3f252010-10-17 01:24:53 +00002217 if (_PyImport_FixupBuiltin(mod, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 return -1;
2219 /* FixupExtension has put the module into sys.modules,
2220 so we can release our own reference. */
2221 Py_DECREF(mod);
2222 return 1;
2223 }
2224 }
2225 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002226}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002227
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002228
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002229/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002230
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002231static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002232find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (!name)
2237 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 for (p = PyImport_FrozenModules; ; p++) {
2240 if (p->name == NULL)
2241 return NULL;
2242 if (strcmp(p->name, name) == 0)
2243 break;
2244 }
2245 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002246}
2247
Guido van Rossum79f25d91997-04-29 20:08:16 +00002248static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002249get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 struct _frozen *p = find_frozen(name);
2252 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (p == NULL) {
2255 PyErr_Format(PyExc_ImportError,
2256 "No such frozen object named %.200s",
2257 name);
2258 return NULL;
2259 }
2260 if (p->code == NULL) {
2261 PyErr_Format(PyExc_ImportError,
2262 "Excluded frozen object named %.200s",
2263 name);
2264 return NULL;
2265 }
2266 size = p->size;
2267 if (size < 0)
2268 size = -size;
2269 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002270}
2271
Brett Cannon8d110132009-03-15 02:20:16 +00002272static PyObject *
2273is_frozen_package(char *name)
2274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 struct _frozen *p = find_frozen(name);
2276 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 if (p == NULL) {
2279 PyErr_Format(PyExc_ImportError,
2280 "No such frozen object named %.200s",
2281 name);
2282 return NULL;
2283 }
Brett Cannon8d110132009-03-15 02:20:16 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (size < 0)
2288 Py_RETURN_TRUE;
2289 else
2290 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002291}
2292
2293
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002294/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002295 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002296 an exception set if the initialization failed.
2297 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002298
2299int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002300PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 struct _frozen *p = find_frozen(name);
2303 PyObject *co;
2304 PyObject *m;
2305 int ispackage;
2306 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 if (p == NULL)
2309 return 0;
2310 if (p->code == NULL) {
2311 PyErr_Format(PyExc_ImportError,
2312 "Excluded frozen object named %.200s",
2313 name);
2314 return -1;
2315 }
2316 size = p->size;
2317 ispackage = (size < 0);
2318 if (ispackage)
2319 size = -size;
2320 if (Py_VerboseFlag)
2321 PySys_WriteStderr("import %s # frozen%s\n",
2322 name, ispackage ? " package" : "");
2323 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2324 if (co == NULL)
2325 return -1;
2326 if (!PyCode_Check(co)) {
2327 PyErr_Format(PyExc_TypeError,
2328 "frozen object %.200s is not a code object",
2329 name);
2330 goto err_return;
2331 }
2332 if (ispackage) {
2333 /* Set __path__ to the package name */
2334 PyObject *d, *s, *l;
2335 int err;
2336 m = PyImport_AddModule(name);
2337 if (m == NULL)
2338 goto err_return;
2339 d = PyModule_GetDict(m);
2340 s = PyUnicode_InternFromString(name);
2341 if (s == NULL)
2342 goto err_return;
2343 l = PyList_New(1);
2344 if (l == NULL) {
2345 Py_DECREF(s);
2346 goto err_return;
2347 }
2348 PyList_SET_ITEM(l, 0, s);
2349 err = PyDict_SetItemString(d, "__path__", l);
2350 Py_DECREF(l);
2351 if (err != 0)
2352 goto err_return;
2353 }
2354 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2355 if (m == NULL)
2356 goto err_return;
2357 Py_DECREF(co);
2358 Py_DECREF(m);
2359 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002360err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 Py_DECREF(co);
2362 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002363}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002364
2365
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002366/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002367 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002368
Guido van Rossum79f25d91997-04-29 20:08:16 +00002369PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002370PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 PyObject *pname;
2373 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 pname = PyUnicode_FromString(name);
2376 if (pname == NULL)
2377 return NULL;
2378 result = PyImport_Import(pname);
2379 Py_DECREF(pname);
2380 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002381}
2382
Christian Heimes072c0f12008-01-03 23:01:04 +00002383/* Import a module without blocking
2384 *
2385 * At first it tries to fetch the module from sys.modules. If the module was
2386 * never loaded before it loads it with PyImport_ImportModule() unless another
2387 * thread holds the import lock. In the latter case the function raises an
2388 * ImportError instead of blocking.
2389 *
2390 * Returns the module object with incremented ref count.
2391 */
2392PyObject *
2393PyImport_ImportModuleNoBlock(const char *name)
2394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 PyObject *result;
2396 PyObject *modules;
2397 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Try to get the module from sys.modules[name] */
2400 modules = PyImport_GetModuleDict();
2401 if (modules == NULL)
2402 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 result = PyDict_GetItemString(modules, name);
2405 if (result != NULL) {
2406 Py_INCREF(result);
2407 return result;
2408 }
2409 else {
2410 PyErr_Clear();
2411 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002412#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 /* check the import lock
2414 * me might be -1 but I ignore the error here, the lock function
2415 * takes care of the problem */
2416 me = PyThread_get_thread_ident();
2417 if (import_lock_thread == -1 || import_lock_thread == me) {
2418 /* no thread or me is holding the lock */
2419 return PyImport_ImportModule(name);
2420 }
2421 else {
2422 PyErr_Format(PyExc_ImportError,
2423 "Failed to import %.200s because the import lock"
2424 "is held by another thread.",
2425 name);
2426 return NULL;
2427 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002428#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002430#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002431}
2432
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002433/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002434static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002436static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002438static int mark_miss(char *name);
2439static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002441static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002442
2443/* The Magnum Opus of dotted-name import :-) */
2444
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002445static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002446import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 char buf[MAXPATHLEN+1];
2450 Py_ssize_t buflen = 0;
2451 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002454#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002456#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 ) {
2458 PyErr_SetString(PyExc_ImportError,
2459 "Import by filename is not supported.");
2460 return NULL;
2461 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 parent = get_parent(globals, buf, &buflen, level);
2464 if (parent == NULL)
2465 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002466
Benjamin Peterson556d8002010-06-27 22:37:28 +00002467 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2468 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 if (head == NULL)
2470 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 tail = head;
2473 Py_INCREF(tail);
2474 while (name) {
2475 next = load_next(tail, tail, &name, buf, &buflen);
2476 Py_DECREF(tail);
2477 if (next == NULL) {
2478 Py_DECREF(head);
2479 return NULL;
2480 }
2481 tail = next;
2482 }
2483 if (tail == Py_None) {
2484 /* If tail is Py_None, both get_parent and load_next found
2485 an empty module name: someone called __import__("") or
2486 doctored faulty bytecode */
2487 Py_DECREF(tail);
2488 Py_DECREF(head);
2489 PyErr_SetString(PyExc_ValueError,
2490 "Empty module name");
2491 return NULL;
2492 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (fromlist != NULL) {
2495 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2496 fromlist = NULL;
2497 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (fromlist == NULL) {
2500 Py_DECREF(tail);
2501 return head;
2502 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 Py_DECREF(head);
2505 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2506 Py_DECREF(tail);
2507 return NULL;
2508 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002511}
2512
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002513PyObject *
2514PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 PyObject *result;
2518 _PyImport_AcquireLock();
2519 result = import_module_level(name, globals, locals, fromlist, level);
2520 if (_PyImport_ReleaseLock() < 0) {
2521 Py_XDECREF(result);
2522 PyErr_SetString(PyExc_RuntimeError,
2523 "not holding the import lock");
2524 return NULL;
2525 }
2526 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002527}
2528
Fred Drake87590902004-05-28 20:21:36 +00002529/* Return the package that an import is being performed in. If globals comes
2530 from the module foo.bar.bat (not itself a package), this returns the
2531 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002532 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002533
2534 The *name* of the returned package is returned in buf, with the length of
2535 the name in *p_buflen.
2536
2537 If globals doesn't come from a package or a module in a package, or a
2538 corresponding entry is not found in sys.modules, Py_None is returned.
2539*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002540static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002541get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 static PyObject *namestr = NULL;
2544 static PyObject *pathstr = NULL;
2545 static PyObject *pkgstr = NULL;
2546 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2547 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 if (globals == NULL || !PyDict_Check(globals) || !level)
2550 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 if (namestr == NULL) {
2553 namestr = PyUnicode_InternFromString("__name__");
2554 if (namestr == NULL)
2555 return NULL;
2556 }
2557 if (pathstr == NULL) {
2558 pathstr = PyUnicode_InternFromString("__path__");
2559 if (pathstr == NULL)
2560 return NULL;
2561 }
2562 if (pkgstr == NULL) {
2563 pkgstr = PyUnicode_InternFromString("__package__");
2564 if (pkgstr == NULL)
2565 return NULL;
2566 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 *buf = '\0';
2569 *p_buflen = 0;
2570 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if ((pkgname != NULL) && (pkgname != Py_None)) {
2573 /* __package__ is set, so use it */
2574 char *pkgname_str;
2575 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 if (!PyUnicode_Check(pkgname)) {
2578 PyErr_SetString(PyExc_ValueError,
2579 "__package__ set to non-string");
2580 return NULL;
2581 }
2582 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2583 if (len == 0) {
2584 if (level > 0) {
2585 PyErr_SetString(PyExc_ValueError,
2586 "Attempted relative import in non-package");
2587 return NULL;
2588 }
2589 return Py_None;
2590 }
2591 if (len > MAXPATHLEN) {
2592 PyErr_SetString(PyExc_ValueError,
2593 "Package name too long");
2594 return NULL;
2595 }
2596 strcpy(buf, pkgname_str);
2597 } else {
2598 /* __package__ not set, so figure it out and set it */
2599 modname = PyDict_GetItem(globals, namestr);
2600 if (modname == NULL || !PyUnicode_Check(modname))
2601 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 modpath = PyDict_GetItem(globals, pathstr);
2604 if (modpath != NULL) {
2605 /* __path__ is set, so modname is already the package name */
2606 char *modname_str;
2607 Py_ssize_t len;
2608 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2611 if (len > MAXPATHLEN) {
2612 PyErr_SetString(PyExc_ValueError,
2613 "Module name too long");
2614 return NULL;
2615 }
2616 strcpy(buf, modname_str);
2617 error = PyDict_SetItem(globals, pkgstr, modname);
2618 if (error) {
2619 PyErr_SetString(PyExc_ValueError,
2620 "Could not set __package__");
2621 return NULL;
2622 }
2623 } else {
2624 /* Normal module, so work out the package name if any */
2625 char *start = _PyUnicode_AsString(modname);
2626 char *lastdot = strrchr(start, '.');
2627 size_t len;
2628 int error;
2629 if (lastdot == NULL && level > 0) {
2630 PyErr_SetString(PyExc_ValueError,
2631 "Attempted relative import in non-package");
2632 return NULL;
2633 }
2634 if (lastdot == NULL) {
2635 error = PyDict_SetItem(globals, pkgstr, Py_None);
2636 if (error) {
2637 PyErr_SetString(PyExc_ValueError,
2638 "Could not set __package__");
2639 return NULL;
2640 }
2641 return Py_None;
2642 }
2643 len = lastdot - start;
2644 if (len >= MAXPATHLEN) {
2645 PyErr_SetString(PyExc_ValueError,
2646 "Module name too long");
2647 return NULL;
2648 }
2649 strncpy(buf, start, len);
2650 buf[len] = '\0';
2651 pkgname = PyUnicode_FromString(buf);
2652 if (pkgname == NULL) {
2653 return NULL;
2654 }
2655 error = PyDict_SetItem(globals, pkgstr, pkgname);
2656 Py_DECREF(pkgname);
2657 if (error) {
2658 PyErr_SetString(PyExc_ValueError,
2659 "Could not set __package__");
2660 return NULL;
2661 }
2662 }
2663 }
2664 while (--level > 0) {
2665 char *dot = strrchr(buf, '.');
2666 if (dot == NULL) {
2667 PyErr_SetString(PyExc_ValueError,
2668 "Attempted relative import beyond "
2669 "toplevel package");
2670 return NULL;
2671 }
2672 *dot = '\0';
2673 }
2674 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 modules = PyImport_GetModuleDict();
2677 parent = PyDict_GetItemString(modules, buf);
2678 if (parent == NULL) {
2679 if (orig_level < 1) {
2680 PyObject *err_msg = PyBytes_FromFormat(
2681 "Parent module '%.200s' not found "
2682 "while handling absolute import", buf);
2683 if (err_msg == NULL) {
2684 return NULL;
2685 }
2686 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2687 PyBytes_AsString(err_msg), 1)) {
2688 *buf = '\0';
2689 *p_buflen = 0;
2690 parent = Py_None;
2691 }
2692 Py_DECREF(err_msg);
2693 } else {
2694 PyErr_Format(PyExc_SystemError,
2695 "Parent module '%.200s' not loaded, "
2696 "cannot perform relative import", buf);
2697 }
2698 }
2699 return parent;
2700 /* We expect, but can't guarantee, if parent != None, that:
2701 - parent.__name__ == buf
2702 - parent.__dict__ is globals
2703 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002704}
2705
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002706/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002707static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002708load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 char *name = *p_name;
2712 char *dot = strchr(name, '.');
2713 size_t len;
2714 char *p;
2715 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 if (strlen(name) == 0) {
2718 /* completely empty module name should only happen in
2719 'from . import' (or '__import__("")')*/
2720 Py_INCREF(mod);
2721 *p_name = NULL;
2722 return mod;
2723 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 if (dot == NULL) {
2726 *p_name = NULL;
2727 len = strlen(name);
2728 }
2729 else {
2730 *p_name = dot+1;
2731 len = dot-name;
2732 }
2733 if (len == 0) {
2734 PyErr_SetString(PyExc_ValueError,
2735 "Empty module name");
2736 return NULL;
2737 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 p = buf + *p_buflen;
2740 if (p != buf)
2741 *p++ = '.';
2742 if (p+len-buf >= MAXPATHLEN) {
2743 PyErr_SetString(PyExc_ValueError,
2744 "Module name too long");
2745 return NULL;
2746 }
2747 strncpy(p, name, len);
2748 p[len] = '\0';
2749 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 result = import_submodule(mod, p, buf);
2752 if (result == Py_None && altmod != mod) {
2753 Py_DECREF(result);
2754 /* Here, altmod must be None and mod must not be None */
2755 result = import_submodule(altmod, p, p);
2756 if (result != NULL && result != Py_None) {
2757 if (mark_miss(buf) != 0) {
2758 Py_DECREF(result);
2759 return NULL;
2760 }
2761 strncpy(buf, name, len);
2762 buf[len] = '\0';
2763 *p_buflen = len;
2764 }
2765 }
2766 if (result == NULL)
2767 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (result == Py_None) {
2770 Py_DECREF(result);
2771 PyErr_Format(PyExc_ImportError,
2772 "No module named %.200s", name);
2773 return NULL;
2774 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002777}
2778
2779static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002780mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 PyObject *modules = PyImport_GetModuleDict();
2783 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002784}
2785
2786static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002787ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 if (!PyObject_HasAttrString(mod, "__path__"))
2793 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 for (i = 0; ; i++) {
2796 PyObject *item = PySequence_GetItem(fromlist, i);
2797 int hasit;
2798 if (item == NULL) {
2799 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2800 PyErr_Clear();
2801 return 1;
2802 }
2803 return 0;
2804 }
2805 if (!PyUnicode_Check(item)) {
2806 PyErr_SetString(PyExc_TypeError,
2807 "Item in ``from list'' not a string");
2808 Py_DECREF(item);
2809 return 0;
2810 }
2811 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2812 PyObject *all;
2813 Py_DECREF(item);
2814 /* See if the package defines __all__ */
2815 if (recursive)
2816 continue; /* Avoid endless recursion */
2817 all = PyObject_GetAttrString(mod, "__all__");
2818 if (all == NULL)
2819 PyErr_Clear();
2820 else {
2821 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2822 Py_DECREF(all);
2823 if (!ret)
2824 return 0;
2825 }
2826 continue;
2827 }
2828 hasit = PyObject_HasAttr(mod, item);
2829 if (!hasit) {
2830 PyObject *item8;
2831 char *subname;
2832 PyObject *submod;
2833 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002834 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 if (!item8) {
2836 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2837 return 0;
2838 }
2839 subname = PyBytes_AS_STRING(item8);
2840 if (buflen + strlen(subname) >= MAXPATHLEN) {
2841 PyErr_SetString(PyExc_ValueError,
2842 "Module name too long");
2843 Py_DECREF(item);
2844 return 0;
2845 }
2846 p = buf + buflen;
2847 *p++ = '.';
2848 strcpy(p, subname);
2849 submod = import_submodule(mod, subname, buf);
2850 Py_DECREF(item8);
2851 Py_XDECREF(submod);
2852 if (submod == NULL) {
2853 Py_DECREF(item);
2854 return 0;
2855 }
2856 }
2857 Py_DECREF(item);
2858 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002861}
2862
Neil Schemenauer00b09662003-06-16 21:03:07 +00002863static int
2864add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 if (mod == Py_None)
2868 return 1;
2869 /* Irrespective of the success of this load, make a
2870 reference to it in the parent package module. A copy gets
2871 saved in the modules dictionary under the full name, so get a
2872 reference from there, if need be. (The exception is when the
2873 load failed with a SyntaxError -- then there's no trace in
2874 sys.modules. In that case, of course, do nothing extra.) */
2875 if (submod == NULL) {
2876 submod = PyDict_GetItemString(modules, fullname);
2877 if (submod == NULL)
2878 return 1;
2879 }
2880 if (PyModule_Check(mod)) {
2881 /* We can't use setattr here since it can give a
2882 * spurious warning if the submodule name shadows a
2883 * builtin name */
2884 PyObject *dict = PyModule_GetDict(mod);
2885 if (!dict)
2886 return 0;
2887 if (PyDict_SetItemString(dict, subname, submod) < 0)
2888 return 0;
2889 }
2890 else {
2891 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2892 return 0;
2893 }
2894 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002895}
2896
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002897static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002898import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 PyObject *modules = PyImport_GetModuleDict();
2901 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 /* Require:
2904 if mod == None: subname == fullname
2905 else: mod.__name__ + "." + subname == fullname
2906 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2909 Py_INCREF(m);
2910 }
2911 else {
2912 PyObject *path, *loader = NULL;
2913 char buf[MAXPATHLEN+1];
2914 struct filedescr *fdp;
2915 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 if (mod == Py_None)
2918 path = NULL;
2919 else {
2920 path = PyObject_GetAttrString(mod, "__path__");
2921 if (path == NULL) {
2922 PyErr_Clear();
2923 Py_INCREF(Py_None);
2924 return Py_None;
2925 }
2926 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 buf[0] = '\0';
2929 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2930 &fp, &loader);
2931 Py_XDECREF(path);
2932 if (fdp == NULL) {
2933 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2934 return NULL;
2935 PyErr_Clear();
2936 Py_INCREF(Py_None);
2937 return Py_None;
2938 }
2939 m = load_module(fullname, fp, buf, fdp->type, loader);
2940 Py_XDECREF(loader);
2941 if (fp)
2942 fclose(fp);
2943 if (!add_submodule(mod, m, fullname, subname, modules)) {
2944 Py_XDECREF(m);
2945 m = NULL;
2946 }
2947 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002950}
2951
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002952
2953/* Re-import a module of any kind and return its module object, WITH
2954 INCREMENTED REFERENCE COUNT */
2955
Guido van Rossum79f25d91997-04-29 20:08:16 +00002956PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002957PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 PyInterpreterState *interp = PyThreadState_Get()->interp;
2960 PyObject *modules_reloading = interp->modules_reloading;
2961 PyObject *modules = PyImport_GetModuleDict();
2962 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2963 char *name, *subname;
2964 char buf[MAXPATHLEN+1];
2965 struct filedescr *fdp;
2966 FILE *fp = NULL;
2967 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 if (modules_reloading == NULL) {
2970 Py_FatalError("PyImport_ReloadModule: "
2971 "no modules_reloading dictionary!");
2972 return NULL;
2973 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 if (m == NULL || !PyModule_Check(m)) {
2976 PyErr_SetString(PyExc_TypeError,
2977 "reload() argument must be module");
2978 return NULL;
2979 }
2980 name = (char*)PyModule_GetName(m);
2981 if (name == NULL)
2982 return NULL;
2983 if (m != PyDict_GetItemString(modules, name)) {
2984 PyErr_Format(PyExc_ImportError,
2985 "reload(): module %.200s not in sys.modules",
2986 name);
2987 return NULL;
2988 }
2989 existing_m = PyDict_GetItemString(modules_reloading, name);
2990 if (existing_m != NULL) {
2991 /* Due to a recursive reload, this module is already
2992 being reloaded. */
2993 Py_INCREF(existing_m);
2994 return existing_m;
2995 }
2996 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2997 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 subname = strrchr(name, '.');
3000 if (subname == NULL)
3001 subname = name;
3002 else {
3003 PyObject *parentname, *parent;
3004 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
3005 if (parentname == NULL) {
3006 imp_modules_reloading_clear();
3007 return NULL;
3008 }
3009 parent = PyDict_GetItem(modules, parentname);
3010 if (parent == NULL) {
3011 PyErr_Format(PyExc_ImportError,
3012 "reload(): parent %U not in sys.modules",
3013 parentname);
3014 Py_DECREF(parentname);
3015 imp_modules_reloading_clear();
3016 return NULL;
3017 }
3018 Py_DECREF(parentname);
3019 subname++;
3020 path = PyObject_GetAttrString(parent, "__path__");
3021 if (path == NULL)
3022 PyErr_Clear();
3023 }
3024 buf[0] = '\0';
3025 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
3026 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 if (fdp == NULL) {
3029 Py_XDECREF(loader);
3030 imp_modules_reloading_clear();
3031 return NULL;
3032 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 newm = load_module(name, fp, buf, fdp->type, loader);
3035 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 if (fp)
3038 fclose(fp);
3039 if (newm == NULL) {
3040 /* load_module probably removed name from modules because of
3041 * the error. Put back the original module object. We're
3042 * going to return NULL in this case regardless of whether
3043 * replacing name succeeds, so the return value is ignored.
3044 */
3045 PyDict_SetItemString(modules, name, m);
3046 }
3047 imp_modules_reloading_clear();
3048 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003049}
3050
3051
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003052/* Higher-level import emulator which emulates the "import" statement
3053 more accurately -- it invokes the __import__() function from the
3054 builtins of the current globals. This means that the import is
3055 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003056 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003057 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003058 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003059 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003060
3061PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003062PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 static PyObject *silly_list = NULL;
3065 static PyObject *builtins_str = NULL;
3066 static PyObject *import_str = NULL;
3067 PyObject *globals = NULL;
3068 PyObject *import = NULL;
3069 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003070 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 /* Initialize constant string objects */
3074 if (silly_list == NULL) {
3075 import_str = PyUnicode_InternFromString("__import__");
3076 if (import_str == NULL)
3077 return NULL;
3078 builtins_str = PyUnicode_InternFromString("__builtins__");
3079 if (builtins_str == NULL)
3080 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003081 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 if (silly_list == NULL)
3083 return NULL;
3084 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 /* Get the builtins from current globals */
3087 globals = PyEval_GetGlobals();
3088 if (globals != NULL) {
3089 Py_INCREF(globals);
3090 builtins = PyObject_GetItem(globals, builtins_str);
3091 if (builtins == NULL)
3092 goto err;
3093 }
3094 else {
3095 /* No globals -- use standard builtins, and fake globals */
3096 builtins = PyImport_ImportModuleLevel("builtins",
3097 NULL, NULL, NULL, 0);
3098 if (builtins == NULL)
3099 return NULL;
3100 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3101 if (globals == NULL)
3102 goto err;
3103 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 /* Get the __import__ function from the builtins */
3106 if (PyDict_Check(builtins)) {
3107 import = PyObject_GetItem(builtins, import_str);
3108 if (import == NULL)
3109 PyErr_SetObject(PyExc_KeyError, import_str);
3110 }
3111 else
3112 import = PyObject_GetAttr(builtins, import_str);
3113 if (import == NULL)
3114 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003117 Always use absolute import here.
3118 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3120 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003121 if (r == NULL)
3122 goto err;
3123 Py_DECREF(r);
3124
3125 modules = PyImport_GetModuleDict();
3126 r = PyDict_GetItem(modules, module_name);
3127 if (r != NULL)
3128 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003129
3130 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 Py_XDECREF(globals);
3132 Py_XDECREF(builtins);
3133 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003136}
3137
3138
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003139/* Module 'imp' provides Python access to the primitives used for
3140 importing modules.
3141*/
3142
Guido van Rossum79f25d91997-04-29 20:08:16 +00003143static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003144imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 buf[0] = (char) ((magic >> 0) & 0xff);
3149 buf[1] = (char) ((magic >> 8) & 0xff);
3150 buf[2] = (char) ((magic >> 16) & 0xff);
3151 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003154}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003155
3156static PyObject *
3157imp_get_magic(PyObject *self, PyObject *noargs)
3158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003160}
3161
3162static PyObject *
3163imp_get_tag(PyObject *self, PyObject *noargs)
3164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003166}
3167
Guido van Rossum79f25d91997-04-29 20:08:16 +00003168static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003169imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 PyObject *list;
3172 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 list = PyList_New(0);
3175 if (list == NULL)
3176 return NULL;
3177 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3178 PyObject *item = Py_BuildValue("ssi",
3179 fdp->suffix, fdp->mode, fdp->type);
3180 if (item == NULL) {
3181 Py_DECREF(list);
3182 return NULL;
3183 }
3184 if (PyList_Append(list, item) < 0) {
3185 Py_DECREF(list);
3186 Py_DECREF(item);
3187 return NULL;
3188 }
3189 Py_DECREF(item);
3190 }
3191 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003192}
3193
Guido van Rossum79f25d91997-04-29 20:08:16 +00003194static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003195call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 extern int fclose(FILE *);
3198 PyObject *fob, *ret;
3199 PyObject *pathobj;
3200 struct filedescr *fdp;
3201 char pathname[MAXPATHLEN+1];
3202 FILE *fp = NULL;
3203 int fd = -1;
3204 char *found_encoding = NULL;
3205 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 pathname[0] = '\0';
3208 if (path == Py_None)
3209 path = NULL;
3210 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3211 if (fdp == NULL)
3212 return NULL;
3213 if (fp != NULL) {
3214 fd = fileno(fp);
3215 if (fd != -1)
3216 fd = dup(fd);
3217 fclose(fp);
3218 fp = NULL;
3219 }
3220 if (fd != -1) {
3221 if (strchr(fdp->mode, 'b') == NULL) {
3222 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3223 memory. */
3224 found_encoding = PyTokenizer_FindEncoding(fd);
3225 lseek(fd, 0, 0); /* Reset position */
3226 if (found_encoding == NULL && PyErr_Occurred())
3227 return NULL;
3228 encoding = (found_encoding != NULL) ? found_encoding :
3229 (char*)PyUnicode_GetDefaultEncoding();
3230 }
3231 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3232 (char*)encoding, NULL, NULL, 1);
3233 if (fob == NULL) {
3234 close(fd);
3235 PyMem_FREE(found_encoding);
3236 return NULL;
3237 }
3238 }
3239 else {
3240 fob = Py_None;
3241 Py_INCREF(fob);
3242 }
3243 pathobj = PyUnicode_DecodeFSDefault(pathname);
3244 ret = Py_BuildValue("NN(ssi)",
3245 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3246 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003249}
3250
Guido van Rossum79f25d91997-04-29 20:08:16 +00003251static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003252imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003253{
Victor Stinnerebc00522010-12-03 17:06:43 +00003254 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 PyObject *ret, *path = NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003256 if (!PyArg_ParseTuple(args, "O&|O:find_module",
3257 PyUnicode_FSConverter, &name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 &path))
3259 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003260 ret = call_find_module(PyBytes_AS_STRING(name), path);
3261 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003263}
3264
3265static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003266imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 char *name;
3269 int ret;
3270 PyObject *m;
3271 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3272 return NULL;
3273 ret = init_builtin(name);
3274 if (ret < 0)
3275 return NULL;
3276 if (ret == 0) {
3277 Py_INCREF(Py_None);
3278 return Py_None;
3279 }
3280 m = PyImport_AddModule(name);
3281 Py_XINCREF(m);
3282 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003283}
3284
Guido van Rossum79f25d91997-04-29 20:08:16 +00003285static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003286imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 char *name;
3289 int ret;
3290 PyObject *m;
3291 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3292 return NULL;
3293 ret = PyImport_ImportFrozenModule(name);
3294 if (ret < 0)
3295 return NULL;
3296 if (ret == 0) {
3297 Py_INCREF(Py_None);
3298 return Py_None;
3299 }
3300 m = PyImport_AddModule(name);
3301 Py_XINCREF(m);
3302 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003303}
3304
Guido van Rossum79f25d91997-04-29 20:08:16 +00003305static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003306imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3311 return NULL;
3312 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003313}
3314
Guido van Rossum79f25d91997-04-29 20:08:16 +00003315static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003316imp_is_frozen_package(PyObject *self, PyObject *args)
3317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3321 return NULL;
3322 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003323}
3324
3325static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003326imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 char *name;
3329 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3330 return NULL;
3331 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003332}
3333
Guido van Rossum79f25d91997-04-29 20:08:16 +00003334static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003335imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 char *name;
3338 struct _frozen *p;
3339 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3340 return NULL;
3341 p = find_frozen(name);
3342 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003343}
3344
3345static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003346get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 FILE *fp;
3349 if (mode[0] == 'U')
3350 mode = "r" PY_STDIOTEXTMODE;
3351 if (fob == NULL) {
3352 fp = fopen(pathname, mode);
3353 }
3354 else {
3355 int fd = PyObject_AsFileDescriptor(fob);
3356 if (fd == -1)
3357 return NULL;
3358 if (!_PyVerify_fd(fd))
3359 goto error;
3360 /* the FILE struct gets a new fd, so that it can be closed
3361 * independently of the file descriptor given
3362 */
3363 fd = dup(fd);
3364 if (fd == -1)
3365 goto error;
3366 fp = fdopen(fd, mode);
3367 }
3368 if (fp)
3369 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003370error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 PyErr_SetFromErrno(PyExc_IOError);
3372 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003373}
3374
Guido van Rossum79f25d91997-04-29 20:08:16 +00003375static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003376imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003379 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 PyObject *fob = NULL;
3381 PyObject *m;
3382 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003383 if (!PyArg_ParseTuple(args, "sO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003385 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 &fob))
3387 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003388 fp = get_file(PyBytes_AS_STRING(pathname), fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003390 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 return NULL;
3392 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003393 m = load_compiled_module(name, PyBytes_AS_STRING(pathname), fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003395 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003397}
3398
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003399#ifdef HAVE_DYNAMIC_LOADING
3400
Guido van Rossum79f25d91997-04-29 20:08:16 +00003401static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003402imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003405 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 char *pathname;
3407 PyObject *fob = NULL;
3408 PyObject *m;
3409 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003410 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3411 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003413 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 if (fob) {
3415 fp = get_file(pathname, fob, "r");
3416 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003417 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 return NULL;
3419 }
3420 }
3421 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003422 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 if (fp)
3424 fclose(fp);
3425 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003426}
3427
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003428#endif /* HAVE_DYNAMIC_LOADING */
3429
Guido van Rossum79f25d91997-04-29 20:08:16 +00003430static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003431imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003434 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 PyObject *fob = NULL;
3436 PyObject *m;
3437 FILE *fp;
Victor Stinnerebc00522010-12-03 17:06:43 +00003438 if (!PyArg_ParseTuple(args, "sO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 &name,
Victor Stinnerebc00522010-12-03 17:06:43 +00003440 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 &fob))
3442 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003443 fp = get_file(PyBytes_AS_STRING(pathname), fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003445 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 return NULL;
3447 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003448 m = load_source_module(name, PyBytes_AS_STRING(pathname), fp);
3449 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 fclose(fp);
3451 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003452}
3453
Guido van Rossum79f25d91997-04-29 20:08:16 +00003454static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003455imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 char *name;
3458 PyObject *fob;
Victor Stinner1a563032010-10-15 22:43:10 +00003459 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 PyObject * ret;
3461 char *suffix; /* Unused */
3462 char *mode;
3463 int type;
3464 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003465
Victor Stinner1a563032010-10-15 22:43:10 +00003466 if (!PyArg_ParseTuple(args, "sOO&(ssi):load_module",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 &name, &fob,
Victor Stinner1a563032010-10-15 22:43:10 +00003468 PyUnicode_FSConverter, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 &suffix, &mode, &type))
3470 return NULL;
3471 if (*mode) {
3472 /* Mode must start with 'r' or 'U' and must not contain '+'.
3473 Implicit in this test is the assumption that the mode
3474 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3477 PyErr_Format(PyExc_ValueError,
3478 "invalid file open mode %.200s", mode);
Victor Stinner1a563032010-10-15 22:43:10 +00003479 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 return NULL;
3481 }
3482 }
3483 if (fob == Py_None)
3484 fp = NULL;
3485 else {
3486 fp = get_file(NULL, fob, mode);
3487 if (fp == NULL) {
Victor Stinner1a563032010-10-15 22:43:10 +00003488 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 return NULL;
3490 }
3491 }
Victor Stinner1a563032010-10-15 22:43:10 +00003492 ret = load_module(name, fp, PyBytes_AS_STRING(pathname), type, NULL);
3493 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 if (fp)
3495 fclose(fp);
3496 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003497}
3498
3499static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003500imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 char *name;
Victor Stinnerebc00522010-12-03 17:06:43 +00003503 PyObject *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 PyObject * ret;
Victor Stinnerebc00522010-12-03 17:06:43 +00003505 if (!PyArg_ParseTuple(args, "sO&:load_package",
3506 &name, PyUnicode_FSConverter, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 return NULL;
Victor Stinnerebc00522010-12-03 17:06:43 +00003508 ret = load_package(name, PyBytes_AS_STRING(pathname));
3509 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003511}
3512
3513static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003514imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 char *name;
3517 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3518 return NULL;
3519 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003520}
3521
Christian Heimes13a7a212008-01-07 17:13:09 +00003522static PyObject *
3523imp_reload(PyObject *self, PyObject *v)
3524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003526}
3527
3528PyDoc_STRVAR(doc_reload,
3529"reload(module) -> module\n\
3530\n\
3531Reload the module. The module must have been successfully imported before.");
3532
Barry Warsaw28a691b2010-04-17 00:19:56 +00003533static PyObject *
3534imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003539 PyObject *pathbytes;
3540 char *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003541 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003545 args, kws, "O&|O", kwlist,
3546 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003548
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003549 if (debug_override != NULL &&
3550 (debug = PyObject_IsTrue(debug_override)) < 0) {
3551 Py_DECREF(pathbytes);
3552 return NULL;
3553 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003554
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003555 cpathname = make_compiled_pathname(
3556 PyBytes_AS_STRING(pathbytes),
3557 buf, MAXPATHLEN+1, debug);
3558 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 if (cpathname == NULL) {
3561 PyErr_Format(PyExc_SystemError, "path buffer too short");
3562 return NULL;
3563 }
Victor Stinner88bd8912010-10-15 22:46:07 +00003564 return PyUnicode_DecodeFSDefault(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003565}
3566
3567PyDoc_STRVAR(doc_cache_from_source,
3568"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3569\n\
3570The .py file does not need to exist; this simply returns the path to the\n\
3571.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3572will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3573\n\
3574If debug_override is not None, then it must be a boolean and is taken as\n\
3575the value of __debug__ instead.");
3576
3577static PyObject *
3578imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003581
Victor Stinnerebc00522010-12-03 17:06:43 +00003582 PyObject *pathname_obj;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 char *pathname;
3584 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003587 args, kws, "O&", kwlist,
3588 PyUnicode_FSConverter, &pathname_obj))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003590
Victor Stinnerebc00522010-12-03 17:06:43 +00003591 pathname = PyBytes_AS_STRING(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 if (make_source_pathname(pathname, buf) == NULL) {
3593 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3594 pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003595 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 return NULL;
3597 }
Victor Stinnerebc00522010-12-03 17:06:43 +00003598 Py_DECREF(pathname_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003600}
3601
3602PyDoc_STRVAR(doc_source_from_cache,
3603"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3604\n\
3605The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3606the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3607does not conform to PEP 3147 format, ValueError will be raised.");
3608
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003609/* Doc strings */
3610
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003611PyDoc_STRVAR(doc_imp,
3612"This module provides the components needed to build your own\n\
3613__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003614
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003615PyDoc_STRVAR(doc_find_module,
3616"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003617Search for a module. If path is omitted or None, search for a\n\
3618built-in, frozen or special module and continue search in sys.path.\n\
3619The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003620package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003622PyDoc_STRVAR(doc_load_module,
3623"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003624Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003625The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003627PyDoc_STRVAR(doc_get_magic,
3628"get_magic() -> string\n\
3629Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003630
Barry Warsaw28a691b2010-04-17 00:19:56 +00003631PyDoc_STRVAR(doc_get_tag,
3632"get_tag() -> string\n\
3633Return the magic tag for .pyc or .pyo files.");
3634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003635PyDoc_STRVAR(doc_get_suffixes,
3636"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003637Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003638that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003640PyDoc_STRVAR(doc_new_module,
3641"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003642Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003643The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003645PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003646"lock_held() -> boolean\n\
3647Return True if the import lock is currently held, else False.\n\
3648On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003649
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003650PyDoc_STRVAR(doc_acquire_lock,
3651"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003652Acquires the interpreter's import lock for the current thread.\n\
3653This lock should be used by import hooks to ensure thread-safety\n\
3654when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003655On platforms without threads, this function does nothing.");
3656
3657PyDoc_STRVAR(doc_release_lock,
3658"release_lock() -> None\n\
3659Release the interpreter's import lock.\n\
3660On platforms without threads, this function does nothing.");
3661
Guido van Rossum79f25d91997-04-29 20:08:16 +00003662static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3664 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3665 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3666 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3667 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3668 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3669 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3670 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3671 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3672 {"reload", imp_reload, METH_O, doc_reload},
3673 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3674 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3675 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3676 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3677 /* The rest are obsolete */
3678 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3679 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3680 {"init_builtin", imp_init_builtin, METH_VARARGS},
3681 {"init_frozen", imp_init_frozen, METH_VARARGS},
3682 {"is_builtin", imp_is_builtin, METH_VARARGS},
3683 {"is_frozen", imp_is_frozen, METH_VARARGS},
3684 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003685#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003687#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 {"load_package", imp_load_package, METH_VARARGS},
3689 {"load_source", imp_load_source, METH_VARARGS},
3690 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003691};
3692
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003693static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003694setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003696 PyObject *v;
3697 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 v = PyLong_FromLong((long)value);
3700 err = PyDict_SetItemString(d, name, v);
3701 Py_XDECREF(v);
3702 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003703}
3704
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003705typedef struct {
3706 PyObject_HEAD
3707} NullImporter;
3708
3709static int
3710NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3711{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003712#ifndef MS_WINDOWS
3713 PyObject *path;
3714 struct stat statbuf;
3715 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3718 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003719
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003720 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3721 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003723
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003724 if (PyBytes_GET_SIZE(path) == 0) {
3725 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 PyErr_SetString(PyExc_ImportError, "empty pathname");
3727 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003729
3730 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3731 Py_DECREF(path);
3732 if (rv == 0) {
3733 /* it exists */
3734 if (S_ISDIR(statbuf.st_mode)) {
3735 /* it's a directory */
3736 PyErr_SetString(PyExc_ImportError, "existing directory");
3737 return -1;
3738 }
3739 }
3740#else /* MS_WINDOWS */
3741 PyObject *pathobj;
3742 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003743 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003744
3745 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3746 return -1;
3747
3748 if (!PyArg_ParseTuple(args, "U:NullImporter",
3749 &pathobj))
3750 return -1;
3751
3752 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3753 PyErr_SetString(PyExc_ImportError, "empty pathname");
3754 return -1;
3755 }
3756
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003757 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003758 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003759 return -1;
3760 /* see issue1293 and issue3677:
3761 * stat() on Windows doesn't recognise paths like
3762 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3763 */
3764 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003765 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003766 if (rv != INVALID_FILE_ATTRIBUTES) {
3767 /* it exists */
3768 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3769 /* it's a directory */
3770 PyErr_SetString(PyExc_ImportError, "existing directory");
3771 return -1;
3772 }
3773 }
3774#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003776}
3777
3778static PyObject *
3779NullImporter_find_module(NullImporter *self, PyObject *args)
3780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003782}
3783
3784static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3786 "Always return None"
3787 },
3788 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003789};
3790
3791
Christian Heimes9cd17752007-11-18 19:35:23 +00003792PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 PyVarObject_HEAD_INIT(NULL, 0)
3794 "imp.NullImporter", /*tp_name*/
3795 sizeof(NullImporter), /*tp_basicsize*/
3796 0, /*tp_itemsize*/
3797 0, /*tp_dealloc*/
3798 0, /*tp_print*/
3799 0, /*tp_getattr*/
3800 0, /*tp_setattr*/
3801 0, /*tp_reserved*/
3802 0, /*tp_repr*/
3803 0, /*tp_as_number*/
3804 0, /*tp_as_sequence*/
3805 0, /*tp_as_mapping*/
3806 0, /*tp_hash */
3807 0, /*tp_call*/
3808 0, /*tp_str*/
3809 0, /*tp_getattro*/
3810 0, /*tp_setattro*/
3811 0, /*tp_as_buffer*/
3812 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3813 "Null importer object", /* tp_doc */
3814 0, /* tp_traverse */
3815 0, /* tp_clear */
3816 0, /* tp_richcompare */
3817 0, /* tp_weaklistoffset */
3818 0, /* tp_iter */
3819 0, /* tp_iternext */
3820 NullImporter_methods, /* tp_methods */
3821 0, /* tp_members */
3822 0, /* tp_getset */
3823 0, /* tp_base */
3824 0, /* tp_dict */
3825 0, /* tp_descr_get */
3826 0, /* tp_descr_set */
3827 0, /* tp_dictoffset */
3828 (initproc)NullImporter_init, /* tp_init */
3829 0, /* tp_alloc */
3830 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003831};
3832
Martin v. Löwis1a214512008-06-11 05:26:20 +00003833static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 PyModuleDef_HEAD_INIT,
3835 "imp",
3836 doc_imp,
3837 0,
3838 imp_methods,
3839 NULL,
3840 NULL,
3841 NULL,
3842 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003843};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003844
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003845PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003846PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if (PyType_Ready(&PyNullImporter_Type) < 0)
3851 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 m = PyModule_Create(&impmodule);
3854 if (m == NULL)
3855 goto failure;
3856 d = PyModule_GetDict(m);
3857 if (d == NULL)
3858 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3861 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3862 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3863 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3864 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3865 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3866 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3867 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3868 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3869 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 Py_INCREF(&PyNullImporter_Type);
3872 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3873 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003874 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 Py_XDECREF(m);
3876 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003877}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003878
3879
Guido van Rossumb18618d2000-05-03 23:44:39 +00003880/* API for embedding applications that want to add their own entries
3881 to the table of built-in modules. This should normally be called
3882 *before* Py_Initialize(). When the table resize fails, -1 is
3883 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003884
3885 After a similar function by Just van Rossum. */
3886
3887int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003888PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 static struct _inittab *our_copy = NULL;
3891 struct _inittab *p;
3892 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 /* Count the number of entries in both tables */
3895 for (n = 0; newtab[n].name != NULL; n++)
3896 ;
3897 if (n == 0)
3898 return 0; /* Nothing to do */
3899 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3900 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 /* Allocate new memory for the combined table */
3903 p = our_copy;
3904 PyMem_RESIZE(p, struct _inittab, i+n+1);
3905 if (p == NULL)
3906 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 /* Copy the tables into the new memory */
3909 if (our_copy != PyImport_Inittab)
3910 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3911 PyImport_Inittab = our_copy = p;
3912 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003915}
3916
3917/* Shorthand to add a single entry given a name and a function */
3918
3919int
Brett Cannona826f322009-04-02 03:41:46 +00003920PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 newtab[0].name = (char *)name;
3927 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003930}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003931
3932#ifdef __cplusplus
3933}
3934#endif