blob: 747b0ddff46f0d6faaf1b8273c9d8af7ace12c87 [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)
Benjamin Petersone7c15fa2011-06-19 19:54:45 -0500105 Python 3.3a0 3190 __class__ super closure changed
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100106 Python 3.3a0 3200 (__qualname__ added)
Benjamin Petersonabdb5522012-03-15 15:40:37 -0500107 3210 (added size modulo 2**32 to the pyc header)
108 Python 3.3a1 3220 (changed PEP 380 implementation)
Tim Peters36515e22001-11-18 04:06:29 +0000109*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000110
Nick Coghlancd419ab2010-09-11 00:39:25 +0000111/* MAGIC must change whenever the bytecode emitted by the compiler may no
112 longer be understood by older implementations of the eval loop (usually
113 due to the addition of new opcodes)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200114 TAG must change for each major Python release. The magic number will take
115 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116*/
Benjamin Peterson48deae12011-06-03 17:50:16 -0500117#define QUOTE(arg) #arg
118#define STRIFY(name) QUOTE(name)
119#define MAJOR STRIFY(PY_MAJOR_VERSION)
120#define MINOR STRIFY(PY_MINOR_VERSION)
Benjamin Petersonf53d20f2012-03-16 09:39:12 -0500121#define MAGIC (3220 | ((long)'\r'<<16) | ((long)'\n'<<24))
Benjamin Peterson48deae12011-06-03 17:50:16 -0500122#define TAG "cpython-" MAJOR MINOR;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000123#define CACHEDIR "__pycache__"
124/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000125static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000126static const char *pyc_tag = TAG;
Benjamin Peterson48deae12011-06-03 17:50:16 -0500127#undef QUOTE
128#undef STRIFY
129#undef MAJOR
130#undef MINOR
Guido van Rossum96774c12000-05-01 20:19:08 +0000131
Victor Stinner95872862011-03-07 18:20:56 +0100132/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000134
Victor Stinnerfe7c5b52011-04-05 01:48:03 +0200135/* Function from Parser/tokenizer.c */
136extern char * PyTokenizer_FindEncodingFilename(int, PyObject *);
137
Guido van Rossum771c6c81997-10-31 18:37:24 +0000138/* This table is defined in config.c: */
139extern struct _inittab _PyImport_Inittab[];
140
141struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000142
Guido van Rossumed1170e1999-12-20 21:23:41 +0000143/* these tables define the module suffixes that Python recognizes */
144struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000145
Guido van Rossumed1170e1999-12-20 21:23:41 +0000146static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000148#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000150#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 {".pyc", "rb", PY_COMPILED},
152 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000153};
154
Victor Stinnerd0296212011-03-14 14:04:10 -0400155static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000157/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158
159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 const struct filedescr *scan;
163 struct filedescr *filetab;
164 int countD = 0;
165 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000166
Victor Stinnerd0296212011-03-14 14:04:10 -0400167 initstr = PyUnicode_InternFromString("__init__");
168 if (initstr == NULL)
169 Py_FatalError("Can't initialize import variables");
170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* prepare _PyImport_Filetab: copy entries from
172 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
173 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000174#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
176 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
179 ++countS;
180 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
181 if (filetab == NULL)
182 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000183#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 memcpy(filetab, _PyImport_DynLoadFiletab,
185 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000186#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 memcpy(filetab + countD, _PyImport_StandardFiletab,
188 countS * sizeof(struct filedescr));
189 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (Py_OptimizeFlag) {
194 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
195 for (; filetab->suffix != NULL; filetab++) {
196 if (strcmp(filetab->suffix, ".pyc") == 0)
197 filetab->suffix = ".pyo";
198 }
199 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202void
Just van Rossum52e14d62002-12-30 22:08:05 +0000203_PyImportHooks_Init(void)
204{
Brett Cannonfd074152012-04-14 14:10:13 -0400205 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (PyType_Ready(&PyNullImporter_Type) < 0)
209 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000210
Brett Cannonfd074152012-04-14 14:10:13 -0400211 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 v = PyList_New(0);
213 if (v == NULL)
214 goto error;
215 err = PySys_SetObject("meta_path", v);
216 Py_DECREF(v);
217 if (err)
218 goto error;
219 v = PyDict_New();
220 if (v == NULL)
221 goto error;
222 err = PySys_SetObject("path_importer_cache", v);
223 Py_DECREF(v);
224 if (err)
225 goto error;
226 path_hooks = PyList_New(0);
227 if (path_hooks == NULL)
228 goto error;
229 err = PySys_SetObject("path_hooks", path_hooks);
230 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000231 error:
Brett Cannonfd074152012-04-14 14:10:13 -0400232 PyErr_Print();
233 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
234 "path_importer_cache, or NullImporter failed"
235 );
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 }
Brett Cannonfd074152012-04-14 14:10:13 -0400237 Py_DECREF(path_hooks);
238}
239
240void
241_PyImportZip_Init(void)
242{
243 PyObject *path_hooks, *zimpimport;
244 int err = 0;
245
246 path_hooks = PySys_GetObject("path_hooks");
247 if (path_hooks == NULL)
248 goto error;
249
250 if (Py_VerboseFlag)
251 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 zimpimport = PyImport_ImportModule("zipimport");
254 if (zimpimport == NULL) {
255 PyErr_Clear(); /* No zip import module -- okay */
256 if (Py_VerboseFlag)
257 PySys_WriteStderr("# can't import zipimport\n");
258 }
259 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200260 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200261 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
262 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 Py_DECREF(zimpimport);
264 if (zipimporter == NULL) {
265 PyErr_Clear(); /* No zipimporter object -- okay */
266 if (Py_VerboseFlag)
267 PySys_WriteStderr(
268 "# can't import zipimport.zipimporter\n");
269 }
270 else {
271 /* sys.path_hooks.append(zipimporter) */
272 err = PyList_Append(path_hooks, zipimporter);
273 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400274 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (Py_VerboseFlag)
278 PySys_WriteStderr(
279 "# installed zipimport hook\n");
280 }
281 }
Brett Cannonfd074152012-04-14 14:10:13 -0400282
283 return;
284
285 error:
286 PyErr_Print();
287 Py_FatalError("initializing zipimport or NullImporter failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000288}
289
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290/* Locking primitives to prevent parallel imports of the same module
291 in different threads to return with a partially loaded module.
292 These calls are serialized by the global interpreter lock. */
293
294#ifdef WITH_THREAD
295
Guido van Rossum49b56061998-10-01 20:42:43 +0000296#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000297
Guido van Rossum65d5b571998-12-21 19:32:43 +0000298static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000299static long import_lock_thread = -1;
300static int import_lock_level = 0;
301
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000302void
303_PyImport_AcquireLock(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)
307 return; /* Too bad */
308 if (import_lock == NULL) {
309 import_lock = PyThread_allocate_lock();
310 if (import_lock == NULL)
311 return; /* Nothing much we can do. */
312 }
313 if (import_lock_thread == me) {
314 import_lock_level++;
315 return;
316 }
317 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
318 {
319 PyThreadState *tstate = PyEval_SaveThread();
320 PyThread_acquire_lock(import_lock, 1);
321 PyEval_RestoreThread(tstate);
322 }
323 import_lock_thread = me;
324 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000325}
326
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000327int
328_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 long me = PyThread_get_thread_ident();
331 if (me == -1 || import_lock == NULL)
332 return 0; /* Too bad */
333 if (import_lock_thread != me)
334 return -1;
335 import_lock_level--;
336 if (import_lock_level == 0) {
337 import_lock_thread = -1;
338 PyThread_release_lock(import_lock);
339 }
340 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000341}
342
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000343/* This function is called from PyOS_AfterFork to ensure that newly
344 created child processes do not share locks with the parent.
345 We now acquire the import lock around fork() calls but on some platforms
346 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000347
348void
349_PyImport_ReInitLock(void)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (import_lock != NULL)
352 import_lock = PyThread_allocate_lock();
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000353 if (import_lock_level > 1) {
354 /* Forked as a side effect of import */
355 long me = PyThread_get_thread_ident();
356 PyThread_acquire_lock(import_lock, 0);
Victor Stinner942003c2011-03-07 16:57:48 +0100357 /* XXX: can the previous line fail? */
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000358 import_lock_thread = me;
359 import_lock_level--;
360 } else {
361 import_lock_thread = -1;
362 import_lock_level = 0;
363 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000364}
365
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000366#endif
367
Tim Peters69232342001-08-30 05:16:13 +0000368static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000369imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000370{
Tim Peters69232342001-08-30 05:16:13 +0000371#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000373#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000375#endif
376}
377
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000378static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000379imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000380{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000381#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000383#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_INCREF(Py_None);
385 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000386}
387
388static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000389imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000390{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000391#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (_PyImport_ReleaseLock() < 0) {
393 PyErr_SetString(PyExc_RuntimeError,
394 "not holding the import lock");
395 return NULL;
396 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 Py_INCREF(Py_None);
399 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000400}
401
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100402void
403_PyImport_Fini(void)
404{
405 Py_XDECREF(extensions);
406 extensions = NULL;
407 PyMem_DEL(_PyImport_Filetab);
408 _PyImport_Filetab = NULL;
409#ifdef WITH_THREAD
410 if (import_lock != NULL) {
411 PyThread_free_lock(import_lock);
412 import_lock = NULL;
413 }
414#endif
415}
416
Guido van Rossumd8faa362007-04-27 19:54:29 +0000417static void
418imp_modules_reloading_clear(void)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyInterpreterState *interp = PyThreadState_Get()->interp;
421 if (interp->modules_reloading != NULL)
422 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423}
424
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425/* Helper for sys */
426
427PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000428PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyInterpreterState *interp = PyThreadState_GET()->interp;
431 if (interp->modules == NULL)
432 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
433 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000434}
435
Guido van Rossum3f5da241990-12-20 15:06:42 +0000436
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000437/* List of names to clear in sys */
438static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 "path", "argv", "ps1", "ps2",
440 "last_type", "last_value", "last_traceback",
441 "path_hooks", "path_importer_cache", "meta_path",
442 /* misc stuff */
443 "flags", "float_info",
444 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000445};
446
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000447static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 "stdin", "__stdin__",
449 "stdout", "__stdout__",
450 "stderr", "__stderr__",
451 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000452};
453
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000454
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000455/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000456
Guido van Rossum3f5da241990-12-20 15:06:42 +0000457void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000458PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_ssize_t pos, ndone;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyObject *key, *value, *dict;
462 PyInterpreterState *interp = PyThreadState_GET()->interp;
463 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (modules == NULL)
466 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* Delete some special variables first. These are common
469 places where user values hide and people complain when their
470 destructors fail. Since the modules containing them are
471 deleted *last* of all, they would come too late in the normal
472 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 value = PyDict_GetItemString(modules, "builtins");
475 if (value != NULL && PyModule_Check(value)) {
476 dict = PyModule_GetDict(value);
477 if (Py_VerboseFlag)
478 PySys_WriteStderr("# clear builtins._\n");
479 PyDict_SetItemString(dict, "_", Py_None);
480 }
481 value = PyDict_GetItemString(modules, "sys");
482 if (value != NULL && PyModule_Check(value)) {
483 char **p;
484 PyObject *v;
485 dict = PyModule_GetDict(value);
486 for (p = sys_deletes; *p != NULL; p++) {
487 if (Py_VerboseFlag)
488 PySys_WriteStderr("# clear sys.%s\n", *p);
489 PyDict_SetItemString(dict, *p, Py_None);
490 }
491 for (p = sys_files; *p != NULL; p+=2) {
492 if (Py_VerboseFlag)
493 PySys_WriteStderr("# restore sys.%s\n", *p);
494 v = PyDict_GetItemString(dict, *(p+1));
495 if (v == NULL)
496 v = Py_None;
497 PyDict_SetItemString(dict, *p, v);
498 }
499 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* First, delete __main__ */
502 value = PyDict_GetItemString(modules, "__main__");
503 if (value != NULL && PyModule_Check(value)) {
504 if (Py_VerboseFlag)
505 PySys_WriteStderr("# cleanup __main__\n");
506 _PyModule_Clear(value);
507 PyDict_SetItemString(modules, "__main__", Py_None);
508 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* The special treatment of "builtins" here is because even
511 when it's not referenced as a module, its dictionary is
512 referenced by almost every module's __builtins__. Since
513 deleting a module clears its dictionary (even if there are
514 references left to it), we need to delete the "builtins"
515 module last. Likewise, we don't delete sys until the very
516 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Also note that we 'delete' modules by replacing their entry
519 in the modules dict with None, rather than really deleting
520 them; this avoids a rehash of the modules dictionary and
521 also marks them as "non existent" so they won't be
522 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Next, repeatedly delete modules with a reference count of
525 one (skipping builtins and sys) and delete them */
526 do {
527 ndone = 0;
528 pos = 0;
529 while (PyDict_Next(modules, &pos, &key, &value)) {
530 if (value->ob_refcnt != 1)
531 continue;
532 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100533 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100535 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 continue;
537 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100538 PySys_FormatStderr(
539 "# cleanup[1] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 _PyModule_Clear(value);
541 PyDict_SetItem(modules, key, Py_None);
542 ndone++;
543 }
544 }
545 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* Next, delete all modules (still skipping builtins and sys) */
548 pos = 0;
549 while (PyDict_Next(modules, &pos, &key, &value)) {
550 if (PyUnicode_Check(key) && PyModule_Check(value)) {
Victor Stinner9464d612011-03-07 17:08:21 +0100551 if (PyUnicode_CompareWithASCIIString(key, "builtins") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 continue;
Victor Stinner9464d612011-03-07 17:08:21 +0100553 if (PyUnicode_CompareWithASCIIString(key, "sys") == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 continue;
555 if (Py_VerboseFlag)
Victor Stinner9464d612011-03-07 17:08:21 +0100556 PySys_FormatStderr("# cleanup[2] %U\n", key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 _PyModule_Clear(value);
558 PyDict_SetItem(modules, key, Py_None);
559 }
560 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* Next, delete sys and builtins (in that order) */
563 value = PyDict_GetItemString(modules, "sys");
564 if (value != NULL && PyModule_Check(value)) {
565 if (Py_VerboseFlag)
566 PySys_WriteStderr("# cleanup sys\n");
567 _PyModule_Clear(value);
568 PyDict_SetItemString(modules, "sys", Py_None);
569 }
570 value = PyDict_GetItemString(modules, "builtins");
571 if (value != NULL && PyModule_Check(value)) {
572 if (Py_VerboseFlag)
573 PySys_WriteStderr("# cleanup builtins\n");
574 _PyModule_Clear(value);
575 PyDict_SetItemString(modules, "builtins", Py_None);
576 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Finally, clear and delete the modules directory */
579 PyDict_Clear(modules);
580 interp->modules = NULL;
581 Py_DECREF(modules);
582 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000583}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000584
585
Barry Warsaw28a691b2010-04-17 00:19:56 +0000586/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
588long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000589PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000592}
593
594
Barry Warsaw28a691b2010-04-17 00:19:56 +0000595const char *
596PyImport_GetMagicTag(void)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000599}
600
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601/* Magic for extension modules (built-in as well as dynamically
602 loaded). To prevent initializing an extension module more than
603 once, we keep a static dictionary 'extensions' keyed by module name
604 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000605 modules), containing these modules. A copy of the module's
Victor Stinner95872862011-03-07 18:20:56 +0100606 dictionary is stored by calling _PyImport_FixupExtensionObject()
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607 immediately after the module initialization function succeeds. A
608 copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100609 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000611 Modules which do support multiple initialization set their m_size
612 field to a non-negative number (indicating the size of the
613 module-specific state). They are still recorded in the extensions
614 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000615*/
616
617int
Victor Stinner95872862011-03-07 18:20:56 +0100618_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
619 PyObject *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *modules, *dict;
622 struct PyModuleDef *def;
623 if (extensions == NULL) {
624 extensions = PyDict_New();
625 if (extensions == NULL)
626 return -1;
627 }
628 if (mod == NULL || !PyModule_Check(mod)) {
629 PyErr_BadInternalCall();
630 return -1;
631 }
632 def = PyModule_GetDef(mod);
633 if (!def) {
634 PyErr_BadInternalCall();
635 return -1;
636 }
637 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +0100638 if (PyDict_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return -1;
640 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100641 PyDict_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return -1;
643 }
644 if (def->m_size == -1) {
645 if (def->m_base.m_copy) {
646 /* Somebody already imported the module,
647 likely under a different name.
648 XXX this should really not happen. */
649 Py_DECREF(def->m_base.m_copy);
650 def->m_base.m_copy = NULL;
651 }
652 dict = PyModule_GetDict(mod);
653 if (dict == NULL)
654 return -1;
655 def->m_base.m_copy = PyDict_Copy(dict);
656 if (def->m_base.m_copy == NULL)
657 return -1;
658 }
Victor Stinner49d3f252010-10-17 01:24:53 +0000659 PyDict_SetItem(extensions, filename, (PyObject*)def);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661}
662
Victor Stinner49d3f252010-10-17 01:24:53 +0000663int
664_PyImport_FixupBuiltin(PyObject *mod, char *name)
665{
666 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100667 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100668 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100669 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000670 return -1;
Victor Stinner95872862011-03-07 18:20:56 +0100671 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj);
672 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000673 return res;
674}
675
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100677_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *mod, *mdict;
680 PyModuleDef* def;
681 if (extensions == NULL)
682 return NULL;
Victor Stinner49d3f252010-10-17 01:24:53 +0000683 def = (PyModuleDef*)PyDict_GetItem(extensions, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (def == NULL)
685 return NULL;
686 if (def->m_size == -1) {
687 /* Module does not support repeated initialization */
688 if (def->m_base.m_copy == NULL)
689 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100690 mod = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (mod == NULL)
692 return NULL;
693 mdict = PyModule_GetDict(mod);
694 if (mdict == NULL)
695 return NULL;
696 if (PyDict_Update(mdict, def->m_base.m_copy))
697 return NULL;
698 }
699 else {
700 if (def->m_base.m_init == NULL)
701 return NULL;
702 mod = def->m_base.m_init();
703 if (mod == NULL)
704 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100705 PyDict_SetItem(PyImport_GetModuleDict(), name, mod);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_DECREF(mod);
707 }
708 if (_PyState_AddModule(mod, def) < 0) {
Victor Stinner95872862011-03-07 18:20:56 +0100709 PyDict_DelItem(PyImport_GetModuleDict(), name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_DECREF(mod);
711 return NULL;
712 }
713 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100714 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 name, filename);
716 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000717
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718}
719
Victor Stinner49d3f252010-10-17 01:24:53 +0000720PyObject *
Victor Stinner501c09a2011-02-23 00:02:00 +0000721_PyImport_FindBuiltin(const char *name)
Victor Stinner49d3f252010-10-17 01:24:53 +0000722{
Victor Stinner95872862011-03-07 18:20:56 +0100723 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100724 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100725 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000726 return NULL;
Victor Stinner95872862011-03-07 18:20:56 +0100727 res = _PyImport_FindExtensionObject(nameobj, nameobj);
728 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000729 return res;
730}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731
732/* Get the module object corresponding to a module name.
733 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000734 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000735 Because the former action is most common, THIS DOES NOT RETURN A
736 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000739PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyObject *modules = PyImport_GetModuleDict();
742 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743
Victor Stinner27ee0892011-03-04 12:57:09 +0000744 if ((m = PyDict_GetItem(modules, name)) != NULL &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyModule_Check(m))
746 return m;
Victor Stinner27ee0892011-03-04 12:57:09 +0000747 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (m == NULL)
749 return NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000750 if (PyDict_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 Py_DECREF(m);
752 return NULL;
753 }
754 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757}
758
Victor Stinner27ee0892011-03-04 12:57:09 +0000759PyObject *
760PyImport_AddModule(const char *name)
761{
762 PyObject *nameobj, *module;
763 nameobj = PyUnicode_FromString(name);
764 if (nameobj == NULL)
765 return NULL;
766 module = PyImport_AddModuleObject(nameobj);
767 Py_DECREF(nameobj);
768 return module;
769}
770
771
Tim Peters1cd70172004-08-02 03:52:12 +0000772/* Remove name from sys.modules, if it's there. */
773static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000774remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject *modules = PyImport_GetModuleDict();
Victor Stinner27ee0892011-03-04 12:57:09 +0000777 if (PyDict_GetItem(modules, name) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 return;
Victor Stinner27ee0892011-03-04 12:57:09 +0000779 if (PyDict_DelItem(modules, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 Py_FatalError("import: deleting existing key in"
781 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000782}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000783
Victor Stinnerc9abda02011-03-14 13:33:46 -0400784static PyObject * get_sourcefile(PyObject *filename);
785static PyObject *make_source_pathname(PyObject *pathname);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200786static PyObject* make_compiled_pathname(PyObject *pathname, int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000787
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000788/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000789 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
790 * removed from sys.modules, to avoid leaving damaged module objects
791 * in sys.modules. The caller may wish to restore the original
792 * module object (if any) in this case; PyImport_ReloadModule is an
793 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000794 *
795 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
796 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000797 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000798PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000799PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return PyImport_ExecCodeModuleWithPathnames(
802 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000803}
804
805PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000806PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return PyImport_ExecCodeModuleWithPathnames(
809 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000810}
811
812PyObject *
813PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000815{
Victor Stinner27ee0892011-03-04 12:57:09 +0000816 PyObject *m = NULL;
817 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL;
818
819 nameobj = PyUnicode_FromString(name);
820 if (nameobj == NULL)
821 return NULL;
822
823 if (pathname != NULL) {
824 pathobj = PyUnicode_DecodeFSDefault(pathname);
825 if (pathobj == NULL)
826 goto error;
827 } else
828 pathobj = NULL;
829 if (cpathname != NULL) {
830 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
831 if (cpathobj == NULL)
832 goto error;
833 } else
834 cpathobj = NULL;
835 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
836error:
837 Py_DECREF(nameobj);
838 Py_XDECREF(pathobj);
839 Py_XDECREF(cpathobj);
840 return m;
841}
842
843PyObject*
844PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
845 PyObject *cpathname)
846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 PyObject *modules = PyImport_GetModuleDict();
848 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000849
Victor Stinner27ee0892011-03-04 12:57:09 +0000850 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (m == NULL)
852 return NULL;
853 /* If the module is being reloaded, we get the old module back
854 and re-use its dict to exec the new code. */
855 d = PyModule_GetDict(m);
856 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
857 if (PyDict_SetItemString(d, "__builtins__",
858 PyEval_GetBuiltins()) != 0)
859 goto error;
860 }
861 /* Remember the filename as the __file__ attribute */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (pathname != NULL) {
Victor Stinnerc9abda02011-03-14 13:33:46 -0400863 v = get_sourcefile(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (v == NULL)
865 PyErr_Clear();
866 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000867 else
868 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (v == NULL) {
870 v = ((PyCodeObject *)co)->co_filename;
871 Py_INCREF(v);
872 }
873 if (PyDict_SetItemString(d, "__file__", v) != 0)
874 PyErr_Clear(); /* Not important enough to report */
875 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Remember the pyc path name as the __cached__ attribute. */
Victor Stinner27ee0892011-03-04 12:57:09 +0000878 if (cpathname != NULL)
879 v = cpathname;
880 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 v = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (PyDict_SetItemString(d, "__cached__", v) != 0)
883 PyErr_Clear(); /* Not important enough to report */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000884
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000885 v = PyEval_EvalCode(co, d, d);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (v == NULL)
887 goto error;
888 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000889
Victor Stinner27ee0892011-03-04 12:57:09 +0000890 if ((m = PyDict_GetItem(modules, name)) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 PyErr_Format(PyExc_ImportError,
Victor Stinner27ee0892011-03-04 12:57:09 +0000892 "Loaded module %R not found in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 name);
894 return NULL;
895 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000900
901 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 remove_module(name);
903 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904}
905
906
Barry Warsaw28a691b2010-04-17 00:19:56 +0000907/* Like strrchr(string, '/') but searches for the rightmost of either SEP
908 or ALTSEP, if the latter is defined.
909*/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200910static Py_UCS4*
911rightmost_sep(Py_UCS4 *s)
Victor Stinnerc9abda02011-03-14 13:33:46 -0400912{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200913 Py_UCS4 *found, c;
Victor Stinnerc9abda02011-03-14 13:33:46 -0400914 for (found = NULL; (c = *s); s++) {
915 if (c == SEP
916#ifdef ALTSEP
917 || c == ALTSEP
918#endif
919 )
920 {
921 found = s;
922 }
923 }
924 return found;
925}
926
Martin v. Löwis2db72862011-10-23 17:29:08 +0200927/* Like rightmost_sep, but operate on unicode objects. */
928static Py_ssize_t
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200929rightmost_sep_obj(PyObject* o, Py_ssize_t start, Py_ssize_t end)
Martin v. Löwis2db72862011-10-23 17:29:08 +0200930{
931 Py_ssize_t found, i;
932 Py_UCS4 c;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200933 for (found = -1, i = start; i < end; i++) {
Martin v. Löwis2db72862011-10-23 17:29:08 +0200934 c = PyUnicode_READ_CHAR(o, i);
935 if (c == SEP
936#ifdef ALTSEP
937 || c == ALTSEP
938#endif
939 )
940 {
941 found = i;
942 }
943 }
944 return found;
945}
Victor Stinnerc9abda02011-03-14 13:33:46 -0400946
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000947/* Given a pathname for a Python source file, fill a buffer with the
948 pathname for the corresponding compiled file. Return the pathname
949 for the compiled file, or NULL if there's no space in the buffer.
Victor Stinner2f42ae52011-03-20 00:41:24 +0100950 Doesn't set an exception.
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000951
Martin v. Löwis30260a72011-10-23 17:35:46 +0200952 foo.py -> __pycache__/foo.<tag>.pyc
953
954 pathstr is assumed to be "ready".
955*/
Victor Stinner2f42ae52011-03-20 00:41:24 +0100956
957static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958make_compiled_pathname(PyObject *pathstr, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000959{
Martin v. Löwis2db72862011-10-23 17:29:08 +0200960 PyObject *result;
961 Py_ssize_t fname, ext, len, i, pos, taglen;
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200962 Py_ssize_t pycache_len = sizeof(CACHEDIR) - 1;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200963 int kind;
964 void *data;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200965 Py_UCS4 lastsep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000966
Martin v. Löwis2db72862011-10-23 17:29:08 +0200967 /* Compute the output string size. */
968 len = PyUnicode_GET_LENGTH(pathstr);
969 /* If there is no separator, this returns -1, so
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200970 fname will be 0. */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +0200971 fname = rightmost_sep_obj(pathstr, 0, len) + 1;
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200972 /* Windows: re-use the last separator character (/ or \\) when
973 appending the __pycache__ path. */
974 if (fname > 0)
975 lastsep = PyUnicode_READ_CHAR(pathstr, fname -1);
976 else
977 lastsep = SEP;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200978 ext = fname - 1;
979 for(i = fname; i < len; i++)
980 if (PyUnicode_READ_CHAR(pathstr, i) == '.')
981 ext = i + 1;
982 if (ext < fname)
983 /* No dot in filename; use entire filename */
984 ext = len;
985
986 /* result = pathstr[:fname] + "__pycache__" + SEP +
987 pathstr[fname:ext] + tag + ".py[co]" */
988 taglen = strlen(pyc_tag);
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200989 result = PyUnicode_New(ext + pycache_len + 1 + taglen + 4,
Martin v. Löwis2db72862011-10-23 17:29:08 +0200990 PyUnicode_MAX_CHAR_VALUE(pathstr));
991 if (!result)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992 return NULL;
Martin v. Löwis2db72862011-10-23 17:29:08 +0200993 kind = PyUnicode_KIND(result);
994 data = PyUnicode_DATA(result);
995 PyUnicode_CopyCharacters(result, 0, pathstr, 0, fname);
996 pos = fname;
Martin v. Löwis2cc0cc52011-10-23 18:41:56 +0200997 for (i = 0; i < pycache_len; i++)
Martin v. Löwisfadcd312011-10-23 18:08:20 +0200998 PyUnicode_WRITE(kind, data, pos++, CACHEDIR[i]);
Antoine Pitroub528fcf2011-10-25 00:21:02 +0200999 PyUnicode_WRITE(kind, data, pos++, lastsep);
Martin v. Löwis2db72862011-10-23 17:29:08 +02001000 PyUnicode_CopyCharacters(result, pos, pathstr,
1001 fname, ext - fname);
1002 pos += ext - fname;
1003 for (i = 0; pyc_tag[i]; i++)
1004 PyUnicode_WRITE(kind, data, pos++, pyc_tag[i]);
1005 PyUnicode_WRITE(kind, data, pos++, '.');
1006 PyUnicode_WRITE(kind, data, pos++, 'p');
1007 PyUnicode_WRITE(kind, data, pos++, 'y');
1008 PyUnicode_WRITE(kind, data, pos++, debug ? 'c' : 'o');
1009 return result;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001010}
1011
1012
Barry Warsaw28a691b2010-04-17 00:19:56 +00001013/* Given a pathname to a Python byte compiled file, return the path to the
1014 source file, if the path matches the PEP 3147 format. This does not check
1015 for any file existence, however, if the pyc file name does not match PEP
1016 3147 style, NULL is returned. buf must be at least as big as pathname;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001017 the resulting path will always be shorter.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018
Victor Stinnerc9abda02011-03-14 13:33:46 -04001019 (...)/__pycache__/foo.<tag>.pyc -> (...)/foo.py */
1020
1021static PyObject*
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001022make_source_pathname(PyObject *path)
Barry Warsaw28a691b2010-04-17 00:19:56 +00001023{
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001024 Py_ssize_t left, right, dot0, dot1, len;
1025 Py_ssize_t i, j;
1026 PyObject *result;
1027 int kind;
1028 void *data;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001029
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001030 len = PyUnicode_GET_LENGTH(path);
1031 if (len > MAXPATHLEN)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001032 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 /* Look back two slashes from the end. In between these two slashes
1035 must be the string __pycache__ or this is not a PEP 3147 style
1036 path. It's possible for there to be only one slash.
1037 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001038 right = rightmost_sep_obj(path, 0, len);
1039 if (right == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return NULL;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001041 left = rightmost_sep_obj(path, 0, right);
1042 if (left == -1)
1043 left = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 else
1045 left++;
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001046 if (right-left != sizeof(CACHEDIR)-1)
1047 return NULL;
1048 for (i = 0; i < sizeof(CACHEDIR)-1; i++)
1049 if (PyUnicode_READ_CHAR(path, left+i) != CACHEDIR[i])
1050 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 /* Now verify that the path component to the right of the last slash
1053 has two dots in it.
1054 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001055 dot0 = PyUnicode_FindChar(path, '.', right+1, len, 1);
1056 if (dot0 < 0)
1057 return NULL;
1058 dot1 = PyUnicode_FindChar(path, '.', dot0+1, len, 1);
1059 if (dot1 < 0)
1060 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 /* Too many dots? */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001062 if (PyUnicode_FindChar(path, '.', dot1+1, len, 1) != -1)
1063 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 /* This is a PEP 3147 path. Start by copying everything from the
1066 start of pathname up to and including the leftmost slash. Then
1067 copy the file's basename, removing the magic tag and adding a .py
1068 suffix.
1069 */
Martin v. Löwis8a0ef782011-10-23 18:05:06 +02001070 result = PyUnicode_New(left + (dot0-right) + 2,
1071 PyUnicode_MAX_CHAR_VALUE(path));
1072 if (!result)
1073 return NULL;
1074 kind = PyUnicode_KIND(result);
1075 data = PyUnicode_DATA(result);
1076 PyUnicode_CopyCharacters(result, 0, path, 0, (i = left));
1077 PyUnicode_CopyCharacters(result, left, path, right+1,
1078 (j = dot0-right));
1079 PyUnicode_WRITE(kind, data, i+j, 'p');
1080 PyUnicode_WRITE(kind, data, i+j+1, 'y');
1081 return result;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001082}
1083
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001084/* Given a pathname for a Python source file, its time of last
1085 modification, and a pathname for a compiled file, check whether the
1086 compiled file represents the same version of the source. If so,
1087 return a FILE pointer for the compiled file, positioned just after
1088 the header; if not, return NULL.
1089 Doesn't set an exception. */
1090
1091static FILE *
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001092check_compiled_module(PyObject *pathname, struct stat *srcstat, PyObject *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 FILE *fp;
1095 long magic;
1096 long pyc_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001097 long pyc_size;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001098
Victor Stinner2f42ae52011-03-20 00:41:24 +01001099 fp = _Py_fopen(cpathname, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (fp == NULL)
1101 return NULL;
1102 magic = PyMarshal_ReadLongFromFile(fp);
1103 if (magic != pyc_magic) {
1104 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001105 PySys_FormatStderr("# %R has bad magic\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 fclose(fp);
1107 return NULL;
1108 }
1109 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001110 if (pyc_mtime != srcstat->st_mtime) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001112 PySys_FormatStderr("# %R has bad mtime\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 fclose(fp);
1114 return NULL;
1115 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001116 pyc_size = PyMarshal_ReadLongFromFile(fp);
1117 if (pyc_size != (srcstat->st_size & 0xFFFFFFFF)) {
1118 if (Py_VerboseFlag)
1119 PySys_FormatStderr("# %R has bad size\n", cpathname);
1120 fclose(fp);
1121 return NULL;
1122 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001124 PySys_FormatStderr("# %R matches %R\n", cpathname, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001126}
1127
1128
1129/* Read a code object from a file and check it for validity */
1130
Guido van Rossum79f25d91997-04-29 20:08:16 +00001131static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001132read_compiled_module(PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 co = PyMarshal_ReadLastObjectFromFile(fp);
1137 if (co == NULL)
1138 return NULL;
1139 if (!PyCode_Check(co)) {
1140 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001141 "Non-code object in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 Py_DECREF(co);
1143 return NULL;
1144 }
1145 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001146}
1147
1148
1149/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001150 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001151
Guido van Rossum79f25d91997-04-29 20:08:16 +00001152static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001153load_compiled_module(PyObject *name, PyObject *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 long magic;
1156 PyCodeObject *co;
1157 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 magic = PyMarshal_ReadLongFromFile(fp);
1160 if (magic != pyc_magic) {
1161 PyErr_Format(PyExc_ImportError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001162 "Bad magic number in %R", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return NULL;
1164 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001165 /* Skip mtime and size */
1166 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 (void) PyMarshal_ReadLongFromFile(fp);
1168 co = read_compiled_module(cpathname, fp);
1169 if (co == NULL)
1170 return NULL;
1171 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001172 PySys_FormatStderr("import %U # precompiled from %R\n",
1173 name, cpathname);
1174 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1175 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001179}
1180
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001181/* Parse a source file and return the corresponding code object */
1182
Guido van Rossum79f25d91997-04-29 20:08:16 +00001183static PyCodeObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001184parse_source_module(PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001185{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001186 PyCodeObject *co;
1187 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 mod_ty mod;
1189 PyCompilerFlags flags;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001190 PyArena *arena;
1191
1192 pathbytes = PyUnicode_EncodeFSDefault(pathname);
1193 if (pathbytes == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001195
Victor Stinner2f42ae52011-03-20 00:41:24 +01001196 arena = PyArena_New();
1197 if (arena == NULL) {
1198 Py_DECREF(pathbytes);
1199 return NULL;
1200 }
1201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 flags.cf_flags = 0;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001203 mod = PyParser_ASTFromFile(fp, PyBytes_AS_STRING(pathbytes), NULL,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_file_input, 0, 0, &flags,
1205 NULL, arena);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001206 if (mod != NULL)
1207 co = PyAST_Compile(mod, PyBytes_AS_STRING(pathbytes), NULL, arena);
1208 else
1209 co = NULL;
1210 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 PyArena_Free(arena);
1212 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001213}
1214
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001215/* Write a compiled module to a file, placing the time of last
1216 modification of its source into the header.
1217 Errors are ignored, if a write error occurs an attempt is made to
1218 remove the file. */
1219
1220static void
Victor Stinner2f42ae52011-03-20 00:41:24 +01001221write_compiled_module(PyCodeObject *co, PyObject *cpathname,
1222 struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 Py_UCS4 *cpathname_ucs4;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 time_t mtime = srcstat->st_mtime;
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001227 long size = srcstat->st_size & 0xFFFFFFFF;
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001228 PyObject *cpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001229#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Victor Stinner1f795172011-11-17 00:45:54 +01001231 wchar_t *wdirname, *wpathname, *wpathname_tmp;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001232#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 mode_t dirmode = (srcstat->st_mode |
1234 S_IXUSR | S_IXGRP | S_IXOTH |
1235 S_IWUSR | S_IWGRP | S_IWOTH);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001236 PyObject *dirbytes;
Antoine Pitrou707033a2011-10-17 19:28:44 +02001237 PyObject *cpathbytes, *cpathbytes_tmp;
Victor Stinner783c82c2011-04-20 03:27:51 +02001238#endif
Charles-François Natali0c929d92011-11-10 19:12:29 +01001239 int fd;
Victor Stinner783c82c2011-04-20 03:27:51 +02001240 PyObject *dirname;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241 Py_UCS4 *dirsep;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001242 int res, ok;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 /* Ensure that the __pycache__ directory exists. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001245 cpathname_ucs4 = PyUnicode_AsUCS4Copy(cpathname);
1246 if (!cpathname_ucs4)
1247 return;
1248 dirsep = rightmost_sep(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001249 if (dirsep == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001251 PySys_FormatStderr("# no %s path found %R\n", CACHEDIR, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 return;
1253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254 dirname = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
1255 cpathname_ucs4,
1256 dirsep - cpathname_ucs4);
1257 PyMem_Free(cpathname_ucs4);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001258 if (dirname == NULL) {
1259 PyErr_Clear();
1260 return;
1261 }
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001262
1263#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001264 wdirname = PyUnicode_AsUnicode(dirname);
1265 if (wdirname == NULL) {
1266 PyErr_Clear();
1267 return;
1268 }
1269 res = CreateDirectoryW(wdirname, NULL);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001270 ok = (res != 0);
1271 if (!ok && GetLastError() == ERROR_ALREADY_EXISTS)
1272 ok = 1;
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001273#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001274 dirbytes = PyUnicode_EncodeFSDefault(dirname);
1275 if (dirbytes == NULL) {
1276 PyErr_Clear();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return;
1278 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001279 res = mkdir(PyBytes_AS_STRING(dirbytes), dirmode);
1280 Py_DECREF(dirbytes);
1281 if (0 <= res)
1282 ok = 1;
1283 else
1284 ok = (errno == EEXIST);
1285#endif
1286 if (!ok) {
1287 if (Py_VerboseFlag)
1288 PySys_FormatStderr("# cannot create cache dir %R\n", dirname);
1289 Py_DECREF(dirname);
1290 return;
1291 }
1292 Py_DECREF(dirname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001293
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001294 /* We first write to a tmp file and then take advantage
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001295 of atomic renaming (which *should* be true even under Windows).
1296 As in importlib, we use id(something) to generate a pseudo-random
1297 filename. mkstemp() can't be used since it doesn't allow specifying
1298 the file access permissions.
1299 */
1300 cpathname_tmp = PyUnicode_FromFormat("%U.%zd",
1301 cpathname, (Py_ssize_t) co);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001302 if (cpathname_tmp == NULL) {
1303 PyErr_Clear();
1304 return;
1305 }
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001306#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001307 wpathname = PyUnicode_AsUnicode(cpathname);
1308 if (wpathname == NULL) {
1309 PyErr_Clear();
1310 return;
1311 }
1312 wpathname_tmp = PyUnicode_AsUnicode(cpathname_tmp);
1313 if (wpathname_tmp == NULL) {
1314 PyErr_Clear();
1315 return;
1316 }
1317
1318 (void)DeleteFileW(wpathname_tmp);
1319 fd = _wopen(wpathname_tmp,
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001320 O_EXCL | O_CREAT | O_WRONLY | O_BINARY,
1321 mode);
Victor Stinner783c82c2011-04-20 03:27:51 +02001322 if (0 <= fd)
1323 fp = fdopen(fd, "wb");
1324 else
1325 fp = NULL;
1326#else
Antoine Pitrou8ad982c2011-11-15 22:27:32 +01001327 cpathbytes_tmp = PyUnicode_EncodeFSDefault(cpathname_tmp);
1328 Py_DECREF(cpathname_tmp);
1329 if (cpathbytes_tmp == NULL) {
1330 PyErr_Clear();
1331 return;
1332 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001333 cpathbytes = PyUnicode_EncodeFSDefault(cpathname);
1334 if (cpathbytes == NULL) {
1335 PyErr_Clear();
1336 return;
1337 }
Charles-François Natali0c929d92011-11-10 19:12:29 +01001338 fd = open(PyBytes_AS_STRING(cpathbytes_tmp),
1339 O_CREAT | O_EXCL | O_WRONLY, 0666);
Charles-François Natalie695eec2011-10-31 20:47:31 +01001340 if (0 <= fd)
1341 fp = fdopen(fd, "wb");
1342 else
1343 fp = NULL;
Victor Stinner783c82c2011-04-20 03:27:51 +02001344#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (fp == NULL) {
1346 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001347 PySys_FormatStderr(
1348 "# can't create %R\n", cpathname);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001349#ifdef MS_WINDOWS
1350 Py_DECREF(cpathname_tmp);
1351#else
Victor Stinner2f42ae52011-03-20 00:41:24 +01001352 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001353 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001354#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return;
1356 }
1357 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001358 /* First write a 0 for mtime and size */
1359 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1361 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001362 fflush(fp);
Antoine Pitrou58161662012-01-25 18:06:07 +01001363 /* Now write the true mtime and size (as 32-bit fields) */
Antoine Pitrou707033a2011-10-17 19:28:44 +02001364 fseek(fp, 4L, 0);
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001365 assert(mtime <= 0xFFFFFFFF);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001366 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001367 PyMarshal_WriteLongToFile(size, fp, Py_MARSHAL_VERSION);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (fflush(fp) != 0 || ferror(fp)) {
1369 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001370 PySys_FormatStderr("# can't write %R\n", cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* Don't keep partial file */
1372 fclose(fp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001373#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001374 (void)DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001375 Py_DECREF(cpathname_tmp);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001376#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001377 (void) unlink(PyBytes_AS_STRING(cpathbytes_tmp));
Victor Stinner2f42ae52011-03-20 00:41:24 +01001378 Py_DECREF(cpathbytes);
Antoine Pitrou707033a2011-10-17 19:28:44 +02001379 Py_DECREF(cpathbytes_tmp);
Victor Stinner783c82c2011-04-20 03:27:51 +02001380#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 return;
1382 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 fclose(fp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001384 /* Do a (hopefully) atomic rename */
1385#ifdef MS_WINDOWS
Victor Stinner1f795172011-11-17 00:45:54 +01001386 if (!MoveFileExW(wpathname_tmp, wpathname, MOVEFILE_REPLACE_EXISTING)) {
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001387 if (Py_VerboseFlag)
1388 PySys_FormatStderr("# can't write %R\n", cpathname);
1389 /* Don't keep tmp file */
Victor Stinner1f795172011-11-17 00:45:54 +01001390 (void) DeleteFileW(wpathname_tmp);
Antoine Pitrou28e401e2011-11-15 19:15:19 +01001391 Py_DECREF(cpathname_tmp);
1392 return;
1393 }
1394 Py_DECREF(cpathname_tmp);
1395#else
Antoine Pitrou707033a2011-10-17 19:28:44 +02001396 if (rename(PyBytes_AS_STRING(cpathbytes_tmp),
1397 PyBytes_AS_STRING(cpathbytes))) {
1398 if (Py_VerboseFlag)
1399 PySys_FormatStderr("# can't write %R\n", cpathname);
1400 /* Don't keep tmp file */
1401 unlink(PyBytes_AS_STRING(cpathbytes_tmp));
1402 Py_DECREF(cpathbytes);
1403 Py_DECREF(cpathbytes_tmp);
1404 return;
1405 }
1406 Py_DECREF(cpathbytes);
1407 Py_DECREF(cpathbytes_tmp);
1408#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001410 PySys_FormatStderr("# wrote %R\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001411}
1412
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001413static void
1414update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyObject *constants, *tmp;
1417 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (PyUnicode_Compare(co->co_filename, oldname))
1420 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 tmp = co->co_filename;
1423 co->co_filename = newname;
1424 Py_INCREF(co->co_filename);
1425 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 constants = co->co_consts;
1428 n = PyTuple_GET_SIZE(constants);
1429 for (i = 0; i < n; i++) {
1430 tmp = PyTuple_GET_ITEM(constants, i);
1431 if (PyCode_Check(tmp))
1432 update_code_filenames((PyCodeObject *)tmp,
1433 oldname, newname);
1434 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001435}
1436
Victor Stinner2f42ae52011-03-20 00:41:24 +01001437static void
1438update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001439{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001440 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001441
Victor Stinner2f42ae52011-03-20 00:41:24 +01001442 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1443 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 oldname = co->co_filename;
1446 Py_INCREF(oldname);
1447 update_code_filenames(co, oldname, newname);
1448 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001449}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001450
Brett Cannon442c9b92011-03-23 16:14:42 -07001451static PyObject *
1452imp_fix_co_filename(PyObject *self, PyObject *args)
1453{
1454 PyObject *co;
1455 PyObject *file_path;
1456
1457 if (!PyArg_ParseTuple(args, "OO:_fix_co_filename", &co, &file_path))
1458 return NULL;
1459
1460 if (!PyCode_Check(co)) {
1461 PyErr_SetString(PyExc_TypeError,
1462 "first argument must be a code object");
1463 return NULL;
1464 }
1465
1466 if (!PyUnicode_Check(file_path)) {
1467 PyErr_SetString(PyExc_TypeError,
1468 "second argument must be a string");
1469 return NULL;
1470 }
1471
1472 update_compiled_module((PyCodeObject*)co, file_path);
1473
1474 Py_RETURN_NONE;
1475}
1476
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001477/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001478 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1479 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001480
Guido van Rossum79f25d91997-04-29 20:08:16 +00001481static PyObject *
Victor Stinner2f42ae52011-03-20 00:41:24 +01001482load_source_module(PyObject *name, PyObject *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 struct stat st;
1485 FILE *fpc;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001486 PyObject *cpathname = NULL, *cpathbytes = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyCodeObject *co;
Victor Stinner2f42ae52011-03-20 00:41:24 +01001488 PyObject *m = NULL;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (fstat(fileno(fp), &st) != 0) {
1491 PyErr_Format(PyExc_RuntimeError,
Victor Stinner2f42ae52011-03-20 00:41:24 +01001492 "unable to get file status from %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001494 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 }
Antoine Pitrou33d15f72012-01-25 18:01:45 +01001496 if (sizeof st.st_mtime > 4) {
1497 /* Python's .pyc timestamp handling presumes that the timestamp fits
1498 in 4 bytes. Since the code only does an equality comparison,
1499 ordering is not important and we can safely ignore the higher bits
1500 (collisions are extremely unlikely).
1501 */
1502 st.st_mtime &= 0xFFFFFFFF;
1503 }
Martin v. Löwis30260a72011-10-23 17:35:46 +02001504 if (PyUnicode_READY(pathname) < 0)
1505 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001506 cpathname = make_compiled_pathname(pathname, !Py_OptimizeFlag);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001507
1508 if (cpathname != NULL)
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001509 fpc = check_compiled_module(pathname, &st, cpathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001510 else
1511 fpc = NULL;
1512
1513 if (fpc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 co = read_compiled_module(cpathname, fpc);
1515 fclose(fpc);
1516 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001517 goto error;
1518 update_compiled_module(co, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001520 PySys_FormatStderr("import %U # precompiled from %R\n",
1521 name, cpathname);
1522 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1523 cpathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 }
1525 else {
1526 co = parse_source_module(pathname, fp);
1527 if (co == NULL)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001528 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (Py_VerboseFlag)
Victor Stinner2f42ae52011-03-20 00:41:24 +01001530 PySys_FormatStderr("import %U # from %R\n",
Victor Stinner98dbba52011-03-14 15:15:47 -04001531 name, pathname);
Victor Stinner2f42ae52011-03-20 00:41:24 +01001532 if (cpathname != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1534 if (ro == NULL || !PyObject_IsTrue(ro))
1535 write_compiled_module(co, cpathname, &st);
1536 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01001537 m = PyImport_ExecCodeModuleObject(name, (PyObject *)co,
1538 pathname, cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001541
Victor Stinner2f42ae52011-03-20 00:41:24 +01001542error:
1543 Py_XDECREF(cpathbytes);
1544 Py_XDECREF(cpathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001546}
1547
Christian Heimes3b06e532008-01-07 20:12:44 +00001548/* Get source file -> unicode or None
1549 * Returns the path to the py file if available, else the given path
1550 */
1551static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001552get_sourcefile(PyObject *filename)
Christian Heimes3b06e532008-01-07 20:12:44 +00001553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001555 Py_UCS4 *fileuni;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001556 PyObject *py;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 struct stat statbuf;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001558 int err;
Christian Heimes3b06e532008-01-07 20:12:44 +00001559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 len = PyUnicode_GET_LENGTH(filename);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001561 if (len == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 Py_RETURN_NONE;
Christian Heimes3b06e532008-01-07 20:12:44 +00001563
Victor Stinnerc9abda02011-03-14 13:33:46 -04001564 /* don't match *.pyc or *.pyo? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001565 fileuni = PyUnicode_AsUCS4Copy(filename);
1566 if (!fileuni)
1567 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001568 if (len < 5
1569 || fileuni[len-4] != '.'
1570 || (fileuni[len-3] != 'p' && fileuni[len-3] != 'P')
1571 || (fileuni[len-2] != 'y' && fileuni[len-2] != 'Y'))
1572 goto unchanged;
Christian Heimes3b06e532008-01-07 20:12:44 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 /* Start by trying to turn PEP 3147 path into source path. If that
1575 * fails, just chop off the trailing character, i.e. legacy pyc path
1576 * to py.
1577 */
Victor Stinnerc9abda02011-03-14 13:33:46 -04001578 py = make_source_pathname(filename);
1579 if (py == NULL) {
1580 PyErr_Clear();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001581 py = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, fileuni, len - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001583 if (py == NULL)
1584 goto error;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001585
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001586 err = _Py_stat(py, &statbuf);
1587 if (err == -2)
1588 goto error;
1589 if (err == 0 && S_ISREG(statbuf.st_mode)) {
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001590 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001591 return py;
Martin v. Löwis0b1d3482011-10-01 16:35:40 +02001592 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04001593 Py_DECREF(py);
1594 goto unchanged;
1595
1596error:
1597 PyErr_Clear();
1598unchanged:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 PyMem_Free(fileuni);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001600 Py_INCREF(filename);
1601 return filename;
Christian Heimes3b06e532008-01-07 20:12:44 +00001602}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001603
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001604/* Forward */
Victor Stinner41c5fec2011-03-13 21:46:30 -04001605static PyObject *load_module(PyObject *, FILE *, PyObject *, int, PyObject *);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001606static struct filedescr *find_module(PyObject *, PyObject *, PyObject *,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001607 PyObject **, FILE **, PyObject **);
Victor Stinner53dc7352011-03-20 01:50:21 +01001608static struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001609
1610/* Load a package and return its module object WITH INCREMENTED
1611 REFERENCE COUNT */
1612
1613static PyObject *
Victor Stinnerc9abda02011-03-14 13:33:46 -04001614load_package(PyObject *name, PyObject *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001615{
Victor Stinner41c5fec2011-03-13 21:46:30 -04001616 PyObject *m, *d, *bufobj;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001617 PyObject *file = NULL, *path_list = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 int err;
Victor Stinnerc9abda02011-03-14 13:33:46 -04001619 FILE *fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001621
Victor Stinnerc9abda02011-03-14 13:33:46 -04001622 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (m == NULL)
1624 return NULL;
1625 if (Py_VerboseFlag)
Victor Stinner98dbba52011-03-14 15:15:47 -04001626 PySys_FormatStderr("import %U # directory %R\n",
1627 name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 file = get_sourcefile(pathname);
1629 if (file == NULL)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001630 return NULL;
1631 path_list = Py_BuildValue("[O]", file);
1632 if (path_list == NULL) {
1633 Py_DECREF(file);
1634 return NULL;
1635 }
1636 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 err = PyDict_SetItemString(d, "__file__", file);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001638 Py_DECREF(file);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (err == 0)
Victor Stinnerc9abda02011-03-14 13:33:46 -04001640 err = PyDict_SetItemString(d, "__path__", path_list);
1641 if (err != 0) {
1642 Py_DECREF(path_list);
1643 return NULL;
1644 }
Victor Stinner533d7832011-03-14 13:22:54 -04001645 fdp = find_module(name, initstr, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001646 &bufobj, &fp, NULL);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001647 Py_DECREF(path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 if (fdp == NULL) {
1649 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1650 PyErr_Clear();
1651 Py_INCREF(m);
Victor Stinnerc9abda02011-03-14 13:33:46 -04001652 return m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 }
1654 else
Victor Stinnerc9abda02011-03-14 13:33:46 -04001655 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04001657 m = load_module(name, fp, bufobj, fdp->type, NULL);
1658 Py_XDECREF(bufobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (fp != NULL)
1660 fclose(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001662}
1663
1664
1665/* Helper to test for built-in module */
1666
1667static int
Victor Stinner95872862011-03-07 18:20:56 +01001668is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001669{
Victor Stinner95872862011-03-07 18:20:56 +01001670 int i, cmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Victor Stinner95872862011-03-07 18:20:56 +01001672 cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
1673 if (cmp == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (PyImport_Inittab[i].initfunc == NULL)
1675 return -1;
1676 else
1677 return 1;
1678 }
1679 }
1680 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001681}
1682
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001683
Just van Rossum52e14d62002-12-30 22:08:05 +00001684/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1685 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001686 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001687 that can handle the path item. Return None if no hook could;
1688 this tells our caller it should fall back to the builtin
1689 import mechanism. Cache the result in path_importer_cache.
1690 Returns a borrowed reference. */
1691
1692static PyObject *
1693get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *importer;
1697 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 /* These conditions are the caller's responsibility: */
1700 assert(PyList_Check(path_hooks));
1701 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 nhooks = PyList_Size(path_hooks);
1704 if (nhooks < 0)
1705 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 importer = PyDict_GetItem(path_importer_cache, p);
1708 if (importer != NULL)
1709 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 /* set path_importer_cache[p] to None to avoid recursion */
1712 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1713 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 for (j = 0; j < nhooks; j++) {
1716 PyObject *hook = PyList_GetItem(path_hooks, j);
1717 if (hook == NULL)
1718 return NULL;
1719 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1720 if (importer != NULL)
1721 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1724 return NULL;
1725 }
1726 PyErr_Clear();
1727 }
1728 if (importer == NULL) {
1729 importer = PyObject_CallFunctionObjArgs(
1730 (PyObject *)&PyNullImporter_Type, p, NULL
1731 );
1732 if (importer == NULL) {
1733 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1734 PyErr_Clear();
1735 return Py_None;
1736 }
1737 }
1738 }
1739 if (importer != NULL) {
1740 int err = PyDict_SetItem(path_importer_cache, p, importer);
1741 Py_DECREF(importer);
1742 if (err != 0)
1743 return NULL;
1744 }
1745 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001746}
1747
Christian Heimes9cd17752007-11-18 19:35:23 +00001748PyAPI_FUNC(PyObject *)
1749PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1753 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1754 importer = get_path_importer(path_importer_cache,
1755 path_hooks, path);
1756 }
1757 }
1758 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1759 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001760}
1761
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001762/* Search the path (default sys.path) for a module. Return the
1763 corresponding filedescr struct, and (via return arguments) the
1764 pathname and an open file. Return NULL if the module is not found. */
1765
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001766#ifdef MS_COREDLL
Victor Stinner4d6c1c42011-03-08 23:49:04 +01001767extern FILE *_PyWin_FindRegisteredModule(PyObject *, struct filedescr **,
1768 PyObject **p_path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001769#endif
1770
Victor Stinner547a2a62011-03-20 03:07:28 +01001771/* Forward */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001772static int case_ok(PyObject *, Py_ssize_t, PyObject *);
Victor Stinner547a2a62011-03-20 03:07:28 +01001773static int find_init_module(PyObject *);
Just van Rossum52e14d62002-12-30 22:08:05 +00001774static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001775
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001776/* Get the path of a module: get its importer and call importer.find_module()
1777 hook, or check if the module if a package (if path/__init__.py exists).
1778
1779 -1: error: a Python error occurred
1780 0: ignore: an error occurred because of invalid data, but the error is not
1781 important enough to be reported.
1782 1: get path: module not found, but *buf contains its path
1783 2: found: *p_fd is the file descriptor (IMP_HOOK or PKG_DIRECTORY)
1784 and *buf is the path */
1785
1786static int
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001787find_module_path(PyObject *fullname, PyObject *name, PyObject *path,
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001788 PyObject *path_hooks, PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001789 PyObject **p_path, PyObject **p_loader, struct filedescr **p_fd)
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001790{
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001791 PyObject *path_unicode, *filename = NULL;
1792 Py_ssize_t len, pos;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001793 struct stat statbuf;
1794 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001795 int err, result, addsep;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001796
1797 if (PyUnicode_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001798 Py_INCREF(path);
1799 path_unicode = path;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001800 }
1801 else if (PyBytes_Check(path)) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04001802 path_unicode = PyUnicode_DecodeFSDefaultAndSize(
1803 PyBytes_AS_STRING(path), PyBytes_GET_SIZE(path));
1804 if (path_unicode == NULL)
1805 return -1;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001806 }
1807 else
1808 return 0;
1809
Victor Stinner46084ba2011-10-06 02:39:42 +02001810 if (PyUnicode_READY(path_unicode))
1811 return -1;
1812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813 len = PyUnicode_GET_LENGTH(path_unicode);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001814 if (PyUnicode_FindChar(path_unicode, 0, 0, len, 1) != -1) {
1815 result = 0;
1816 goto out; /* path contains '\0' */
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001817 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001818
1819 /* sys.path_hooks import hook */
1820 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001821 _Py_IDENTIFIER(find_module);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001822 PyObject *importer;
1823
1824 importer = get_path_importer(path_importer_cache,
1825 path_hooks, path);
1826 if (importer == NULL) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001827 result = -1;
1828 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001829 }
1830 /* Note: importer is a borrowed reference */
1831 if (importer != Py_None) {
1832 PyObject *loader;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001833 loader = _PyObject_CallMethodId(importer,
1834 &PyId_find_module, "O", fullname);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001835 if (loader == NULL) {
1836 result = -1; /* error */
1837 goto out;
1838 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001839 if (loader != Py_None) {
1840 /* a loader was found */
1841 *p_loader = loader;
1842 *p_fd = &importhookdescr;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001843 result = 2;
1844 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001845 }
1846 Py_DECREF(loader);
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001847 result = 0;
1848 goto out;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001849 }
1850 }
1851 /* no hook was found, use builtin import */
1852
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001853 addsep = 0;
1854 if (len > 0 && PyUnicode_READ_CHAR(path_unicode, len-1) != SEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001855#ifdef ALTSEP
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001856 && PyUnicode_READ_CHAR(path_unicode, len-1) != ALTSEP
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001857#endif
1858 )
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001859 addsep = 1;
1860 filename = PyUnicode_New(len + PyUnicode_GET_LENGTH(name) + addsep,
1861 Py_MAX(PyUnicode_MAX_CHAR_VALUE(path_unicode),
1862 PyUnicode_MAX_CHAR_VALUE(name)));
1863 if (filename == NULL) {
1864 result = -1;
1865 goto out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001866 }
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001867 PyUnicode_CopyCharacters(filename, 0, path_unicode, 0, len);
1868 pos = len;
1869 if (addsep)
Victor Stinner1f795172011-11-17 00:45:54 +01001870 PyUnicode_WRITE(PyUnicode_KIND(filename),
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001871 PyUnicode_DATA(filename),
1872 pos++, SEP);
Victor Stinner1f795172011-11-17 00:45:54 +01001873 PyUnicode_CopyCharacters(filename, pos, name, 0,
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001874 PyUnicode_GET_LENGTH(name));
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001875
1876 /* Check for package import (buf holds a directory name,
1877 and there's an __init__ module in that directory */
1878#ifdef HAVE_STAT
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001879 err = _Py_stat(filename, &statbuf);
1880 if (err == -2) {
1881 result = -1;
1882 goto out;
1883 }
1884 if (err == 0 && /* it exists */
Victor Stinnerd0296212011-03-14 14:04:10 -04001885 S_ISDIR(statbuf.st_mode)) /* it's a directory */
1886 {
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001887 int match;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001888
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001889 match = case_ok(filename, 0, name);
1890 if (match < 0) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001891 result = -1;
1892 goto out;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001893 }
1894 if (match) { /* case matches */
1895 if (find_init_module(filename)) { /* and has __init__.py */
Victor Stinner2fd76e42011-03-14 15:19:39 -04001896 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001897 filename = NULL;
Victor Stinnerd0296212011-03-14 14:04:10 -04001898 *p_fd = &fd_package;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001899 result = 2;
1900 goto out;
Victor Stinnerd0296212011-03-14 14:04:10 -04001901 }
1902 else {
1903 int err;
Victor Stinnerd0296212011-03-14 14:04:10 -04001904 err = PyErr_WarnFormat(PyExc_ImportWarning, 1,
Victor Stinner547a2a62011-03-20 03:07:28 +01001905 "Not importing directory %R: missing __init__.py",
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001906 filename);
Victor Stinner547a2a62011-03-20 03:07:28 +01001907 if (err) {
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001908 result = -1;
1909 goto out;
Victor Stinner547a2a62011-03-20 03:07:28 +01001910 }
Victor Stinnerd0296212011-03-14 14:04:10 -04001911 }
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001912 }
1913 }
1914#endif
Victor Stinner2fd76e42011-03-14 15:19:39 -04001915 *p_path = filename;
Martin v. Löwis9af29d32011-10-23 18:45:16 +02001916 filename = NULL;
1917 result = 1;
1918 out:
1919 Py_DECREF(path_unicode);
1920 Py_XDECREF(filename);
1921 return result;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001922}
1923
1924/* Find a module in search_path_list. For each path, try
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001925 find_module_path() or try each _PyImport_Filetab suffix.
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001926
1927 If the module is found, return a file descriptor, write the path in
1928 *p_filename, write the pointer to the file object into *p_fp, and (if
1929 p_loader is not NULL) the loader into *p_loader.
1930
1931 Otherwise, raise an exception and return NULL. */
1932
Victor Stinner37580282011-03-20 01:34:43 +01001933static struct filedescr*
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001934find_module_path_list(PyObject *fullname, PyObject *name,
Victor Stinner37580282011-03-20 01:34:43 +01001935 PyObject *search_path_list, PyObject *path_hooks,
1936 PyObject *path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001937 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 Py_ssize_t i, npath;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 struct filedescr *fdp = NULL;
1941 char *filemode;
1942 FILE *fp = NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001943 PyObject *prefix, *filename;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001944 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001945 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001946
Victor Stinner37580282011-03-20 01:34:43 +01001947 npath = PyList_Size(search_path_list);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 for (i = 0; i < npath; i++) {
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001949 PyObject *path;
1950 int ok;
1951
1952 path = PyList_GetItem(search_path_list, i);
1953 if (path == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 return NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001955
Victor Stinner2fd76e42011-03-14 15:19:39 -04001956 prefix = NULL;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001957 ok = find_module_path(fullname, name, path,
1958 path_hooks, path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04001959 &prefix, p_loader, &fdp);
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001960 if (ok < 0)
1961 return NULL;
1962 if (ok == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 continue;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001964 if (ok == 2) {
1965 *p_path = prefix;
Victor Stinnerd68c2cf2011-03-12 16:02:28 -05001966 return fdp;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001967 }
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001970 struct stat statbuf;
1971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 filemode = fdp->mode;
1973 if (filemode[0] == 'U')
1974 filemode = "r" PY_STDIOTEXTMODE;
Victor Stinnerd0296212011-03-14 14:04:10 -04001975
Victor Stinner2fd76e42011-03-14 15:19:39 -04001976 filename = PyUnicode_FromFormat("%U%s", prefix, fdp->suffix);
1977 if (filename == NULL) {
1978 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001979 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04001980 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001981
1982 if (Py_VerboseFlag > 1)
1983 PySys_FormatStderr("# trying %R\n", filename);
1984
Victor Stinnerbd0850b2011-12-18 20:47:30 +01001985 err = _Py_stat(filename, &statbuf);
1986 if (err == -2) {
1987 Py_DECREF(prefix);
1988 Py_DECREF(filename);
1989 return NULL;
1990 }
1991 if (err != 0 || S_ISDIR(statbuf.st_mode)) {
Charles-François Natali1659b832011-12-07 23:17:58 +01001992 /* it doesn't exist, or it's a directory */
Victor Stinnera1fe1f82011-09-23 18:59:08 +02001993 Py_DECREF(filename);
1994 continue;
1995 }
1996
Victor Stinnerc9a271c2011-03-14 14:34:13 -04001997 fp = _Py_fopen(filename, filemode);
1998 if (fp == NULL) {
1999 Py_DECREF(filename);
Victor Stinner925ef392011-06-20 15:01:10 +02002000 if (PyErr_Occurred()) {
2001 Py_DECREF(prefix);
2002 return NULL;
2003 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002004 continue;
2005 }
2006 match = case_ok(filename, -(Py_ssize_t)strlen(fdp->suffix), name);
2007 if (match < 0) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04002008 Py_DECREF(prefix);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002009 Py_DECREF(filename);
2010 return NULL;
2011 }
2012 if (match) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04002013 Py_DECREF(prefix);
2014 *p_path = filename;
Victor Stinnerd0296212011-03-14 14:04:10 -04002015 *p_fp = fp;
2016 return fdp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 }
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002018 Py_DECREF(filename);
Victor Stinnerd0296212011-03-14 14:04:10 -04002019
2020 fclose(fp);
2021 fp = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04002023 Py_DECREF(prefix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 }
Victor Stinnerd0296212011-03-14 14:04:10 -04002025 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002026 "No module named %R", name);
Victor Stinnerd0296212011-03-14 14:04:10 -04002027 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002028}
2029
Victor Stinner37580282011-03-20 01:34:43 +01002030/* Find a module:
2031
2032 - try find_module() of each sys.meta_path hook
2033 - try find_frozen()
2034 - try is_builtin()
2035 - try _PyWin_FindRegisteredModule() (Windows only)
2036 - otherwise, call find_module_path_list() with search_path_list (if not
2037 NULL) or sys.path
2038
Victor Stinner2fd76e42011-03-14 15:19:39 -04002039 fullname can be NULL, but only if p_loader is NULL.
2040
Victor Stinner37580282011-03-20 01:34:43 +01002041 Return:
2042
2043 - &fd_builtin (C_BUILTIN) if it is a builtin
2044 - &fd_frozen (PY_FROZEN) if it is frozen
Victor Stinner2fd76e42011-03-14 15:19:39 -04002045 - &fd_package (PKG_DIRECTORY) and write the filename into *p_path
Victor Stinner37580282011-03-20 01:34:43 +01002046 if it is a package
2047 - &importhookdescr (IMP_HOOK) and write the loader into *p_loader if a
2048 importer loader was found
2049 - a file descriptor (PY_SOURCE, PY_COMPILED, C_EXTENSION, PY_RESOURCE or
2050 PY_CODERESOURCE: see _PyImport_Filetab), write the filename into
Victor Stinner2fd76e42011-03-14 15:19:39 -04002051 *p_path and the pointer to the open file into *p_fp
Victor Stinner37580282011-03-20 01:34:43 +01002052 - NULL on error
2053
Victor Stinner2fd76e42011-03-14 15:19:39 -04002054 By default, *p_path, *p_fp and *p_loader (if set) are set to NULL.
2055 Eg. *p_path is set to NULL for a builtin package.
2056*/
Victor Stinner37580282011-03-20 01:34:43 +01002057
2058static struct filedescr *
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002059find_module(PyObject *fullname, PyObject *name, PyObject *search_path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002060 PyObject **p_path, FILE **p_fp, PyObject **p_loader)
Victor Stinner37580282011-03-20 01:34:43 +01002061{
2062 Py_ssize_t i, npath;
2063 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
2064 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
2065 PyObject *path_hooks, *path_importer_cache;
Victor Stinner37580282011-03-20 01:34:43 +01002066
Victor Stinner2fd76e42011-03-14 15:19:39 -04002067 *p_path = NULL;
Victor Stinner37580282011-03-20 01:34:43 +01002068 *p_fp = NULL;
2069 if (p_loader != NULL)
2070 *p_loader = NULL;
2071
Victor Stinner37580282011-03-20 01:34:43 +01002072 /* sys.meta_path import hook */
2073 if (p_loader != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002074 _Py_IDENTIFIER(find_module);
Victor Stinner37580282011-03-20 01:34:43 +01002075 PyObject *meta_path;
2076
2077 meta_path = PySys_GetObject("meta_path");
2078 if (meta_path == NULL || !PyList_Check(meta_path)) {
Victor Stinner16191322011-09-15 19:28:05 +02002079 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002080 "sys.meta_path must be a list of "
2081 "import hooks");
2082 return NULL;
2083 }
2084 Py_INCREF(meta_path); /* zap guard */
2085 npath = PyList_Size(meta_path);
2086 for (i = 0; i < npath; i++) {
2087 PyObject *loader;
2088 PyObject *hook = PyList_GetItem(meta_path, i);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002089 loader = _PyObject_CallMethodId(hook, &PyId_find_module,
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002090 "OO", fullname,
Victor Stinner37580282011-03-20 01:34:43 +01002091 search_path_list != NULL ?
2092 search_path_list : Py_None);
2093 if (loader == NULL) {
2094 Py_DECREF(meta_path);
2095 return NULL; /* true error */
2096 }
2097 if (loader != Py_None) {
2098 /* a loader was found */
2099 *p_loader = loader;
2100 Py_DECREF(meta_path);
2101 return &importhookdescr;
2102 }
2103 Py_DECREF(loader);
2104 }
2105 Py_DECREF(meta_path);
2106 }
2107
Victor Stinnerdf75a022011-03-14 13:40:04 -04002108 if (find_frozen(fullname) != NULL)
Victor Stinnerad3c03b2011-03-14 09:21:33 -04002109 return &fd_frozen;
Victor Stinner37580282011-03-20 01:34:43 +01002110
2111 if (search_path_list == NULL) {
2112#ifdef MS_COREDLL
2113 FILE *fp;
2114 struct filedescr *fdp;
Victor Stinner37580282011-03-20 01:34:43 +01002115#endif
Victor Stinnerdf75a022011-03-14 13:40:04 -04002116 if (is_builtin(name))
Victor Stinner37580282011-03-20 01:34:43 +01002117 return &fd_builtin;
Victor Stinner37580282011-03-20 01:34:43 +01002118#ifdef MS_COREDLL
Victor Stinner2fd76e42011-03-14 15:19:39 -04002119 fp = _PyWin_FindRegisteredModule(name, &fdp, p_path);
Victor Stinner37580282011-03-20 01:34:43 +01002120 if (fp != NULL) {
Victor Stinner37580282011-03-20 01:34:43 +01002121 *p_fp = fp;
2122 return fdp;
2123 }
2124 else if (PyErr_Occurred())
2125 return NULL;
2126#endif
Victor Stinner37580282011-03-20 01:34:43 +01002127 search_path_list = PySys_GetObject("path");
2128 }
2129
2130 if (search_path_list == NULL || !PyList_Check(search_path_list)) {
Victor Stinner16191322011-09-15 19:28:05 +02002131 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002132 "sys.path must be a list of directory names");
2133 return NULL;
2134 }
2135
2136 path_hooks = PySys_GetObject("path_hooks");
2137 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
Victor Stinner16191322011-09-15 19:28:05 +02002138 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002139 "sys.path_hooks must be a list of "
2140 "import hooks");
2141 return NULL;
2142 }
2143 path_importer_cache = PySys_GetObject("path_importer_cache");
2144 if (path_importer_cache == NULL ||
2145 !PyDict_Check(path_importer_cache)) {
Victor Stinner16191322011-09-15 19:28:05 +02002146 PyErr_SetString(PyExc_RuntimeError,
Victor Stinner37580282011-03-20 01:34:43 +01002147 "sys.path_importer_cache must be a dict");
2148 return NULL;
2149 }
2150
2151 return find_module_path_list(fullname, name,
2152 search_path_list, path_hooks,
2153 path_importer_cache,
Victor Stinner2fd76e42011-03-14 15:19:39 -04002154 p_path, p_fp, p_loader);
Victor Stinner37580282011-03-20 01:34:43 +01002155}
2156
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002157/* case_bytes(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00002158 * The arguments here are tricky, best shown by example:
2159 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
2160 * ^ ^ ^ ^
2161 * |--------------------- buf ---------------------|
2162 * |------------------- len ------------------|
2163 * |------ name -------|
2164 * |----- namelen -----|
2165 * buf is the full path, but len only counts up to (& exclusive of) the
2166 * extension. name is the module name, also exclusive of extension.
2167 *
2168 * We've already done a successful stat() or fopen() on buf, so know that
2169 * there's some match, possibly case-insensitive.
2170 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002171 * case_bytes() is to return 1 if there's a case-sensitive match for
2172 * name, else 0. case_bytes() is also to return 1 if envar PYTHONCASEOK
Tim Peters50d8d372001-02-28 05:34:27 +00002173 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00002174 *
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002175 * case_bytes() is used to implement case-sensitive import semantics even
Tim Peters50d8d372001-02-28 05:34:27 +00002176 * on platforms with case-insensitive filesystems. It's trivial to implement
2177 * for case-sensitive filesystems. It's pretty much a cross-platform
2178 * nightmare for systems with case-insensitive filesystems.
2179 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00002180
Tim Peters50d8d372001-02-28 05:34:27 +00002181/* First we may need a pile of platform-specific header files; the sequence
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002182 * of #if's here should match the sequence in the body of case_bytes().
Tim Peters50d8d372001-02-28 05:34:27 +00002183 */
Jason Tishler7961aa62005-05-20 00:56:54 +00002184#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002185#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00002186
Tim Peters50d8d372001-02-28 05:34:27 +00002187#elif defined(DJGPP)
2188#include <dir.h>
2189
Jason Tishler7961aa62005-05-20 00:56:54 +00002190#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00002191#include <sys/types.h>
2192#include <dirent.h>
2193
Andrew MacIntyred9400542002-02-26 11:41:34 +00002194#elif defined(PYOS_OS2)
2195#define INCL_DOS
2196#define INCL_DOSERRORS
2197#define INCL_NOPMAPI
2198#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00002199#endif
2200
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002201#if defined(DJGPP) \
2202 || ((defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) \
2203 && defined(HAVE_DIRENT_H)) \
2204 || defined(PYOS_OS2)
2205# define USE_CASE_OK_BYTES
2206#endif
2207
2208
2209#ifdef USE_CASE_OK_BYTES
Guido van Rossum0980bd91998-02-13 17:18:36 +00002210static int
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002211case_bytes(char *buf, Py_ssize_t len, Py_ssize_t namelen, const char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00002212{
Tim Peters50d8d372001-02-28 05:34:27 +00002213/* Pick a platform-specific implementation; the sequence of #if's here should
2214 * match the sequence just above.
2215 */
2216
Tim Peters50d8d372001-02-28 05:34:27 +00002217/* DJGPP */
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002218#if defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 struct ffblk ffblk;
2220 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (Py_GETENV("PYTHONCASEOK") != NULL)
2223 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
2226 if (done) {
2227 PyErr_Format(PyExc_NameError,
2228 "Can't find file for module %.100s\n(filename %.300s)",
2229 name, buf);
Victor Stinner9c61e242011-03-22 01:22:27 +01002230 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 }
2232 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002233
Jason Tishler7961aa62005-05-20 00:56:54 +00002234/* new-fangled macintosh (macosx) or Cygwin */
2235#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 DIR *dirp;
2237 struct dirent *dp;
2238 char dirname[MAXPATHLEN + 1];
2239 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (Py_GETENV("PYTHONCASEOK") != NULL)
2242 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* Copy the dir component into dirname; substitute "." if empty */
2245 if (dirlen <= 0) {
2246 dirname[0] = '.';
2247 dirname[1] = '\0';
2248 }
2249 else {
2250 assert(dirlen <= MAXPATHLEN);
2251 memcpy(dirname, buf, dirlen);
2252 dirname[dirlen] = '\0';
2253 }
2254 /* Open the directory and search the entries for an exact match. */
2255 dirp = opendir(dirname);
2256 if (dirp) {
2257 char *nameWithExt = buf + len - namelen;
2258 while ((dp = readdir(dirp)) != NULL) {
2259 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00002260#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00002262#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00002264#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (thislen >= namelen &&
2266 strcmp(dp->d_name, nameWithExt) == 0) {
2267 (void)closedir(dirp);
2268 return 1; /* Found */
2269 }
2270 }
2271 (void)closedir(dirp);
2272 }
2273 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00002274
Andrew MacIntyred9400542002-02-26 11:41:34 +00002275/* OS/2 */
2276#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 HDIR hdir = 1;
2278 ULONG srchcnt = 1;
2279 FILEFINDBUF3 ffbuf;
2280 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 if (Py_GETENV("PYTHONCASEOK") != NULL)
2283 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 rc = DosFindFirst(buf,
2286 &hdir,
2287 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
2288 &ffbuf, sizeof(ffbuf),
2289 &srchcnt,
2290 FIL_STANDARD);
2291 if (rc != NO_ERROR)
2292 return 0;
2293 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00002294
Tim Peters50d8d372001-02-28 05:34:27 +00002295/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
2296#else
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002297# error "USE_CASE_OK_BYTES is not correctly defined"
2298#endif
2299}
2300#endif
2301
2302/*
2303 * Check if a filename case matchs the name case. We've already done a
2304 * successful stat() or fopen() on buf, so know that there's some match,
2305 * possibly case-insensitive.
2306 *
2307 * case_ok() is to return 1 if there's a case-sensitive match for name, 0 if it
2308 * the filename doesn't match, or -1 on error. case_ok() is also to return 1
2309 * if envar PYTHONCASEOK exists.
2310 *
2311 * case_ok() is used to implement case-sensitive import semantics even
2312 * on platforms with case-insensitive filesystems. It's trivial to implement
2313 * for case-sensitive filesystems. It's pretty much a cross-platform
2314 * nightmare for systems with case-insensitive filesystems.
2315 */
2316
2317static int
2318case_ok(PyObject *filename, Py_ssize_t prefix_delta, PyObject *name)
2319{
2320#ifdef MS_WINDOWS
2321 WIN32_FIND_DATAW data;
2322 HANDLE h;
2323 int cmp;
Victor Stinner1f795172011-11-17 00:45:54 +01002324 wchar_t *wfilename, *wname;
Victor Stinner8c981892011-10-11 22:27:13 +02002325 Py_ssize_t wname_len;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002326
2327 if (Py_GETENV("PYTHONCASEOK") != NULL)
2328 return 1;
2329
Victor Stinner1f795172011-11-17 00:45:54 +01002330 wfilename = PyUnicode_AsUnicode(filename);
2331 if (wfilename == NULL)
2332 return -1;
2333
2334 h = FindFirstFileW(wfilename, &data);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002335 if (h == INVALID_HANDLE_VALUE) {
2336 PyErr_Format(PyExc_NameError,
2337 "Can't find file for module %R\n(filename %R)",
2338 name, filename);
Victor Stinner1f795172011-11-17 00:45:54 +01002339 return -1;
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002340 }
2341 FindClose(h);
Victor Stinnerbeac78b2011-10-11 21:55:01 +02002342
2343 wname = PyUnicode_AsUnicodeAndSize(name, &wname_len);
2344 if (wname == NULL)
2345 return -1;
2346
2347 cmp = wcsncmp(data.cFileName, wname, wname_len);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002348 return cmp == 0;
2349#elif defined(USE_CASE_OK_BYTES)
2350 int match;
2351 PyObject *filebytes, *namebytes;
2352 filebytes = PyUnicode_EncodeFSDefault(filename);
2353 if (filebytes == NULL)
2354 return -1;
2355 namebytes = PyUnicode_EncodeFSDefault(name);
2356 if (namebytes == NULL) {
2357 Py_DECREF(filebytes);
2358 return -1;
2359 }
2360 match = case_bytes(
2361 PyBytes_AS_STRING(filebytes),
2362 PyBytes_GET_SIZE(filebytes) + prefix_delta,
Victor Stinner1304f2d2011-03-20 04:28:55 +01002363 PyBytes_GET_SIZE(namebytes),
2364 PyBytes_AS_STRING(namebytes));
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002365 Py_DECREF(filebytes);
2366 Py_DECREF(namebytes);
2367 return match;
2368#else
2369 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00002371
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002372#endif
Tim Peters50d8d372001-02-28 05:34:27 +00002373}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00002374
Guido van Rossum197346f1997-10-31 18:38:52 +00002375#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00002376
Victor Stinner547a2a62011-03-20 03:07:28 +01002377/* Helper to look for __init__.py or __init__.py[co] in potential package.
2378 Return 1 if __init__ was found, 0 if not, or -1 on error. */
Guido van Rossum197346f1997-10-31 18:38:52 +00002379static int
Victor Stinner547a2a62011-03-20 03:07:28 +01002380find_init_module(PyObject *directory)
Guido van Rossum197346f1997-10-31 18:38:52 +00002381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 struct stat statbuf;
Victor Stinner547a2a62011-03-20 03:07:28 +01002383 PyObject *filename;
2384 int match;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002385 int err;
Guido van Rossum197346f1997-10-31 18:38:52 +00002386
Victor Stinner547a2a62011-03-20 03:07:28 +01002387 filename = PyUnicode_FromFormat("%U%c__init__.py", directory, SEP);
2388 if (filename == NULL)
2389 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002390 err = _Py_stat(filename, &statbuf);
2391 if (err == -2)
2392 return -1;
2393 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002394 /* 3=len(".py") */
2395 match = case_ok(filename, -3, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002396 if (match < 0) {
2397 Py_DECREF(filename);
2398 return -1;
2399 }
2400 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002401 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 return 1;
2403 }
2404 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002405 Py_DECREF(filename);
2406
2407 filename = PyUnicode_FromFormat("%U%c__init__.py%c",
2408 directory, SEP, Py_OptimizeFlag ? 'o' : 'c');
2409 if (filename == NULL)
2410 return -1;
Victor Stinnerbd0850b2011-12-18 20:47:30 +01002411 err = _Py_stat(filename, &statbuf);
2412 if (err == -2) {
2413 Py_DECREF(filename);
2414 return -1;
2415 }
2416 if (err == 0) {
Victor Stinnercc9564e2011-03-20 04:58:29 +01002417 /* 4=len(".pyc") */
2418 match = case_ok(filename, -4, initstr);
Victor Stinnerc9a271c2011-03-14 14:34:13 -04002419 if (match < 0) {
2420 Py_DECREF(filename);
2421 return -1;
2422 }
2423 if (match) {
Victor Stinner547a2a62011-03-20 03:07:28 +01002424 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return 1;
2426 }
2427 }
Victor Stinner547a2a62011-03-20 03:07:28 +01002428 Py_DECREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002430}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002431
Guido van Rossum197346f1997-10-31 18:38:52 +00002432#endif /* HAVE_STAT */
2433
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002434
Victor Stinner95872862011-03-07 18:20:56 +01002435static int init_builtin(PyObject *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002436
Victor Stinner44c6c152010-08-09 00:59:10 +00002437static PyObject*
Victor Stinner95872862011-03-07 18:20:56 +01002438load_builtin(PyObject *name, int type)
Victor Stinner44c6c152010-08-09 00:59:10 +00002439{
2440 PyObject *m, *modules;
2441 int err;
2442
Victor Stinner44c6c152010-08-09 00:59:10 +00002443 if (type == C_BUILTIN)
2444 err = init_builtin(name);
2445 else
Victor Stinner95872862011-03-07 18:20:56 +01002446 err = PyImport_ImportFrozenModuleObject(name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002447 if (err < 0)
2448 return NULL;
2449 if (err == 0) {
2450 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002451 "Purported %s module %R not found",
2452 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002453 name);
2454 return NULL;
2455 }
2456
2457 modules = PyImport_GetModuleDict();
Victor Stinner95872862011-03-07 18:20:56 +01002458 m = PyDict_GetItem(modules, name);
Victor Stinner44c6c152010-08-09 00:59:10 +00002459 if (m == NULL) {
2460 PyErr_Format(
2461 PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002462 "%s module %R not properly initialized",
2463 type == C_BUILTIN ? "builtin" : "frozen",
Victor Stinner44c6c152010-08-09 00:59:10 +00002464 name);
2465 return NULL;
2466 }
2467 Py_INCREF(m);
2468 return m;
2469}
2470
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002471/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002472 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002473
Guido van Rossum79f25d91997-04-29 20:08:16 +00002474static PyObject *
Victor Stinner41c5fec2011-03-13 21:46:30 -04002475load_module(PyObject *name, FILE *fp, PyObject *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* First check that there's an open file (if we need one) */
2480 switch (type) {
2481 case PY_SOURCE:
2482 case PY_COMPILED:
2483 if (fp == NULL) {
2484 PyErr_Format(PyExc_ValueError,
Victor Stinner41c5fec2011-03-13 21:46:30 -04002485 "file object required for import (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 type);
2487 return NULL;
2488 }
2489 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002492
Victor Stinner41c5fec2011-03-13 21:46:30 -04002493 case PY_SOURCE:
2494 m = load_source_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002496
Victor Stinner41c5fec2011-03-13 21:46:30 -04002497 case PY_COMPILED:
2498 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002500
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002501#ifdef HAVE_DYNAMIC_LOADING
Victor Stinner41c5fec2011-03-13 21:46:30 -04002502 case C_EXTENSION:
2503 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002505#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002506
Victor Stinner41c5fec2011-03-13 21:46:30 -04002507 case PKG_DIRECTORY:
2508 m = load_package(name, pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 case C_BUILTIN:
Victor Stinner41c5fec2011-03-13 21:46:30 -04002512 case PY_FROZEN:
2513 m = load_builtin(name, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 case IMP_HOOK: {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002517 _Py_IDENTIFIER(load_module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if (loader == NULL) {
2519 PyErr_SetString(PyExc_ImportError,
2520 "import hook without loader");
2521 return NULL;
2522 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002523 m = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 break;
2525 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 default:
2528 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04002529 "Don't know how to import %R (type code %d)",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 name, type);
2531 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002536}
2537
2538
2539/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002540 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002541 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002542
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002543static int
Victor Stinner95872862011-03-07 18:20:56 +01002544init_builtin(PyObject *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002547
Victor Stinner95872862011-03-07 18:20:56 +01002548 if (_PyImport_FindExtensionObject(name, name) != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 for (p = PyImport_Inittab; p->name != NULL; p++) {
2552 PyObject *mod;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002553 PyModuleDef *def;
Victor Stinner95872862011-03-07 18:20:56 +01002554 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (p->initfunc == NULL) {
2556 PyErr_Format(PyExc_ImportError,
Victor Stinner95872862011-03-07 18:20:56 +01002557 "Cannot re-init internal module %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 name);
2559 return -1;
2560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 mod = (*p->initfunc)();
2562 if (mod == 0)
2563 return -1;
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01002564 /* Remember pointer to module init function. */
2565 def = PyModule_GetDef(mod);
2566 def->m_base.m_init = p->initfunc;
Victor Stinner95872862011-03-07 18:20:56 +01002567 if (_PyImport_FixupExtensionObject(mod, name, name) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 return -1;
2569 /* FixupExtension has put the module into sys.modules,
2570 so we can release our own reference. */
2571 Py_DECREF(mod);
2572 return 1;
2573 }
2574 }
2575 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002576}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002577
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002578
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002579/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002580
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002581static struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01002582find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002585
Victor Stinner53dc7352011-03-20 01:50:21 +01002586 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 for (p = PyImport_FrozenModules; ; p++) {
2590 if (p->name == NULL)
2591 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01002592 if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 break;
2594 }
2595 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002596}
2597
Guido van Rossum79f25d91997-04-29 20:08:16 +00002598static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002599get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 struct _frozen *p = find_frozen(name);
2602 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 if (p == NULL) {
2605 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002606 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 name);
2608 return NULL;
2609 }
2610 if (p->code == NULL) {
2611 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002612 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 name);
2614 return NULL;
2615 }
2616 size = p->size;
2617 if (size < 0)
2618 size = -size;
2619 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002620}
2621
Brett Cannon8d110132009-03-15 02:20:16 +00002622static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01002623is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00002624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 struct _frozen *p = find_frozen(name);
2626 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (p == NULL) {
2629 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002630 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 name);
2632 return NULL;
2633 }
Brett Cannon8d110132009-03-15 02:20:16 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (size < 0)
2638 Py_RETURN_TRUE;
2639 else
2640 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002641}
2642
2643
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002644/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002645 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002646 an exception set if the initialization failed.
2647 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002648
2649int
Victor Stinner53dc7352011-03-20 01:50:21 +01002650PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002651{
Victor Stinner53dc7352011-03-20 01:50:21 +01002652 struct _frozen *p;
2653 PyObject *co, *m, *path;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 int ispackage;
2655 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002656
Victor Stinner53dc7352011-03-20 01:50:21 +01002657 p = find_frozen(name);
2658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 if (p == NULL)
2660 return 0;
2661 if (p->code == NULL) {
2662 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002663 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 name);
2665 return -1;
2666 }
2667 size = p->size;
2668 ispackage = (size < 0);
2669 if (ispackage)
2670 size = -size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2672 if (co == NULL)
2673 return -1;
2674 if (!PyCode_Check(co)) {
2675 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01002676 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 name);
2678 goto err_return;
2679 }
2680 if (ispackage) {
2681 /* Set __path__ to the package name */
Victor Stinner53dc7352011-03-20 01:50:21 +01002682 PyObject *d, *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01002684 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 if (m == NULL)
2686 goto err_return;
2687 d = PyModule_GetDict(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 l = PyList_New(1);
2689 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 goto err_return;
2691 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002692 Py_INCREF(name);
2693 PyList_SET_ITEM(l, 0, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 err = PyDict_SetItemString(d, "__path__", l);
2695 Py_DECREF(l);
2696 if (err != 0)
2697 goto err_return;
2698 }
Victor Stinner53dc7352011-03-20 01:50:21 +01002699 path = PyUnicode_FromString("<frozen>");
2700 if (path == NULL)
2701 goto err_return;
2702 m = PyImport_ExecCodeModuleObject(name, co, path, NULL);
2703 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (m == NULL)
2705 goto err_return;
2706 Py_DECREF(co);
2707 Py_DECREF(m);
2708 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002709err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 Py_DECREF(co);
2711 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002712}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002713
Victor Stinner53dc7352011-03-20 01:50:21 +01002714int
2715PyImport_ImportFrozenModule(char *name)
2716{
2717 PyObject *nameobj;
2718 int ret;
2719 nameobj = PyUnicode_InternFromString(name);
2720 if (nameobj == NULL)
2721 return -1;
2722 ret = PyImport_ImportFrozenModuleObject(nameobj);
2723 Py_DECREF(nameobj);
2724 return ret;
2725}
2726
Guido van Rossum74e6a111994-08-29 12:54:38 +00002727
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002728/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002729 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002730
Guido van Rossum79f25d91997-04-29 20:08:16 +00002731PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002732PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 PyObject *pname;
2735 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 pname = PyUnicode_FromString(name);
2738 if (pname == NULL)
2739 return NULL;
2740 result = PyImport_Import(pname);
2741 Py_DECREF(pname);
2742 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002743}
2744
Christian Heimes072c0f12008-01-03 23:01:04 +00002745/* Import a module without blocking
2746 *
2747 * At first it tries to fetch the module from sys.modules. If the module was
2748 * never loaded before it loads it with PyImport_ImportModule() unless another
2749 * thread holds the import lock. In the latter case the function raises an
2750 * ImportError instead of blocking.
2751 *
2752 * Returns the module object with incremented ref count.
2753 */
2754PyObject *
2755PyImport_ImportModuleNoBlock(const char *name)
2756{
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002757 PyObject *nameobj, *modules, *result;
Victor Stinner0af03062011-09-02 00:11:43 +02002758#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 long me;
Victor Stinner0af03062011-09-02 00:11:43 +02002760#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* Try to get the module from sys.modules[name] */
2763 modules = PyImport_GetModuleDict();
2764 if (modules == NULL)
2765 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002766
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002767 nameobj = PyUnicode_FromString(name);
2768 if (nameobj == NULL)
2769 return NULL;
2770 result = PyDict_GetItem(modules, nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 if (result != NULL) {
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002772 Py_DECREF(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 Py_INCREF(result);
2774 return result;
2775 }
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002776 PyErr_Clear();
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002777#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 /* check the import lock
2779 * me might be -1 but I ignore the error here, the lock function
2780 * takes care of the problem */
2781 me = PyThread_get_thread_ident();
2782 if (import_lock_thread == -1 || import_lock_thread == me) {
2783 /* no thread or me is holding the lock */
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002784 result = PyImport_Import(nameobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 }
2786 else {
2787 PyErr_Format(PyExc_ImportError,
Victor Stinnerc24c8102011-03-13 22:38:06 -04002788 "Failed to import %R because the import lock"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 "is held by another thread.",
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002790 nameobj);
2791 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002793#else
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002794 result = PyImport_Import(nameobj);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002795#endif
Victor Stinner2e5f11a2011-03-13 21:57:27 -04002796 Py_DECREF(nameobj);
2797 return result;
Christian Heimes072c0f12008-01-03 23:01:04 +00002798}
2799
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002800
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002801PyObject *
Brett Cannonfd074152012-04-14 14:10:13 -04002802PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
2803 PyObject *locals, PyObject *given_fromlist,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04002804 int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002805{
Brett Cannonfd074152012-04-14 14:10:13 -04002806 _Py_IDENTIFIER(__import__);
2807 _Py_IDENTIFIER(__package__);
2808 _Py_IDENTIFIER(__path__);
2809 _Py_IDENTIFIER(__name__);
2810 _Py_IDENTIFIER(_find_and_load);
2811 _Py_IDENTIFIER(_handle_fromlist);
2812 _Py_static_string(single_dot, ".");
2813 PyObject *abs_name = NULL;
2814 PyObject *builtins_import = NULL;
2815 PyObject *final_mod = NULL;
2816 PyObject *mod = NULL;
2817 PyObject *package = NULL;
2818 PyObject *globals = NULL;
2819 PyObject *fromlist = NULL;
2820 PyInterpreterState *interp = PyThreadState_GET()->interp;
2821
2822 /* Make sure to use default values so as to not have
2823 PyObject_CallMethodObjArgs() truncate the parameter list because of a
2824 NULL argument. */
2825 if (given_globals == NULL) {
2826 globals = PyDict_New();
2827 if (globals == NULL) {
2828 goto error;
2829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 }
Brett Cannonfd074152012-04-14 14:10:13 -04002831 else {
2832 /* Only have to care what given_globals is if it will be used
2833 fortsomething. */
2834 if (level > 0 && !PyDict_Check(given_globals)) {
2835 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
2836 goto error;
2837 }
2838 globals = given_globals;
2839 Py_INCREF(globals);
2840 }
2841
2842 if (given_fromlist == NULL) {
2843 fromlist = PyList_New(0);
2844 if (fromlist == NULL) {
2845 goto error;
2846 }
2847 }
2848 else {
2849 fromlist = given_fromlist;
2850 Py_INCREF(fromlist);
2851 }
2852 if (name == NULL) {
2853 PyErr_SetString(PyExc_ValueError, "Empty module name");
2854 goto error;
2855 }
2856
2857 /* The below code is importlib.__import__() & _gcd_import(), ported to C
2858 for added performance. */
2859
2860 if (!PyUnicode_Check(name)) {
2861 PyErr_SetString(PyExc_TypeError, "module name must be a string");
2862 goto error;
2863 }
2864 else if (PyUnicode_READY(name) < 0) {
2865 goto error;
2866 }
2867 if (level < 0) {
2868 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
2869 goto error;
2870 }
2871 else if (level > 0) {
2872 package = _PyDict_GetItemId(globals, &PyId___package__);
2873 if (package != NULL && package != Py_None) {
2874 Py_INCREF(package);
2875 if (!PyUnicode_Check(package)) {
2876 PyErr_SetString(PyExc_TypeError, "package must be a string");
2877 goto error;
2878 }
2879 }
2880 else {
2881 package = _PyDict_GetItemIdWithError(globals, &PyId___name__);
2882 if (package == NULL) {
2883 goto error;
2884 }
2885 else if (!PyUnicode_Check(package)) {
2886 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
2887 }
2888 Py_INCREF(package);
2889
2890 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
Brett Cannon740fce02012-04-14 14:23:49 -04002891 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04002892 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
2893 if (borrowed_dot == NULL) {
2894 goto error;
2895 }
Brett Cannon740fce02012-04-14 14:23:49 -04002896 partition = PyUnicode_RPartition(package, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04002897 Py_DECREF(package);
2898 if (partition == NULL) {
2899 goto error;
2900 }
2901 package = PyTuple_GET_ITEM(partition, 0);
2902 Py_INCREF(package);
2903 Py_DECREF(partition);
2904 }
2905 }
2906
2907 if (PyDict_GetItem(interp->modules, package) == NULL) {
2908 PyErr_Format(PyExc_SystemError,
2909 "Parent module %R not loaded, cannot perform relative "
2910 "import", package);
2911 goto error;
2912 }
2913 }
2914 else { /* level == 0 */
2915 if (PyUnicode_GET_LENGTH(name) == 0) {
2916 PyErr_SetString(PyExc_ValueError, "Empty module name");
2917 goto error;
2918 }
2919 package = Py_None;
2920 Py_INCREF(package);
2921 }
2922
2923 if (level > 0) {
2924 Py_ssize_t last_dot = PyUnicode_GET_LENGTH(package);
2925 PyObject *base = NULL;
2926 int level_up = 1;
2927
2928 for (level_up = 1; level_up < level; level_up += 1) {
2929 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
2930 if (last_dot == -2) {
2931 goto error;
2932 }
2933 else if (last_dot == -1) {
2934 PyErr_SetString(PyExc_ValueError,
2935 "attempted relative import beyond top-level "
2936 "package");
2937 goto error;
2938 }
2939 }
2940 base = PyUnicode_Substring(package, 0, last_dot);
2941 if (PyUnicode_GET_LENGTH(name) > 0) {
2942 PyObject *borrowed_dot = NULL;
2943 PyObject *seq = PyTuple_Pack(2, base, name);
2944
2945 borrowed_dot = _PyUnicode_FromId(&single_dot);
2946 if (borrowed_dot == NULL || seq == NULL) {
2947 goto error;
2948 }
2949
2950 abs_name = PyUnicode_Join(borrowed_dot, seq);
2951 Py_DECREF(seq);
2952 if (abs_name == NULL) {
2953 goto error;
2954 }
2955 }
2956 else {
2957 abs_name = base;
2958 }
2959 }
2960 else {
2961 abs_name = name;
2962 Py_INCREF(abs_name);
2963 }
2964
Brian Curtine6b299f2012-04-14 14:19:33 -05002965#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04002966 _PyImport_AcquireLock();
2967#endif
2968 /* From this point forward, goto error_with_unlock! */
2969 if (PyDict_Check(globals)) {
2970 builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
2971 }
2972 if (builtins_import == NULL) {
2973 builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
2974 if (builtins_import == NULL) {
2975 Py_FatalError("__import__ missing");
2976 }
2977 }
2978 Py_INCREF(builtins_import);
2979
2980 mod = PyDict_GetItem(interp->modules, abs_name);
2981 if (mod == Py_None) {
Brett Cannon27fc5282012-04-15 14:15:31 -04002982 PyObject *msg = PyUnicode_FromFormat("import of %R halted; "
2983 "None in sys.modules", abs_name);
2984 if (msg != NULL) {
2985 PyErr_SetFromImportErrorWithName(msg, abs_name);
2986 }
Brett Cannonfd074152012-04-14 14:10:13 -04002987 goto error_with_unlock;
2988 }
2989 else if (mod != NULL) {
2990 Py_INCREF(mod);
2991 }
2992 else {
2993 mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
2994 &PyId__find_and_load, abs_name,
2995 builtins_import, NULL);
2996 if (mod == NULL) {
2997 goto error_with_unlock;
2998 }
2999 }
3000
3001 if (PyObject_Not(fromlist)) {
3002 if (level == 0 || PyUnicode_GET_LENGTH(name) > 0) {
3003 PyObject *front = NULL;
Brian Curtine6b299f2012-04-14 14:19:33 -05003004 PyObject *partition = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04003005 PyObject *borrowed_dot = _PyUnicode_FromId(&single_dot);
3006
3007 if (borrowed_dot == NULL) {
3008 goto error_with_unlock;
3009 }
3010
Brian Curtine6b299f2012-04-14 14:19:33 -05003011 partition = PyUnicode_Partition(name, borrowed_dot);
Brett Cannonfd074152012-04-14 14:10:13 -04003012 if (partition == NULL) {
3013 goto error_with_unlock;
3014 }
3015
3016 front = PyTuple_GET_ITEM(partition, 0);
3017 Py_INCREF(front);
3018 Py_DECREF(partition);
3019
3020 if (level == 0) {
Brett Cannon881535b2012-04-15 15:24:04 -04003021 if (PyUnicode_GET_LENGTH(name) ==
3022 PyUnicode_GET_LENGTH(front)) {
3023 final_mod = mod;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04003024 }
3025 else {
Brett Cannon881535b2012-04-15 15:24:04 -04003026 final_mod = PyDict_GetItem(interp->modules, front);
3027 if (final_mod == NULL) {
3028 PyErr_Format(PyExc_KeyError,
3029 "%R not in sys.modules as expected", front);
3030 }
Brett Cannon49f8d8b2012-04-14 21:50:00 -04003031 }
Brett Cannon881535b2012-04-15 15:24:04 -04003032 Py_DECREF(front);
3033 if (final_mod == NULL) {
3034 goto error_with_unlock;
3035 }
3036 Py_INCREF(final_mod);
Brett Cannonfd074152012-04-14 14:10:13 -04003037 }
3038 else {
3039 Py_ssize_t cut_off = PyUnicode_GetLength(name) -
3040 PyUnicode_GetLength(front);
3041 Py_ssize_t abs_name_len = PyUnicode_GetLength(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04003042 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04003043 abs_name_len - cut_off);
3044
3045 final_mod = PyDict_GetItem(interp->modules, to_return);
Brett Cannonfd074152012-04-14 14:10:13 -04003046 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04003047 if (final_mod == NULL) {
3048 PyErr_Format(PyExc_KeyError,
3049 "%R not in sys.modules as expected",
3050 to_return);
3051 }
3052 else {
3053 Py_INCREF(final_mod);
3054 }
Brett Cannonfd074152012-04-14 14:10:13 -04003055 }
3056 }
3057 else {
3058 final_mod = mod;
3059 Py_INCREF(mod);
3060 }
3061 }
3062 else {
3063 final_mod = _PyObject_CallMethodObjIdArgs(interp->importlib,
3064 &PyId__handle_fromlist, mod,
3065 fromlist, builtins_import,
3066 NULL);
3067 }
3068 error_with_unlock:
Brian Curtine6b299f2012-04-14 14:19:33 -05003069#ifdef WITH_THREAD
Brett Cannonfd074152012-04-14 14:10:13 -04003070 if (_PyImport_ReleaseLock() < 0) {
3071 PyErr_SetString(PyExc_RuntimeError, "not holding the import lock");
3072 }
3073#endif
3074 error:
3075 Py_XDECREF(abs_name);
3076 Py_XDECREF(builtins_import);
3077 Py_XDECREF(mod);
3078 Py_XDECREF(package);
3079 Py_XDECREF(globals);
3080 Py_XDECREF(fromlist);
3081 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00003082}
3083
Victor Stinnerfe93faf2011-03-14 15:54:52 -04003084PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05003085PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04003086 PyObject *fromlist, int level)
3087{
3088 PyObject *nameobj, *mod;
3089 nameobj = PyUnicode_FromString(name);
3090 if (nameobj == NULL)
3091 return NULL;
3092 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
3093 fromlist, level);
3094 Py_DECREF(nameobj);
3095 return mod;
3096}
3097
3098
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003099/* Re-import a module of any kind and return its module object, WITH
3100 INCREMENTED REFERENCE COUNT */
3101
Guido van Rossum79f25d91997-04-29 20:08:16 +00003102PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003103PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 PyInterpreterState *interp = PyThreadState_Get()->interp;
3106 PyObject *modules_reloading = interp->modules_reloading;
3107 PyObject *modules = PyImport_GetModuleDict();
Brett Cannon8a1d04c2012-04-15 17:56:09 -04003108 PyObject *loader = NULL, *existing_m = NULL;
3109 PyObject *name;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003110 Py_ssize_t subname_start;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003111 PyObject *newm = NULL;
Brett Cannon8a1d04c2012-04-15 17:56:09 -04003112 _Py_IDENTIFIER(__loader__);
3113 _Py_IDENTIFIER(load_module);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 if (modules_reloading == NULL) {
3116 Py_FatalError("PyImport_ReloadModule: "
3117 "no modules_reloading dictionary!");
3118 return NULL;
3119 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 if (m == NULL || !PyModule_Check(m)) {
3122 PyErr_SetString(PyExc_TypeError,
3123 "reload() argument must be module");
3124 return NULL;
3125 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003126 name = PyModule_GetNameObject(m);
3127 if (name == NULL || PyUnicode_READY(name) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 return NULL;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003129 if (m != PyDict_GetItem(modules, name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003131 "reload(): module %R not in sys.modules",
Martin v. Löwis796ea532011-10-30 09:07:07 +01003132 name);
3133 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 return NULL;
3135 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003136 existing_m = PyDict_GetItem(modules_reloading, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 if (existing_m != NULL) {
3138 /* Due to a recursive reload, this module is already
3139 being reloaded. */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003140 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 Py_INCREF(existing_m);
3142 return existing_m;
3143 }
Martin v. Löwis796ea532011-10-30 09:07:07 +01003144 if (PyDict_SetItem(modules_reloading, name, m) < 0) {
3145 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003147 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00003148
Martin v. Löwis796ea532011-10-30 09:07:07 +01003149 subname_start = PyUnicode_FindChar(name, '.', 0,
3150 PyUnicode_GET_LENGTH(name), -1);
Brett Cannon8a1d04c2012-04-15 17:56:09 -04003151 if (subname_start != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 PyObject *parentname, *parent;
Martin v. Löwis796ea532011-10-30 09:07:07 +01003153 parentname = PyUnicode_Substring(name, 0, subname_start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 if (parentname == NULL) {
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003155 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
3157 parent = PyDict_GetItem(modules, parentname);
Brett Cannon8a1d04c2012-04-15 17:56:09 -04003158 Py_XDECREF(parent);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 if (parent == NULL) {
3160 PyErr_Format(PyExc_ImportError,
Victor Stinner98dbba52011-03-14 15:15:47 -04003161 "reload(): parent %R not in sys.modules",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 parentname);
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003163 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00003166
Brett Cannon8a1d04c2012-04-15 17:56:09 -04003167 loader = _PyObject_GetAttrId(m, &PyId___loader__);
3168 if (loader == NULL) {
3169 goto error;
3170 }
3171 newm = _PyObject_CallMethodId(loader, &PyId_load_module, "O", name);
3172 Py_DECREF(loader);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 if (newm == NULL) {
3174 /* load_module probably removed name from modules because of
3175 * the error. Put back the original module object. We're
3176 * going to return NULL in this case regardless of whether
3177 * replacing name succeeds, so the return value is ignored.
3178 */
Martin v. Löwis796ea532011-10-30 09:07:07 +01003179 PyDict_SetItem(modules, name, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003181
3182error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 imp_modules_reloading_clear();
Martin v. Löwis796ea532011-10-30 09:07:07 +01003184 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003186}
3187
3188
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003189/* Higher-level import emulator which emulates the "import" statement
3190 more accurately -- it invokes the __import__() function from the
3191 builtins of the current globals. This means that the import is
3192 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00003193 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00003194 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00003195 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00003196 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003197
3198PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003199PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 static PyObject *silly_list = NULL;
3202 static PyObject *builtins_str = NULL;
3203 static PyObject *import_str = NULL;
3204 PyObject *globals = NULL;
3205 PyObject *import = NULL;
3206 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003207 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* Initialize constant string objects */
3211 if (silly_list == NULL) {
3212 import_str = PyUnicode_InternFromString("__import__");
3213 if (import_str == NULL)
3214 return NULL;
3215 builtins_str = PyUnicode_InternFromString("__builtins__");
3216 if (builtins_str == NULL)
3217 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003218 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 if (silly_list == NULL)
3220 return NULL;
3221 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 /* Get the builtins from current globals */
3224 globals = PyEval_GetGlobals();
3225 if (globals != NULL) {
3226 Py_INCREF(globals);
3227 builtins = PyObject_GetItem(globals, builtins_str);
3228 if (builtins == NULL)
3229 goto err;
3230 }
3231 else {
3232 /* No globals -- use standard builtins, and fake globals */
3233 builtins = PyImport_ImportModuleLevel("builtins",
3234 NULL, NULL, NULL, 0);
3235 if (builtins == NULL)
3236 return NULL;
3237 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3238 if (globals == NULL)
3239 goto err;
3240 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 /* Get the __import__ function from the builtins */
3243 if (PyDict_Check(builtins)) {
3244 import = PyObject_GetItem(builtins, import_str);
3245 if (import == NULL)
3246 PyErr_SetObject(PyExc_KeyError, import_str);
3247 }
3248 else
3249 import = PyObject_GetAttr(builtins, import_str);
3250 if (import == NULL)
3251 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003254 Always use absolute import here.
3255 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3257 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003258 if (r == NULL)
3259 goto err;
3260 Py_DECREF(r);
3261
3262 modules = PyImport_GetModuleDict();
3263 r = PyDict_GetItem(modules, module_name);
3264 if (r != NULL)
3265 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003266
3267 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 Py_XDECREF(globals);
3269 Py_XDECREF(builtins);
3270 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003273}
3274
3275
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003276/* Module 'imp' provides Python access to the primitives used for
3277 importing modules.
3278*/
3279
Guido van Rossum79f25d91997-04-29 20:08:16 +00003280static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003281imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 buf[0] = (char) ((magic >> 0) & 0xff);
3286 buf[1] = (char) ((magic >> 8) & 0xff);
3287 buf[2] = (char) ((magic >> 16) & 0xff);
3288 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 return PyBytes_FromStringAndSize(buf, 4);
Victor Stinner3e2b7172010-11-09 09:32:19 +00003291}
Barry Warsaw28a691b2010-04-17 00:19:56 +00003292
3293static PyObject *
3294imp_get_magic(PyObject *self, PyObject *noargs)
3295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003297}
3298
3299static PyObject *
3300imp_get_tag(PyObject *self, PyObject *noargs)
3301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003303}
3304
Guido van Rossum79f25d91997-04-29 20:08:16 +00003305static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003306imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 PyObject *list;
3309 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 list = PyList_New(0);
3312 if (list == NULL)
3313 return NULL;
3314 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3315 PyObject *item = Py_BuildValue("ssi",
3316 fdp->suffix, fdp->mode, fdp->type);
3317 if (item == NULL) {
3318 Py_DECREF(list);
3319 return NULL;
3320 }
3321 if (PyList_Append(list, item) < 0) {
3322 Py_DECREF(list);
3323 Py_DECREF(item);
3324 return NULL;
3325 }
3326 Py_DECREF(item);
3327 }
3328 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003329}
3330
Guido van Rossum79f25d91997-04-29 20:08:16 +00003331static PyObject *
Victor Stinner533d7832011-03-14 13:22:54 -04003332call_find_module(PyObject *name, PyObject *path_list)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 extern int fclose(FILE *);
3335 PyObject *fob, *ret;
3336 PyObject *pathobj;
3337 struct filedescr *fdp;
Victor Stinner7d8b77c2011-03-12 08:45:02 -05003338 FILE *fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 int fd = -1;
3340 char *found_encoding = NULL;
3341 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003342
Victor Stinner533d7832011-03-14 13:22:54 -04003343 if (path_list == Py_None)
3344 path_list = NULL;
3345 fdp = find_module(NULL, name, path_list,
Victor Stinner2fd76e42011-03-14 15:19:39 -04003346 &pathobj, &fp, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (fdp == NULL)
3348 return NULL;
3349 if (fp != NULL) {
3350 fd = fileno(fp);
3351 if (fd != -1)
3352 fd = dup(fd);
3353 fclose(fp);
3354 fp = NULL;
Antoine Pitrou72146122012-02-22 18:03:04 +01003355 if (fd == -1)
3356 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 }
3358 if (fd != -1) {
3359 if (strchr(fdp->mode, 'b') == NULL) {
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003360 /* PyTokenizer_FindEncodingFilename() returns PyMem_MALLOC'ed
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 memory. */
Victor Stinnerfe7c5b52011-04-05 01:48:03 +02003362 found_encoding = PyTokenizer_FindEncodingFilename(fd, pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 lseek(fd, 0, 0); /* Reset position */
Victor Stinner2fd76e42011-03-14 15:19:39 -04003364 if (found_encoding == NULL && PyErr_Occurred()) {
3365 Py_XDECREF(pathobj);
Antoine Pitrou4f22a8d2012-02-22 18:05:43 +01003366 close(fd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 return NULL;
Victor Stinner2fd76e42011-03-14 15:19:39 -04003368 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 encoding = (found_encoding != NULL) ? found_encoding :
3370 (char*)PyUnicode_GetDefaultEncoding();
3371 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003372 fob = PyFile_FromFd(fd, NULL, fdp->mode, -1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 (char*)encoding, NULL, NULL, 1);
3374 if (fob == NULL) {
Victor Stinner2fd76e42011-03-14 15:19:39 -04003375 Py_XDECREF(pathobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 close(fd);
3377 PyMem_FREE(found_encoding);
3378 return NULL;
3379 }
3380 }
3381 else {
3382 fob = Py_None;
3383 Py_INCREF(fob);
3384 }
Victor Stinner2fd76e42011-03-14 15:19:39 -04003385 if (pathobj == NULL) {
3386 Py_INCREF(Py_None);
3387 pathobj = Py_None;
3388 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 ret = Py_BuildValue("NN(ssi)",
3390 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3391 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003394}
3395
Guido van Rossum79f25d91997-04-29 20:08:16 +00003396static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003397imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003398{
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003399 PyObject *name, *path_list = NULL;
3400 if (!PyArg_ParseTuple(args, "U|O:find_module",
3401 &name, &path_list))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 return NULL;
Victor Stinnerad3c03b2011-03-14 09:21:33 -04003403 return call_find_module(name, path_list);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003404}
3405
3406static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003407imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003408{
Victor Stinner95872862011-03-07 18:20:56 +01003409 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 int ret;
3411 PyObject *m;
Victor Stinner95872862011-03-07 18:20:56 +01003412 if (!PyArg_ParseTuple(args, "U:init_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 return NULL;
3414 ret = init_builtin(name);
3415 if (ret < 0)
3416 return NULL;
3417 if (ret == 0) {
3418 Py_INCREF(Py_None);
3419 return Py_None;
3420 }
Victor Stinner95872862011-03-07 18:20:56 +01003421 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 Py_XINCREF(m);
3423 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003424}
3425
Guido van Rossum79f25d91997-04-29 20:08:16 +00003426static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003427imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003428{
Victor Stinner53dc7352011-03-20 01:50:21 +01003429 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 int ret;
3431 PyObject *m;
Victor Stinner53dc7352011-03-20 01:50:21 +01003432 if (!PyArg_ParseTuple(args, "U:init_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 return NULL;
Victor Stinner53dc7352011-03-20 01:50:21 +01003434 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 if (ret < 0)
3436 return NULL;
3437 if (ret == 0) {
3438 Py_INCREF(Py_None);
3439 return Py_None;
3440 }
Victor Stinner53dc7352011-03-20 01:50:21 +01003441 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 Py_XINCREF(m);
3443 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003444}
3445
Guido van Rossum79f25d91997-04-29 20:08:16 +00003446static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003447imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003448{
Victor Stinner53dc7352011-03-20 01:50:21 +01003449 PyObject *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003450
Victor Stinner53dc7352011-03-20 01:50:21 +01003451 if (!PyArg_ParseTuple(args, "U:get_frozen_object", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 return NULL;
3453 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003454}
3455
Guido van Rossum79f25d91997-04-29 20:08:16 +00003456static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003457imp_is_frozen_package(PyObject *self, PyObject *args)
3458{
Victor Stinner53dc7352011-03-20 01:50:21 +01003459 PyObject *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003460
Victor Stinner53dc7352011-03-20 01:50:21 +01003461 if (!PyArg_ParseTuple(args, "U:is_frozen_package", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 return NULL;
3463 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003464}
3465
3466static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003467imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003468{
Victor Stinner95872862011-03-07 18:20:56 +01003469 PyObject *name;
3470 if (!PyArg_ParseTuple(args, "U:is_builtin", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 return NULL;
3472 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003473}
3474
Guido van Rossum79f25d91997-04-29 20:08:16 +00003475static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003476imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003477{
Victor Stinner53dc7352011-03-20 01:50:21 +01003478 PyObject *name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003479 struct _frozen *p;
Victor Stinner53dc7352011-03-20 01:50:21 +01003480 if (!PyArg_ParseTuple(args, "U:is_frozen", &name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 return NULL;
3482 p = find_frozen(name);
3483 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003484}
3485
3486static FILE *
Victor Stinner2f42ae52011-03-20 00:41:24 +01003487get_file(PyObject *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 FILE *fp;
3490 if (mode[0] == 'U')
3491 mode = "r" PY_STDIOTEXTMODE;
3492 if (fob == NULL) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003493 fp = _Py_fopen(pathname, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003494 if (!fp) {
3495 if (!PyErr_Occurred())
3496 PyErr_SetFromErrno(PyExc_IOError);
3497 return NULL;
3498 }
3499 return fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 }
3501 else {
3502 int fd = PyObject_AsFileDescriptor(fob);
3503 if (fd == -1)
3504 return NULL;
Victor Stinner35734762011-12-18 21:05:22 +01003505 if (!_PyVerify_fd(fd)) {
3506 PyErr_SetFromErrno(PyExc_IOError);
3507 return NULL;
3508 }
3509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 /* the FILE struct gets a new fd, so that it can be closed
3511 * independently of the file descriptor given
3512 */
3513 fd = dup(fd);
Victor Stinner35734762011-12-18 21:05:22 +01003514 if (fd == -1) {
3515 PyErr_SetFromErrno(PyExc_IOError);
3516 return NULL;
3517 }
3518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 fp = fdopen(fd, mode);
Victor Stinner35734762011-12-18 21:05:22 +01003520 if (!fp) {
3521 PyErr_SetFromErrno(PyExc_IOError);
3522 return NULL;
3523 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 return fp;
Victor Stinner35734762011-12-18 21:05:22 +01003525 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003526}
3527
Guido van Rossum79f25d91997-04-29 20:08:16 +00003528static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003529imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003530{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003531 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 PyObject *fob = NULL;
3533 PyObject *m;
3534 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003535 if (!PyArg_ParseTuple(args, "UO&|O:load_compiled",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003537 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 &fob))
3539 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003540 fp = get_file(pathname, fob, "rb");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003542 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 return NULL;
3544 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003545 m = load_compiled_module(name, pathname, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 fclose(fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003547 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003549}
3550
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003551#ifdef HAVE_DYNAMIC_LOADING
3552
Guido van Rossum79f25d91997-04-29 20:08:16 +00003553static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003554imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003555{
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003556 PyObject *name, *pathname, *fob = NULL, *mod;
3557 FILE *fp;
3558
3559 if (!PyArg_ParseTuple(args, "UO&|O:load_dynamic",
3560 &name, PyUnicode_FSDecoder, &pathname, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 return NULL;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003562 if (fob != NULL) {
3563 fp = get_file(NULL, fob, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003564 if (fp == NULL) {
3565 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003569 else
3570 fp = NULL;
3571 mod = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinnere9ddbf62011-03-22 10:46:35 +01003572 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 if (fp)
3574 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04003575 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003576}
3577
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003578#endif /* HAVE_DYNAMIC_LOADING */
3579
Guido van Rossum79f25d91997-04-29 20:08:16 +00003580static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003581imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003582{
Victor Stinner2f42ae52011-03-20 00:41:24 +01003583 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 PyObject *fob = NULL;
3585 PyObject *m;
3586 FILE *fp;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003587 if (!PyArg_ParseTuple(args, "UO&|O:load_source",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 &name,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003589 PyUnicode_FSDecoder, &pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 &fob))
3591 return NULL;
Victor Stinner2f42ae52011-03-20 00:41:24 +01003592 fp = get_file(pathname, fob, "r");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 if (fp == NULL) {
Victor Stinnerebc00522010-12-03 17:06:43 +00003594 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 return NULL;
3596 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003597 m = load_source_module(name, pathname, fp);
Victor Stinnerebc00522010-12-03 17:06:43 +00003598 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 fclose(fp);
3600 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003601}
3602
Guido van Rossum79f25d91997-04-29 20:08:16 +00003603static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003604imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003605{
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003606 PyObject *name, *fob, *pathname, *pathname_obj, *ret;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 char *suffix; /* Unused */
3608 char *mode;
3609 int type;
3610 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003611
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003612 if (!PyArg_ParseTuple(args, "UOO(ssi):load_module",
3613 &name, &fob, &pathname_obj, &suffix, &mode, &type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 return NULL;
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003615 if (pathname_obj != Py_None) {
3616 if (!PyUnicode_FSDecoder(pathname_obj, &pathname))
3617 return NULL;
3618 }
3619 else
3620 pathname = NULL;
3621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 if (*mode) {
3623 /* Mode must start with 'r' or 'U' and must not contain '+'.
3624 Implicit in this test is the assumption that the mode
3625 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3628 PyErr_Format(PyExc_ValueError,
3629 "invalid file open mode %.200s", mode);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003630 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 return NULL;
3632 }
3633 }
3634 if (fob == Py_None)
3635 fp = NULL;
3636 else {
3637 fp = get_file(NULL, fob, mode);
3638 if (fp == NULL) {
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003639 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 return NULL;
3641 }
3642 }
Victor Stinner41c5fec2011-03-13 21:46:30 -04003643 ret = load_module(name, fp, pathname, type, NULL);
Victor Stinner6ae1e7f2011-03-20 22:37:17 +01003644 Py_XDECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 if (fp)
3646 fclose(fp);
3647 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003648}
3649
3650static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003651imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003652{
Victor Stinnerc9abda02011-03-14 13:33:46 -04003653 PyObject *name, *pathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 PyObject * ret;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003655 if (!PyArg_ParseTuple(args, "UO&:load_package",
3656 &name, PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 return NULL;
Victor Stinnerc9abda02011-03-14 13:33:46 -04003658 ret = load_package(name, pathname);
Victor Stinnerebc00522010-12-03 17:06:43 +00003659 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003661}
3662
3663static PyObject *
Christian Heimes13a7a212008-01-07 17:13:09 +00003664imp_reload(PyObject *self, PyObject *v)
3665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003667}
3668
3669PyDoc_STRVAR(doc_reload,
3670"reload(module) -> module\n\
3671\n\
3672Reload the module. The module must have been successfully imported before.");
3673
Barry Warsaw28a691b2010-04-17 00:19:56 +00003674static PyObject *
3675imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003678
Victor Stinner2f42ae52011-03-20 00:41:24 +01003679 PyObject *pathname, *cpathname;
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003680 PyObject *debug_override = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003684 args, kws, "O&|O", kwlist,
Victor Stinner2f42ae52011-03-20 00:41:24 +01003685 PyUnicode_FSDecoder, &pathname, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003687
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003688 if (debug_override != NULL &&
3689 (debug = PyObject_IsTrue(debug_override)) < 0) {
Victor Stinner2f42ae52011-03-20 00:41:24 +01003690 Py_DECREF(pathname);
Benjamin Peterson294a9fc2010-10-16 03:12:39 +00003691 return NULL;
3692 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00003693
Martin v. Löwis30260a72011-10-23 17:35:46 +02003694 if (PyUnicode_READY(pathname) < 0)
3695 return NULL;
3696
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003697 cpathname = make_compiled_pathname(pathname, debug);
Victor Stinner2f42ae52011-03-20 00:41:24 +01003698 Py_DECREF(pathname);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 if (cpathname == NULL) {
3701 PyErr_Format(PyExc_SystemError, "path buffer too short");
3702 return NULL;
3703 }
Victor Stinner2f42ae52011-03-20 00:41:24 +01003704 return cpathname;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003705}
3706
3707PyDoc_STRVAR(doc_cache_from_source,
Éric Araujo5df11082011-11-03 03:38:44 +01003708"cache_from_source(path, [debug_override]) -> path\n\
3709Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003710\n\
3711The .py file does not need to exist; this simply returns the path to the\n\
3712.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3713will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3714\n\
3715If debug_override is not None, then it must be a boolean and is taken as\n\
3716the value of __debug__ instead.");
3717
3718static PyObject *
3719imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 static char *kwlist[] = {"path", NULL};
Victor Stinnerc9abda02011-03-14 13:33:46 -04003722 PyObject *pathname, *source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 if (!PyArg_ParseTupleAndKeywords(
Victor Stinnerebc00522010-12-03 17:06:43 +00003725 args, kws, "O&", kwlist,
Victor Stinnerc9abda02011-03-14 13:33:46 -04003726 PyUnicode_FSDecoder, &pathname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003728
Victor Stinnerc9abda02011-03-14 13:33:46 -04003729 source = make_source_pathname(pathname);
3730 if (source == NULL) {
3731 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 pathname);
Victor Stinnerc9abda02011-03-14 13:33:46 -04003733 Py_DECREF(pathname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 return NULL;
3735 }
Victor Stinnerc9abda02011-03-14 13:33:46 -04003736 Py_DECREF(pathname);
3737 return source;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003738}
3739
3740PyDoc_STRVAR(doc_source_from_cache,
Éric Araujo5df11082011-11-03 03:38:44 +01003741"source_from_cache(path) -> path\n\
3742Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
Barry Warsaw28a691b2010-04-17 00:19:56 +00003743\n\
3744The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3745the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3746does not conform to PEP 3147 format, ValueError will be raised.");
3747
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003748/* Doc strings */
3749
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003750PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04003751"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003753PyDoc_STRVAR(doc_find_module,
3754"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003755Search for a module. If path is omitted or None, search for a\n\
3756built-in, frozen or special module and continue search in sys.path.\n\
3757The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003758package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003760PyDoc_STRVAR(doc_load_module,
3761"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003762Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003763The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003765PyDoc_STRVAR(doc_get_magic,
3766"get_magic() -> string\n\
3767Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003768
Barry Warsaw28a691b2010-04-17 00:19:56 +00003769PyDoc_STRVAR(doc_get_tag,
3770"get_tag() -> string\n\
3771Return the magic tag for .pyc or .pyo files.");
3772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003773PyDoc_STRVAR(doc_get_suffixes,
3774"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003775Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003776that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003778PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003779"lock_held() -> boolean\n\
3780Return True if the import lock is currently held, else False.\n\
3781On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003782
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003783PyDoc_STRVAR(doc_acquire_lock,
3784"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003785Acquires the interpreter's import lock for the current thread.\n\
3786This lock should be used by import hooks to ensure thread-safety\n\
3787when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003788On platforms without threads, this function does nothing.");
3789
3790PyDoc_STRVAR(doc_release_lock,
3791"release_lock() -> None\n\
3792Release the interpreter's import lock.\n\
3793On platforms without threads, this function does nothing.");
3794
Guido van Rossum79f25d91997-04-29 20:08:16 +00003795static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3797 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3798 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3799 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3800 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3802 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3803 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3804 {"reload", imp_reload, METH_O, doc_reload},
3805 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3806 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3807 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3808 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3809 /* The rest are obsolete */
3810 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3811 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3812 {"init_builtin", imp_init_builtin, METH_VARARGS},
3813 {"init_frozen", imp_init_frozen, METH_VARARGS},
3814 {"is_builtin", imp_is_builtin, METH_VARARGS},
3815 {"is_frozen", imp_is_frozen, METH_VARARGS},
3816 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003817#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003819#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 {"load_package", imp_load_package, METH_VARARGS},
3821 {"load_source", imp_load_source, METH_VARARGS},
Brett Cannon442c9b92011-03-23 16:14:42 -07003822 {"_fix_co_filename", imp_fix_co_filename, METH_VARARGS},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003824};
3825
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003826static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003827setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 PyObject *v;
3830 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 v = PyLong_FromLong((long)value);
3833 err = PyDict_SetItemString(d, name, v);
3834 Py_XDECREF(v);
3835 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003836}
3837
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003838typedef struct {
3839 PyObject_HEAD
3840} NullImporter;
3841
3842static int
3843NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3844{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003845#ifndef MS_WINDOWS
3846 PyObject *path;
3847 struct stat statbuf;
3848 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3851 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003852
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003853 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3854 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003856
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003857 if (PyBytes_GET_SIZE(path) == 0) {
3858 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 PyErr_SetString(PyExc_ImportError, "empty pathname");
3860 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003862
3863 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3864 Py_DECREF(path);
3865 if (rv == 0) {
3866 /* it exists */
3867 if (S_ISDIR(statbuf.st_mode)) {
3868 /* it's a directory */
3869 PyErr_SetString(PyExc_ImportError, "existing directory");
3870 return -1;
3871 }
3872 }
3873#else /* MS_WINDOWS */
3874 PyObject *pathobj;
3875 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003876 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003877
3878 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3879 return -1;
3880
3881 if (!PyArg_ParseTuple(args, "U:NullImporter",
3882 &pathobj))
3883 return -1;
3884
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885 if (PyUnicode_GET_LENGTH(pathobj) == 0) {
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003886 PyErr_SetString(PyExc_ImportError, "empty pathname");
3887 return -1;
3888 }
3889
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003890 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003891 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003892 return -1;
3893 /* see issue1293 and issue3677:
3894 * stat() on Windows doesn't recognise paths like
3895 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3896 */
3897 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003898 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003899 if (rv != INVALID_FILE_ATTRIBUTES) {
3900 /* it exists */
3901 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3902 /* it's a directory */
3903 PyErr_SetString(PyExc_ImportError, "existing directory");
3904 return -1;
3905 }
3906 }
3907#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003909}
3910
3911static PyObject *
3912NullImporter_find_module(NullImporter *self, PyObject *args)
3913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003915}
3916
3917static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3919 "Always return None"
3920 },
3921 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003922};
3923
3924
Christian Heimes9cd17752007-11-18 19:35:23 +00003925PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 PyVarObject_HEAD_INIT(NULL, 0)
3927 "imp.NullImporter", /*tp_name*/
3928 sizeof(NullImporter), /*tp_basicsize*/
3929 0, /*tp_itemsize*/
3930 0, /*tp_dealloc*/
3931 0, /*tp_print*/
3932 0, /*tp_getattr*/
3933 0, /*tp_setattr*/
3934 0, /*tp_reserved*/
3935 0, /*tp_repr*/
3936 0, /*tp_as_number*/
3937 0, /*tp_as_sequence*/
3938 0, /*tp_as_mapping*/
3939 0, /*tp_hash */
3940 0, /*tp_call*/
3941 0, /*tp_str*/
3942 0, /*tp_getattro*/
3943 0, /*tp_setattro*/
3944 0, /*tp_as_buffer*/
3945 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3946 "Null importer object", /* tp_doc */
3947 0, /* tp_traverse */
3948 0, /* tp_clear */
3949 0, /* tp_richcompare */
3950 0, /* tp_weaklistoffset */
3951 0, /* tp_iter */
3952 0, /* tp_iternext */
3953 NullImporter_methods, /* tp_methods */
3954 0, /* tp_members */
3955 0, /* tp_getset */
3956 0, /* tp_base */
3957 0, /* tp_dict */
3958 0, /* tp_descr_get */
3959 0, /* tp_descr_set */
3960 0, /* tp_dictoffset */
3961 (initproc)NullImporter_init, /* tp_init */
3962 0, /* tp_alloc */
3963 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003964};
3965
Martin v. Löwis1a214512008-06-11 05:26:20 +00003966static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04003968 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 doc_imp,
3970 0,
3971 imp_methods,
3972 NULL,
3973 NULL,
3974 NULL,
3975 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003976};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003977
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003978PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003979PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 if (PyType_Ready(&PyNullImporter_Type) < 0)
3984 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 m = PyModule_Create(&impmodule);
3987 if (m == NULL)
3988 goto failure;
3989 d = PyModule_GetDict(m);
3990 if (d == NULL)
3991 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3994 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3995 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3996 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3997 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3998 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3999 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
4000 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
4001 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
4002 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 Py_INCREF(&PyNullImporter_Type);
4005 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
4006 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00004007 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 Py_XDECREF(m);
4009 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00004010}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004011
4012
Guido van Rossumb18618d2000-05-03 23:44:39 +00004013/* API for embedding applications that want to add their own entries
4014 to the table of built-in modules. This should normally be called
4015 *before* Py_Initialize(). When the table resize fails, -1 is
4016 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004017
4018 After a similar function by Just van Rossum. */
4019
4020int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00004021PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 static struct _inittab *our_copy = NULL;
4024 struct _inittab *p;
4025 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 /* Count the number of entries in both tables */
4028 for (n = 0; newtab[n].name != NULL; n++)
4029 ;
4030 if (n == 0)
4031 return 0; /* Nothing to do */
4032 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
4033 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 /* Allocate new memory for the combined table */
4036 p = our_copy;
4037 PyMem_RESIZE(p, struct _inittab, i+n+1);
4038 if (p == NULL)
4039 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 /* Copy the tables into the new memory */
4042 if (our_copy != PyImport_Inittab)
4043 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
4044 PyImport_Inittab = our_copy = p;
4045 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004048}
4049
4050/* Shorthand to add a single entry given a name and a function */
4051
4052int
Brett Cannona826f322009-04-02 03:41:46 +00004053PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 newtab[0].name = (char *)name;
4060 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00004063}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004064
4065#ifdef __cplusplus
4066}
4067#endif