blob: 6a4143955e559aa55bc14cb12dc7a8efe1e547b2 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000022extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Christian Heimesd3eb5a152008-02-24 00:38:49 +000025#ifdef MS_WINDOWS
26/* for stat.st_mode */
27typedef unsigned short mode_t;
Daniel Stutzbachc7937792010-09-09 21:18:04 +000028/* for _mkdir */
29#include <direct.h>
Christian Heimesd3eb5a152008-02-24 00:38:49 +000030#endif
31
Guido van Rossum21d335e1993-10-15 13:01:11 +000032
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000033/* Magic word to reject .pyc files generated by other Python versions.
34 It should change for each incompatible change to the bytecode.
35
36 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000037 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000038 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039
Guido van Rossum45aecf42006-03-15 04:58:47 +000040 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000041 -U interpeter flag will cause MAGIC+1 being used. They have been
42 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000044 There were a variety of old schemes for setting the magic number.
45 The current working scheme is to increment the previous value by
46 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000047
Barry Warsaw28a691b2010-04-17 00:19:56 +000048 Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
49 number also includes a new "magic tag", i.e. a human readable string used
50 to represent the magic number in __pycache__ directories. When you change
51 the magic number, you must also set a new unique magic tag. Generally this
52 can be named after the Python major version of the magic number bump, but
53 it can really be anything, as long as it's different than anything else
54 that's come before. The tags are included in the following table, starting
55 with Python 3.2a0.
56
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000057 Known values:
58 Python 1.5: 20121
59 Python 1.5.1: 20121
60 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000062 Python 2.0: 50823
63 Python 2.0.1: 50823
64 Python 2.1: 60202
65 Python 2.1.1: 60202
66 Python 2.1.2: 60202
67 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000068 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000069 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000070 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000071 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000072 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000073 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000074 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000075 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000076 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000077 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
79 Python 2.5b3: 62111 (fix wrong code: x += yield)
80 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000082 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Christian Heimes99170a52007-12-19 02:07:34 +000083 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Christian Heimesdd15f6c2008-03-16 00:07:10 +000084 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Guido van Rossum45aecf42006-03-15 04:58:47 +000085 Python 3000: 3000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 3010 (removed UNARY_CONVERT)
87 3020 (added BUILD_SET)
88 3030 (added keyword-only parameters)
89 3040 (added signature annotations)
90 3050 (print becomes a function)
91 3060 (PEP 3115 metaclass syntax)
92 3061 (string literals become unicode)
93 3071 (PEP 3109 raise changes)
94 3081 (PEP 3137 make __file__ and __name__ unicode)
95 3091 (kill str8 interning)
96 3101 (merge from 2.6a0, see 62151)
97 3103 (__file__ points to source file)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +000098 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
99 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
100 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 change LIST_APPEND and SET_ADD, add MAP_ADD)
Benjamin Peterson0f6cae02009-12-10 02:09:08 +0000102 Python 3.1a0: 3151 (optimize conditional branches:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Benjamin Peterson876b2f22009-06-28 03:18:59 +0000104 Python 3.2a0: 3160 (add SETUP_WITH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 tag: cpython-32
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000106 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
107 tag: cpython-32
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000108 Python 3.2a2 3180 (add DELETE_DEREF)
Tim Peters36515e22001-11-18 04:06:29 +0000109*/
Guido van Rossum3ddee711991-12-16 13:06:34 +0000110
Nick Coghlancd419ab2010-09-11 00:39:25 +0000111/* MAGIC must change whenever the bytecode emitted by the compiler may no
112 longer be understood by older implementations of the eval loop (usually
113 due to the addition of new opcodes)
114 TAG must change for each major Python release. The magic number will take
115 care of any bytecode changes that occur during development.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116*/
Benjamin Peterson6246d6d2010-09-10 21:51:44 +0000117#define MAGIC (3180 | ((long)'\r'<<16) | ((long)'\n'<<24))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000118#define TAG "cpython-32"
119#define CACHEDIR "__pycache__"
120/* Current magic word and string tag as globals. */
Guido van Rossum96774c12000-05-01 20:19:08 +0000121static long pyc_magic = MAGIC;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122static const char *pyc_tag = TAG;
Guido van Rossum96774c12000-05-01 20:19:08 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124/* See _PyImport_FixupExtension() below */
125static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000126
Guido van Rossum771c6c81997-10-31 18:37:24 +0000127/* This table is defined in config.c: */
128extern struct _inittab _PyImport_Inittab[];
129
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000130/* Method from Parser/tokenizer.c */
Guido van Rossum40d20bc2007-10-22 00:09:51 +0000131extern char * PyTokenizer_FindEncoding(int);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000132
Guido van Rossum771c6c81997-10-31 18:37:24 +0000133struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +0000134
Guido van Rossumed1170e1999-12-20 21:23:41 +0000135/* these tables define the module suffixes that Python recognizes */
136struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +0000137
Guido van Rossumed1170e1999-12-20 21:23:41 +0000138static const struct filedescr _PyImport_StandardFiletab[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000140#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000142#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 {".pyc", "rb", PY_COMPILED},
144 {0, 0}
Guido van Rossumed1170e1999-12-20 21:23:41 +0000145};
146
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000147
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000148/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149
150void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000151_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 const struct filedescr *scan;
154 struct filedescr *filetab;
155 int countD = 0;
156 int countS = 0;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 /* prepare _PyImport_Filetab: copy entries from
159 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
160 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000161#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
163 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000164#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
166 ++countS;
167 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
168 if (filetab == NULL)
169 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000170#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 memcpy(filetab, _PyImport_DynLoadFiletab,
172 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000173#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 memcpy(filetab + countD, _PyImport_StandardFiletab,
175 countS * sizeof(struct filedescr));
176 filetab[countD + countS].suffix = NULL;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 _PyImport_Filetab = filetab;
Guido van Rossumed1170e1999-12-20 21:23:41 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (Py_OptimizeFlag) {
181 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
182 for (; filetab->suffix != NULL; filetab++) {
183 if (strcmp(filetab->suffix, ".pyc") == 0)
184 filetab->suffix = ".pyo";
185 }
186 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187}
188
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189void
Just van Rossum52e14d62002-12-30 22:08:05 +0000190_PyImportHooks_Init(void)
191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyObject *v, *path_hooks = NULL, *zimpimport;
193 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* adding sys.path_hooks and sys.path_importer_cache, setting up
196 zipimport */
197 if (PyType_Ready(&PyNullImporter_Type) < 0)
198 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 if (Py_VerboseFlag)
201 PySys_WriteStderr("# installing zipimport hook\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 v = PyList_New(0);
204 if (v == NULL)
205 goto error;
206 err = PySys_SetObject("meta_path", v);
207 Py_DECREF(v);
208 if (err)
209 goto error;
210 v = PyDict_New();
211 if (v == NULL)
212 goto error;
213 err = PySys_SetObject("path_importer_cache", v);
214 Py_DECREF(v);
215 if (err)
216 goto error;
217 path_hooks = PyList_New(0);
218 if (path_hooks == NULL)
219 goto error;
220 err = PySys_SetObject("path_hooks", path_hooks);
221 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +0000222 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyErr_Print();
224 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
225 "path_importer_cache, or NullImporter failed"
226 );
227 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 zimpimport = PyImport_ImportModule("zipimport");
230 if (zimpimport == NULL) {
231 PyErr_Clear(); /* No zip import module -- okay */
232 if (Py_VerboseFlag)
233 PySys_WriteStderr("# can't import zipimport\n");
234 }
235 else {
236 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
237 "zipimporter");
238 Py_DECREF(zimpimport);
239 if (zipimporter == NULL) {
240 PyErr_Clear(); /* No zipimporter object -- okay */
241 if (Py_VerboseFlag)
242 PySys_WriteStderr(
243 "# can't import zipimport.zipimporter\n");
244 }
245 else {
246 /* sys.path_hooks.append(zipimporter) */
247 err = PyList_Append(path_hooks, zipimporter);
248 Py_DECREF(zipimporter);
249 if (err)
250 goto error;
251 if (Py_VerboseFlag)
252 PySys_WriteStderr(
253 "# installed zipimport hook\n");
254 }
255 }
256 Py_DECREF(path_hooks);
Just van Rossum52e14d62002-12-30 22:08:05 +0000257}
258
259void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000260_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 Py_XDECREF(extensions);
263 extensions = NULL;
264 PyMem_DEL(_PyImport_Filetab);
265 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000266}
267
268
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269/* Locking primitives to prevent parallel imports of the same module
270 in different threads to return with a partially loaded module.
271 These calls are serialized by the global interpreter lock. */
272
273#ifdef WITH_THREAD
274
Guido van Rossum49b56061998-10-01 20:42:43 +0000275#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000276
Guido van Rossum65d5b571998-12-21 19:32:43 +0000277static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000278static long import_lock_thread = -1;
279static int import_lock_level = 0;
280
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000281void
282_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 long me = PyThread_get_thread_ident();
285 if (me == -1)
286 return; /* Too bad */
287 if (import_lock == NULL) {
288 import_lock = PyThread_allocate_lock();
289 if (import_lock == NULL)
290 return; /* Nothing much we can do. */
291 }
292 if (import_lock_thread == me) {
293 import_lock_level++;
294 return;
295 }
296 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
297 {
298 PyThreadState *tstate = PyEval_SaveThread();
299 PyThread_acquire_lock(import_lock, 1);
300 PyEval_RestoreThread(tstate);
301 }
302 import_lock_thread = me;
303 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000304}
305
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000306int
307_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 long me = PyThread_get_thread_ident();
310 if (me == -1 || import_lock == NULL)
311 return 0; /* Too bad */
312 if (import_lock_thread != me)
313 return -1;
314 import_lock_level--;
315 if (import_lock_level == 0) {
316 import_lock_thread = -1;
317 PyThread_release_lock(import_lock);
318 }
319 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000320}
321
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000322/* This function is called from PyOS_AfterFork to ensure that newly
323 created child processes do not share locks with the parent.
324 We now acquire the import lock around fork() calls but on some platforms
325 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000326
327void
328_PyImport_ReInitLock(void)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (import_lock != NULL)
331 import_lock = PyThread_allocate_lock();
332 import_lock_thread = -1;
333 import_lock_level = 0;
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000334}
335
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000336#endif
337
Tim Peters69232342001-08-30 05:16:13 +0000338static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000339imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000340{
Tim Peters69232342001-08-30 05:16:13 +0000341#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000343#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000345#endif
346}
347
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000348static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000349imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000350{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000351#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000353#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 Py_INCREF(Py_None);
355 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000356}
357
358static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000359imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000360{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000361#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (_PyImport_ReleaseLock() < 0) {
363 PyErr_SetString(PyExc_RuntimeError,
364 "not holding the import lock");
365 return NULL;
366 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000367#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 Py_INCREF(Py_None);
369 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000370}
371
Guido van Rossumd8faa362007-04-27 19:54:29 +0000372static void
373imp_modules_reloading_clear(void)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyInterpreterState *interp = PyThreadState_Get()->interp;
376 if (interp->modules_reloading != NULL)
377 PyDict_Clear(interp->modules_reloading);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000378}
379
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380/* Helper for sys */
381
382PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000383PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyInterpreterState *interp = PyThreadState_GET()->interp;
386 if (interp->modules == NULL)
387 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
388 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389}
390
Guido van Rossum3f5da241990-12-20 15:06:42 +0000391
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392/* List of names to clear in sys */
393static char* sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 "path", "argv", "ps1", "ps2",
395 "last_type", "last_value", "last_traceback",
396 "path_hooks", "path_importer_cache", "meta_path",
397 /* misc stuff */
398 "flags", "float_info",
399 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000400};
401
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000402static char* sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 "stdin", "__stdin__",
404 "stdout", "__stdout__",
405 "stderr", "__stderr__",
406 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000407};
408
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000409
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000410/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000411
Guido van Rossum3f5da241990-12-20 15:06:42 +0000412void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000413PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 Py_ssize_t pos, ndone;
416 char *name;
417 PyObject *key, *value, *dict;
418 PyInterpreterState *interp = PyThreadState_GET()->interp;
419 PyObject *modules = interp->modules;
Guido van Rossum758eec01998-01-19 21:58:26 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (modules == NULL)
422 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* Delete some special variables first. These are common
425 places where user values hide and people complain when their
426 destructors fail. Since the modules containing them are
427 deleted *last* of all, they would come too late in the normal
428 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 value = PyDict_GetItemString(modules, "builtins");
431 if (value != NULL && PyModule_Check(value)) {
432 dict = PyModule_GetDict(value);
433 if (Py_VerboseFlag)
434 PySys_WriteStderr("# clear builtins._\n");
435 PyDict_SetItemString(dict, "_", Py_None);
436 }
437 value = PyDict_GetItemString(modules, "sys");
438 if (value != NULL && PyModule_Check(value)) {
439 char **p;
440 PyObject *v;
441 dict = PyModule_GetDict(value);
442 for (p = sys_deletes; *p != NULL; p++) {
443 if (Py_VerboseFlag)
444 PySys_WriteStderr("# clear sys.%s\n", *p);
445 PyDict_SetItemString(dict, *p, Py_None);
446 }
447 for (p = sys_files; *p != NULL; p+=2) {
448 if (Py_VerboseFlag)
449 PySys_WriteStderr("# restore sys.%s\n", *p);
450 v = PyDict_GetItemString(dict, *(p+1));
451 if (v == NULL)
452 v = Py_None;
453 PyDict_SetItemString(dict, *p, v);
454 }
455 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* First, delete __main__ */
458 value = PyDict_GetItemString(modules, "__main__");
459 if (value != NULL && PyModule_Check(value)) {
460 if (Py_VerboseFlag)
461 PySys_WriteStderr("# cleanup __main__\n");
462 _PyModule_Clear(value);
463 PyDict_SetItemString(modules, "__main__", Py_None);
464 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 /* The special treatment of "builtins" here is because even
467 when it's not referenced as a module, its dictionary is
468 referenced by almost every module's __builtins__. Since
469 deleting a module clears its dictionary (even if there are
470 references left to it), we need to delete the "builtins"
471 module last. Likewise, we don't delete sys until the very
472 end because it is implicitly referenced (e.g. by print).
Guido van Rossum758eec01998-01-19 21:58:26 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 Also note that we 'delete' modules by replacing their entry
475 in the modules dict with None, rather than really deleting
476 them; this avoids a rehash of the modules dictionary and
477 also marks them as "non existent" so they won't be
478 re-imported. */
Guido van Rossum758eec01998-01-19 21:58:26 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* Next, repeatedly delete modules with a reference count of
481 one (skipping builtins and sys) and delete them */
482 do {
483 ndone = 0;
484 pos = 0;
485 while (PyDict_Next(modules, &pos, &key, &value)) {
486 if (value->ob_refcnt != 1)
487 continue;
488 if (PyUnicode_Check(key) && PyModule_Check(value)) {
489 name = _PyUnicode_AsString(key);
490 if (strcmp(name, "builtins") == 0)
491 continue;
492 if (strcmp(name, "sys") == 0)
493 continue;
494 if (Py_VerboseFlag)
495 PySys_WriteStderr(
496 "# cleanup[1] %s\n", name);
497 _PyModule_Clear(value);
498 PyDict_SetItem(modules, key, Py_None);
499 ndone++;
500 }
501 }
502 } while (ndone > 0);
Guido van Rossum758eec01998-01-19 21:58:26 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Next, delete all modules (still skipping builtins and sys) */
505 pos = 0;
506 while (PyDict_Next(modules, &pos, &key, &value)) {
507 if (PyUnicode_Check(key) && PyModule_Check(value)) {
508 name = _PyUnicode_AsString(key);
509 if (strcmp(name, "builtins") == 0)
510 continue;
511 if (strcmp(name, "sys") == 0)
512 continue;
513 if (Py_VerboseFlag)
514 PySys_WriteStderr("# cleanup[2] %s\n", name);
515 _PyModule_Clear(value);
516 PyDict_SetItem(modules, key, Py_None);
517 }
518 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 /* Next, delete sys and builtins (in that order) */
521 value = PyDict_GetItemString(modules, "sys");
522 if (value != NULL && PyModule_Check(value)) {
523 if (Py_VerboseFlag)
524 PySys_WriteStderr("# cleanup sys\n");
525 _PyModule_Clear(value);
526 PyDict_SetItemString(modules, "sys", Py_None);
527 }
528 value = PyDict_GetItemString(modules, "builtins");
529 if (value != NULL && PyModule_Check(value)) {
530 if (Py_VerboseFlag)
531 PySys_WriteStderr("# cleanup builtins\n");
532 _PyModule_Clear(value);
533 PyDict_SetItemString(modules, "builtins", Py_None);
534 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Finally, clear and delete the modules directory */
537 PyDict_Clear(modules);
538 interp->modules = NULL;
539 Py_DECREF(modules);
540 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000541}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000542
543
Barry Warsaw28a691b2010-04-17 00:19:56 +0000544/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545
546long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550}
551
552
Barry Warsaw28a691b2010-04-17 00:19:56 +0000553const char *
554PyImport_GetMagicTag(void)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return pyc_tag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000557}
558
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559/* Magic for extension modules (built-in as well as dynamically
560 loaded). To prevent initializing an extension module more than
561 once, we keep a static dictionary 'extensions' keyed by module name
562 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000563 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 dictionary is stored by calling _PyImport_FixupExtension()
565 immediately after the module initialization function succeeds. A
566 copy can be retrieved from there by calling
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000567 _PyImport_FindExtension().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000568
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000569 Modules which do support multiple initialization set their m_size
570 field to a non-negative number (indicating the size of the
571 module-specific state). They are still recorded in the extensions
572 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000573*/
574
575int
576_PyImport_FixupExtension(PyObject *mod, char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 PyObject *modules, *dict;
579 struct PyModuleDef *def;
580 if (extensions == NULL) {
581 extensions = PyDict_New();
582 if (extensions == NULL)
583 return -1;
584 }
585 if (mod == NULL || !PyModule_Check(mod)) {
586 PyErr_BadInternalCall();
587 return -1;
588 }
589 def = PyModule_GetDef(mod);
590 if (!def) {
591 PyErr_BadInternalCall();
592 return -1;
593 }
594 modules = PyImport_GetModuleDict();
595 if (PyDict_SetItemString(modules, name, mod) < 0)
596 return -1;
597 if (_PyState_AddModule(mod, def) < 0) {
598 PyDict_DelItemString(modules, name);
599 return -1;
600 }
601 if (def->m_size == -1) {
602 if (def->m_base.m_copy) {
603 /* Somebody already imported the module,
604 likely under a different name.
605 XXX this should really not happen. */
606 Py_DECREF(def->m_base.m_copy);
607 def->m_base.m_copy = NULL;
608 }
609 dict = PyModule_GetDict(mod);
610 if (dict == NULL)
611 return -1;
612 def->m_base.m_copy = PyDict_Copy(dict);
613 if (def->m_base.m_copy == NULL)
614 return -1;
615 }
616 PyDict_SetItemString(extensions, filename, (PyObject*)def);
617 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618}
619
620PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000621_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyObject *mod, *mdict;
624 PyModuleDef* def;
625 if (extensions == NULL)
626 return NULL;
627 def = (PyModuleDef*)PyDict_GetItemString(extensions, filename);
628 if (def == NULL)
629 return NULL;
630 if (def->m_size == -1) {
631 /* Module does not support repeated initialization */
632 if (def->m_base.m_copy == NULL)
633 return NULL;
634 mod = PyImport_AddModule(name);
635 if (mod == NULL)
636 return NULL;
637 mdict = PyModule_GetDict(mod);
638 if (mdict == NULL)
639 return NULL;
640 if (PyDict_Update(mdict, def->m_base.m_copy))
641 return NULL;
642 }
643 else {
644 if (def->m_base.m_init == NULL)
645 return NULL;
646 mod = def->m_base.m_init();
647 if (mod == NULL)
648 return NULL;
649 PyDict_SetItemString(PyImport_GetModuleDict(), name, mod);
650 Py_DECREF(mod);
651 }
652 if (_PyState_AddModule(mod, def) < 0) {
653 PyDict_DelItemString(PyImport_GetModuleDict(), name);
654 Py_DECREF(mod);
655 return NULL;
656 }
657 if (Py_VerboseFlag)
658 PySys_WriteStderr("import %s # previously loaded (%s)\n",
659 name, filename);
660 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000661
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662}
663
664
665/* Get the module object corresponding to a module name.
666 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000667 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000668 Because the former action is most common, THIS DOES NOT RETURN A
669 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000670
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000672PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyObject *modules = PyImport_GetModuleDict();
675 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
678 PyModule_Check(m))
679 return m;
680 m = PyModule_New(name);
681 if (m == NULL)
682 return NULL;
683 if (PyDict_SetItemString(modules, name, m) != 0) {
684 Py_DECREF(m);
685 return NULL;
686 }
687 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000690}
691
Tim Peters1cd70172004-08-02 03:52:12 +0000692/* Remove name from sys.modules, if it's there. */
693static void
Benjamin Petersonfa0aeba2010-03-25 23:30:20 +0000694remove_module(const char *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *modules = PyImport_GetModuleDict();
697 if (PyDict_GetItemString(modules, name) == NULL)
698 return;
699 if (PyDict_DelItemString(modules, name) < 0)
700 Py_FatalError("import: deleting existing key in"
701 "sys.modules failed");
Tim Peters1cd70172004-08-02 03:52:12 +0000702}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000703
Barry Warsaw28a691b2010-04-17 00:19:56 +0000704static PyObject * get_sourcefile(char *file);
705static char *make_source_pathname(char *pathname, char *buf);
706static char *make_compiled_pathname(char *pathname, char *buf, size_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 int debug);
Christian Heimes3b06e532008-01-07 20:12:44 +0000708
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000709/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000710 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
711 * removed from sys.modules, to avoid leaving damaged module objects
712 * in sys.modules. The caller may wish to restore the original
713 * module object (if any) in this case; PyImport_ReloadModule is an
714 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000715 *
716 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
717 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000718 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000719PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000720PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return PyImport_ExecCodeModuleWithPathnames(
723 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000724}
725
726PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000727PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 return PyImport_ExecCodeModuleWithPathnames(
730 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000731}
732
733PyObject *
734PyImport_ExecCodeModuleWithPathnames(char *name, PyObject *co, char *pathname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *modules = PyImport_GetModuleDict();
738 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 m = PyImport_AddModule(name);
741 if (m == NULL)
742 return NULL;
743 /* If the module is being reloaded, we get the old module back
744 and re-use its dict to exec the new code. */
745 d = PyModule_GetDict(m);
746 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
747 if (PyDict_SetItemString(d, "__builtins__",
748 PyEval_GetBuiltins()) != 0)
749 goto error;
750 }
751 /* Remember the filename as the __file__ attribute */
752 v = NULL;
753 if (pathname != NULL) {
754 v = get_sourcefile(pathname);
755 if (v == NULL)
756 PyErr_Clear();
757 }
758 if (v == NULL) {
759 v = ((PyCodeObject *)co)->co_filename;
760 Py_INCREF(v);
761 }
762 if (PyDict_SetItemString(d, "__file__", v) != 0)
763 PyErr_Clear(); /* Not important enough to report */
764 Py_DECREF(v);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* Remember the pyc path name as the __cached__ attribute. */
767 if (cpathname == NULL) {
768 v = Py_None;
769 Py_INCREF(v);
770 }
771 else if ((v = PyUnicode_FromString(cpathname)) == NULL) {
772 PyErr_Clear(); /* Not important enough to report */
773 v = Py_None;
774 Py_INCREF(v);
775 }
776 if (PyDict_SetItemString(d, "__cached__", v) != 0)
777 PyErr_Clear(); /* Not important enough to report */
778 Py_DECREF(v);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
781 if (v == NULL)
782 goto error;
783 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
786 PyErr_Format(PyExc_ImportError,
787 "Loaded module %.200s not found in sys.modules",
788 name);
789 return NULL;
790 }
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000795
796 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 remove_module(name);
798 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000799}
800
801
Barry Warsaw28a691b2010-04-17 00:19:56 +0000802/* Like strrchr(string, '/') but searches for the rightmost of either SEP
803 or ALTSEP, if the latter is defined.
804*/
805static char *
806rightmost_sep(char *s)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 char *found, c;
809 for (found = NULL; (c = *s); s++) {
810 if (c == SEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000811#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 || c == ALTSEP
Barry Warsaw28a691b2010-04-17 00:19:56 +0000813#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 )
815 {
816 found = s;
817 }
818 }
819 return found;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000820}
821
822
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000823/* Given a pathname for a Python source file, fill a buffer with the
824 pathname for the corresponding compiled file. Return the pathname
825 for the compiled file, or NULL if there's no space in the buffer.
826 Doesn't set an exception. */
827
828static char *
Barry Warsaw28a691b2010-04-17 00:19:56 +0000829make_compiled_pathname(char *pathname, char *buf, size_t buflen, int debug)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* foo.py -> __pycache__/foo.<tag>.pyc */
832 size_t len = strlen(pathname);
833 size_t i, save;
834 char *pos;
835 int sep = SEP;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 /* Sanity check that the buffer has roughly enough space to hold what
838 will eventually be the full path to the compiled file. The 5 extra
839 bytes include the slash afer __pycache__, the two extra dots, the
840 extra trailing character ('c' or 'o') and null. This isn't exact
841 because the contents of the buffer can affect how many actual
842 characters of the string get into the buffer. We'll do a final
843 sanity check before writing the extension to ensure we do not
844 overflow the buffer.
845 */
846 if (len + strlen(CACHEDIR) + strlen(pyc_tag) + 5 > buflen)
847 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* Find the last path separator and copy everything from the start of
850 the source string up to and including the separator.
851 */
852 if ((pos = rightmost_sep(pathname)) == NULL) {
853 i = 0;
854 }
855 else {
856 sep = *pos;
857 i = pos - pathname + 1;
858 strncpy(buf, pathname, i);
859 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 save = i;
862 buf[i++] = '\0';
863 /* Add __pycache__/ */
864 strcat(buf, CACHEDIR);
865 i += strlen(CACHEDIR) - 1;
866 buf[i++] = sep;
867 buf[i++] = '\0';
868 /* Add the base filename, but remove the .py or .pyw extension, since
869 the tag name must go before the extension.
870 */
871 strcat(buf, pathname + save);
872 if ((pos = strrchr(buf, '.')) != NULL)
873 *++pos = '\0';
874 strcat(buf, pyc_tag);
875 /* The length test above assumes that we're only adding one character
876 to the end of what would normally be the extension. What if there
877 is no extension, or the string ends in '.' or '.p', and otherwise
878 fills the buffer? By appending 4 more characters onto the string
879 here, we could overrun the buffer.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 As a simple example, let's say buflen=32 and the input string is
882 'xxx.py'. strlen() would be 6 and the test above would yield:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 (6 + 11 + 10 + 5 == 32) > 32
Barry Warsaw28a691b2010-04-17 00:19:56 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 which is false and so the name mangling would continue. This would
887 be fine because we'd end up with this string in buf:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 __pycache__/xxx.cpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 strlen(of that) == 30 + the nul fits inside a 32 character buffer.
892 We can even handle an input string of say 'xxxxx' above because
893 that's (5 + 11 + 10 + 5 == 31) > 32 which is also false. Name
894 mangling that yields:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 __pycache__/xxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 which is 32 characters including the nul, and thus fits in the
899 buffer. However, an input string of 'xxxxxx' would yield a result
900 string of:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 __pycache__/xxxxxxcpython-32.pyc\0
Barry Warsaw28a691b2010-04-17 00:19:56 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 which is 33 characters long (including the nul), thus overflowing
905 the buffer, even though the first test would fail, i.e.: the input
906 string is also 6 characters long, so 32 > 32 is false.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 The reason the first test fails but we still overflow the buffer is
909 that the test above only expects to add one extra character to be
910 added to the extension, and here we're adding three (pyc). We
911 don't add the first dot, so that reclaims one of expected
912 positions, leaving us overflowing by 1 byte (3 extra - 1 reclaimed
913 dot - 1 expected extra == 1 overflowed).
Barry Warsaw28a691b2010-04-17 00:19:56 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 The best we can do is ensure that we still have enough room in the
916 target buffer before we write the extension. Because it's always
917 only the extension that can cause the overflow, and never the other
918 path bytes we've written, it's sufficient to just do one more test
919 here. Still, the assertion that follows can't hurt.
920 */
Barry Warsaw28a691b2010-04-17 00:19:56 +0000921#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 printf("strlen(buf): %d; buflen: %d\n", (int)strlen(buf), (int)buflen);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000923#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (strlen(buf) + 5 > buflen)
925 return NULL;
926 strcat(buf, debug ? ".pyc" : ".pyo");
927 assert(strlen(buf) < buflen);
928 return buf;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000929}
930
931
Barry Warsaw28a691b2010-04-17 00:19:56 +0000932/* Given a pathname to a Python byte compiled file, return the path to the
933 source file, if the path matches the PEP 3147 format. This does not check
934 for any file existence, however, if the pyc file name does not match PEP
935 3147 style, NULL is returned. buf must be at least as big as pathname;
936 the resulting path will always be shorter. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937
Barry Warsaw28a691b2010-04-17 00:19:56 +0000938static char *
939make_source_pathname(char *pathname, char *buf)
940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* __pycache__/foo.<tag>.pyc -> foo.py */
942 size_t i, j;
943 char *left, *right, *dot0, *dot1, sep;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* Look back two slashes from the end. In between these two slashes
946 must be the string __pycache__ or this is not a PEP 3147 style
947 path. It's possible for there to be only one slash.
948 */
949 if ((right = rightmost_sep(pathname)) == NULL)
950 return NULL;
951 sep = *right;
952 *right = '\0';
953 left = rightmost_sep(pathname);
954 *right = sep;
955 if (left == NULL)
956 left = pathname;
957 else
958 left++;
959 if (right-left != strlen(CACHEDIR) ||
960 strncmp(left, CACHEDIR, right-left) != 0)
961 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Now verify that the path component to the right of the last slash
964 has two dots in it.
965 */
966 if ((dot0 = strchr(right + 1, '.')) == NULL)
967 return NULL;
968 if ((dot1 = strchr(dot0 + 1, '.')) == NULL)
969 return NULL;
970 /* Too many dots? */
971 if (strchr(dot1 + 1, '.') != NULL)
972 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* This is a PEP 3147 path. Start by copying everything from the
975 start of pathname up to and including the leftmost slash. Then
976 copy the file's basename, removing the magic tag and adding a .py
977 suffix.
978 */
979 strncpy(buf, pathname, (i=left-pathname));
980 strncpy(buf+i, right+1, (j=dot0-right));
981 strcpy(buf+i+j, "py");
982 return buf;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000983}
984
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000985/* Given a pathname for a Python source file, its time of last
986 modification, and a pathname for a compiled file, check whether the
987 compiled file represents the same version of the source. If so,
988 return a FILE pointer for the compiled file, positioned just after
989 the header; if not, return NULL.
990 Doesn't set an exception. */
991
992static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000993check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 FILE *fp;
996 long magic;
997 long pyc_mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 fp = fopen(cpathname, "rb");
1000 if (fp == NULL)
1001 return NULL;
1002 magic = PyMarshal_ReadLongFromFile(fp);
1003 if (magic != pyc_magic) {
1004 if (Py_VerboseFlag)
1005 PySys_WriteStderr("# %s has bad magic\n", cpathname);
1006 fclose(fp);
1007 return NULL;
1008 }
1009 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
1010 if (pyc_mtime != mtime) {
1011 if (Py_VerboseFlag)
1012 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
1013 fclose(fp);
1014 return NULL;
1015 }
1016 if (Py_VerboseFlag)
1017 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
1018 return fp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001019}
1020
1021
1022/* Read a code object from a file and check it for validity */
1023
Guido van Rossum79f25d91997-04-29 20:08:16 +00001024static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001025read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 co = PyMarshal_ReadLastObjectFromFile(fp);
1030 if (co == NULL)
1031 return NULL;
1032 if (!PyCode_Check(co)) {
1033 PyErr_Format(PyExc_ImportError,
1034 "Non-code object in %.200s", cpathname);
1035 Py_DECREF(co);
1036 return NULL;
1037 }
1038 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001039}
1040
1041
1042/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001043 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001044
Guido van Rossum79f25d91997-04-29 20:08:16 +00001045static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001046load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 long magic;
1049 PyCodeObject *co;
1050 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 magic = PyMarshal_ReadLongFromFile(fp);
1053 if (magic != pyc_magic) {
1054 PyErr_Format(PyExc_ImportError,
1055 "Bad magic number in %.200s", cpathname);
1056 return NULL;
1057 }
1058 (void) PyMarshal_ReadLongFromFile(fp);
1059 co = read_compiled_module(cpathname, fp);
1060 if (co == NULL)
1061 return NULL;
1062 if (Py_VerboseFlag)
1063 PySys_WriteStderr("import %s # precompiled from %s\n",
1064 name, cpathname);
1065 m = PyImport_ExecCodeModuleWithPathnames(
1066 name, (PyObject *)co, cpathname, cpathname);
1067 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001070}
1071
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001072/* Parse a source file and return the corresponding code object */
1073
Guido van Rossum79f25d91997-04-29 20:08:16 +00001074static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyCodeObject *co = NULL;
1078 mod_ty mod;
1079 PyCompilerFlags flags;
1080 PyArena *arena = PyArena_New();
1081 if (arena == NULL)
1082 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 flags.cf_flags = 0;
1085 mod = PyParser_ASTFromFile(fp, pathname, NULL,
1086 Py_file_input, 0, 0, &flags,
1087 NULL, arena);
1088 if (mod) {
1089 co = PyAST_Compile(mod, pathname, NULL, arena);
1090 }
1091 PyArena_Free(arena);
1092 return co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001093}
1094
1095
Guido van Rossum55a83382000-09-20 20:31:38 +00001096/* Helper to open a bytecode file for writing in exclusive mode */
1097
1098static FILE *
Christian Heimes05e8be12008-02-23 18:30:17 +00001099open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +00001100{
1101#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* Use O_EXCL to avoid a race condition when another process tries to
1103 write the same file. When that happens, our open() call fails,
1104 which is just fine (since it's only a cache).
1105 XXX If the file exists and is writable but the directory is not
1106 writable, the file will never be written. Oh well.
1107 */
1108 int fd;
1109 (void) unlink(filename);
1110 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
Tim Peters42c83af2000-09-29 04:03:10 +00001111#ifdef O_BINARY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 |O_BINARY /* necessary for Windows */
Tim Peters42c83af2000-09-29 04:03:10 +00001113#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001114#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001116#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 , mode
Martin v. Löwis79acb9e2002-12-06 12:48:53 +00001118#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 );
1120 if (fd < 0)
1121 return NULL;
1122 return fdopen(fd, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001123#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* Best we can do -- on Windows this can't happen anyway */
1125 return fopen(filename, "wb");
Guido van Rossum55a83382000-09-20 20:31:38 +00001126#endif
1127}
1128
1129
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001130/* Write a compiled module to a file, placing the time of last
1131 modification of its source into the header.
1132 Errors are ignored, if a write error occurs an attempt is made to
1133 remove the file. */
1134
1135static void
Christian Heimes05e8be12008-02-23 18:30:17 +00001136write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 FILE *fp;
1139 char *dirpath;
1140 time_t mtime = srcstat->st_mtime;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001141#ifdef MS_WINDOWS /* since Windows uses different permissions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 mode_t mode = srcstat->st_mode & ~S_IEXEC;
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +00001143#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
1145 mode_t dirmode = (srcstat->st_mode |
1146 S_IXUSR | S_IXGRP | S_IXOTH |
1147 S_IWUSR | S_IWGRP | S_IWOTH);
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001148#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 int saved;
Barry Warsaw28a691b2010-04-17 00:19:56 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 /* Ensure that the __pycache__ directory exists. */
1152 dirpath = rightmost_sep(cpathname);
1153 if (dirpath == NULL) {
1154 if (Py_VerboseFlag)
1155 PySys_WriteStderr(
1156 "# no %s path found %s\n",
1157 CACHEDIR, cpathname);
1158 return;
1159 }
1160 saved = *dirpath;
1161 *dirpath = '\0';
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001162
1163#ifdef MS_WINDOWS
1164 if (_mkdir(cpathname) < 0 && errno != EEXIST) {
1165#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (mkdir(cpathname, dirmode) < 0 && errno != EEXIST) {
Daniel Stutzbachc7937792010-09-09 21:18:04 +00001167#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 *dirpath = saved;
1169 if (Py_VerboseFlag)
1170 PySys_WriteStderr(
1171 "# cannot create cache dir %s\n", cpathname);
1172 return;
1173 }
1174 *dirpath = saved;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 fp = open_exclusive(cpathname, mode);
1177 if (fp == NULL) {
1178 if (Py_VerboseFlag)
1179 PySys_WriteStderr(
1180 "# can't create %s\n", cpathname);
1181 return;
1182 }
1183 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
1184 /* First write a 0 for mtime */
1185 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
1186 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
1187 if (fflush(fp) != 0 || ferror(fp)) {
1188 if (Py_VerboseFlag)
1189 PySys_WriteStderr("# can't write %s\n", cpathname);
1190 /* Don't keep partial file */
1191 fclose(fp);
1192 (void) unlink(cpathname);
1193 return;
1194 }
1195 /* Now write the true mtime */
1196 fseek(fp, 4L, 0);
1197 assert(mtime < LONG_MAX);
1198 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
1199 fflush(fp);
1200 fclose(fp);
1201 if (Py_VerboseFlag)
1202 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001203}
1204
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001205static void
1206update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *constants, *tmp;
1209 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (PyUnicode_Compare(co->co_filename, oldname))
1212 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 tmp = co->co_filename;
1215 co->co_filename = newname;
1216 Py_INCREF(co->co_filename);
1217 Py_DECREF(tmp);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 constants = co->co_consts;
1220 n = PyTuple_GET_SIZE(constants);
1221 for (i = 0; i < n; i++) {
1222 tmp = PyTuple_GET_ITEM(constants, i);
1223 if (PyCode_Check(tmp))
1224 update_code_filenames((PyCodeObject *)tmp,
1225 oldname, newname);
1226 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001227}
1228
1229static int
1230update_compiled_module(PyCodeObject *co, char *pathname)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyObject *oldname, *newname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 newname = PyUnicode_DecodeFSDefault(pathname);
1235 if (newname == NULL)
1236 return -1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (!PyUnicode_Compare(co->co_filename, newname)) {
1239 Py_DECREF(newname);
1240 return 0;
1241 }
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 oldname = co->co_filename;
1244 Py_INCREF(oldname);
1245 update_code_filenames(co, oldname, newname);
1246 Py_DECREF(oldname);
1247 Py_DECREF(newname);
1248 return 1;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001249}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001250
1251/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001252 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
1253 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001254
Guido van Rossum79f25d91997-04-29 20:08:16 +00001255static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001256load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 struct stat st;
1259 FILE *fpc;
1260 char buf[MAXPATHLEN+1];
1261 char *cpathname;
1262 PyCodeObject *co;
1263 PyObject *m;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (fstat(fileno(fp), &st) != 0) {
1266 PyErr_Format(PyExc_RuntimeError,
1267 "unable to get file status from '%s'",
1268 pathname);
1269 return NULL;
1270 }
Fred Drake4c82b232000-06-30 16:18:57 +00001271#if SIZEOF_TIME_T > 4
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* Python's .pyc timestamp handling presumes that the timestamp fits
1273 in 4 bytes. This will be fine until sometime in the year 2038,
1274 when a 4-byte signed time_t will overflow.
1275 */
1276 if (st.st_mtime >> 32) {
1277 PyErr_SetString(PyExc_OverflowError,
1278 "modification time overflows a 4 byte field");
1279 return NULL;
1280 }
Fred Drake4c82b232000-06-30 16:18:57 +00001281#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 cpathname = make_compiled_pathname(
1283 pathname, buf, (size_t)MAXPATHLEN + 1, !Py_OptimizeFlag);
1284 if (cpathname != NULL &&
1285 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
1286 co = read_compiled_module(cpathname, fpc);
1287 fclose(fpc);
1288 if (co == NULL)
1289 return NULL;
1290 if (update_compiled_module(co, pathname) < 0)
1291 return NULL;
1292 if (Py_VerboseFlag)
1293 PySys_WriteStderr("import %s # precompiled from %s\n",
1294 name, cpathname);
1295 pathname = cpathname;
1296 }
1297 else {
1298 co = parse_source_module(pathname, fp);
1299 if (co == NULL)
1300 return NULL;
1301 if (Py_VerboseFlag)
1302 PySys_WriteStderr("import %s # from %s\n",
1303 name, pathname);
1304 if (cpathname) {
1305 PyObject *ro = PySys_GetObject("dont_write_bytecode");
1306 if (ro == NULL || !PyObject_IsTrue(ro))
1307 write_compiled_module(co, cpathname, &st);
1308 }
1309 }
1310 m = PyImport_ExecCodeModuleWithPathnames(
1311 name, (PyObject *)co, pathname, cpathname);
1312 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001315}
1316
Christian Heimes3b06e532008-01-07 20:12:44 +00001317/* Get source file -> unicode or None
1318 * Returns the path to the py file if available, else the given path
1319 */
1320static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00001321get_sourcefile(char *file)
Christian Heimes3b06e532008-01-07 20:12:44 +00001322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 char py[MAXPATHLEN + 1];
1324 Py_ssize_t len;
1325 PyObject *u;
1326 struct stat statbuf;
Christian Heimes3b06e532008-01-07 20:12:44 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (!file || !*file) {
1329 Py_RETURN_NONE;
1330 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 len = strlen(file);
1333 /* match '*.py?' */
1334 if (len > MAXPATHLEN || PyOS_strnicmp(&file[len-4], ".py", 3) != 0) {
1335 return PyUnicode_DecodeFSDefault(file);
1336 }
Christian Heimes3b06e532008-01-07 20:12:44 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 /* Start by trying to turn PEP 3147 path into source path. If that
1339 * fails, just chop off the trailing character, i.e. legacy pyc path
1340 * to py.
1341 */
1342 if (make_source_pathname(file, py) == NULL) {
1343 strncpy(py, file, len-1);
1344 py[len-1] = '\0';
1345 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (stat(py, &statbuf) == 0 &&
1348 S_ISREG(statbuf.st_mode)) {
1349 u = PyUnicode_DecodeFSDefault(py);
1350 }
1351 else {
1352 u = PyUnicode_DecodeFSDefault(file);
1353 }
1354 return u;
Christian Heimes3b06e532008-01-07 20:12:44 +00001355}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001356
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001357/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001358static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
1359static struct filedescr *find_module(char *, char *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 char *, size_t, FILE **, PyObject **);
Christian Heimes3b06e532008-01-07 20:12:44 +00001361static struct _frozen * find_frozen(char *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001362
1363/* Load a package and return its module object WITH INCREMENTED
1364 REFERENCE COUNT */
1365
1366static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001367load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject *m, *d;
1370 PyObject *file = NULL;
1371 PyObject *path = NULL;
1372 int err;
1373 char buf[MAXPATHLEN+1];
1374 FILE *fp = NULL;
1375 struct filedescr *fdp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 m = PyImport_AddModule(name);
1378 if (m == NULL)
1379 return NULL;
1380 if (Py_VerboseFlag)
1381 PySys_WriteStderr("import %s # directory %s\n",
1382 name, pathname);
1383 d = PyModule_GetDict(m);
1384 file = get_sourcefile(pathname);
1385 if (file == NULL)
1386 goto error;
1387 path = Py_BuildValue("[O]", file);
1388 if (path == NULL)
1389 goto error;
1390 err = PyDict_SetItemString(d, "__file__", file);
1391 if (err == 0)
1392 err = PyDict_SetItemString(d, "__path__", path);
1393 if (err != 0)
1394 goto error;
1395 buf[0] = '\0';
1396 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1397 if (fdp == NULL) {
1398 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1399 PyErr_Clear();
1400 Py_INCREF(m);
1401 }
1402 else
1403 m = NULL;
1404 goto cleanup;
1405 }
1406 m = load_module(name, fp, buf, fdp->type, NULL);
1407 if (fp != NULL)
1408 fclose(fp);
1409 goto cleanup;
Tim Peters1cd70172004-08-02 03:52:12 +00001410
1411 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001413 cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 Py_XDECREF(path);
1415 Py_XDECREF(file);
1416 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001417}
1418
1419
1420/* Helper to test for built-in module */
1421
1422static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001423is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 int i;
1426 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1427 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1428 if (PyImport_Inittab[i].initfunc == NULL)
1429 return -1;
1430 else
1431 return 1;
1432 }
1433 }
1434 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001435}
1436
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001437
Just van Rossum52e14d62002-12-30 22:08:05 +00001438/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1439 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001440 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001441 that can handle the path item. Return None if no hook could;
1442 this tells our caller it should fall back to the builtin
1443 import mechanism. Cache the result in path_importer_cache.
1444 Returns a borrowed reference. */
1445
1446static PyObject *
1447get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyObject *importer;
1451 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* These conditions are the caller's responsibility: */
1454 assert(PyList_Check(path_hooks));
1455 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 nhooks = PyList_Size(path_hooks);
1458 if (nhooks < 0)
1459 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 importer = PyDict_GetItem(path_importer_cache, p);
1462 if (importer != NULL)
1463 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 /* set path_importer_cache[p] to None to avoid recursion */
1466 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1467 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 for (j = 0; j < nhooks; j++) {
1470 PyObject *hook = PyList_GetItem(path_hooks, j);
1471 if (hook == NULL)
1472 return NULL;
1473 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1474 if (importer != NULL)
1475 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1478 return NULL;
1479 }
1480 PyErr_Clear();
1481 }
1482 if (importer == NULL) {
1483 importer = PyObject_CallFunctionObjArgs(
1484 (PyObject *)&PyNullImporter_Type, p, NULL
1485 );
1486 if (importer == NULL) {
1487 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1488 PyErr_Clear();
1489 return Py_None;
1490 }
1491 }
1492 }
1493 if (importer != NULL) {
1494 int err = PyDict_SetItem(path_importer_cache, p, importer);
1495 Py_DECREF(importer);
1496 if (err != 0)
1497 return NULL;
1498 }
1499 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001500}
1501
Christian Heimes9cd17752007-11-18 19:35:23 +00001502PyAPI_FUNC(PyObject *)
1503PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1507 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1508 importer = get_path_importer(path_importer_cache,
1509 path_hooks, path);
1510 }
1511 }
1512 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1513 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001514}
1515
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001516/* Search the path (default sys.path) for a module. Return the
1517 corresponding filedescr struct, and (via return arguments) the
1518 pathname and an open file. Return NULL if the module is not found. */
1519
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001520#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001521extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001523#endif
1524
Martin v. Löwis18e16552006-02-15 17:27:45 +00001525static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001526static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001527static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001528
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001529static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001530find_module(char *fullname, char *subname, PyObject *path, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 Py_ssize_t i, npath;
1534 size_t len, namelen;
1535 struct filedescr *fdp = NULL;
1536 char *filemode;
1537 FILE *fp = NULL;
1538 PyObject *path_hooks, *path_importer_cache;
1539 struct stat statbuf;
1540 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1541 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1542 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1543 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001544#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 size_t saved_len;
1546 size_t saved_namelen;
1547 char *saved_buf = NULL;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001548#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (p_loader != NULL)
1550 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 if (strlen(subname) > MAXPATHLEN) {
1553 PyErr_SetString(PyExc_OverflowError,
1554 "module name is too long");
1555 return NULL;
1556 }
1557 strcpy(name, subname);
Just van Rossum52e14d62002-12-30 22:08:05 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 /* sys.meta_path import hook */
1560 if (p_loader != NULL) {
1561 PyObject *meta_path;
Just van Rossum52e14d62002-12-30 22:08:05 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 meta_path = PySys_GetObject("meta_path");
1564 if (meta_path == NULL || !PyList_Check(meta_path)) {
1565 PyErr_SetString(PyExc_ImportError,
1566 "sys.meta_path must be a list of "
1567 "import hooks");
1568 return NULL;
1569 }
1570 Py_INCREF(meta_path); /* zap guard */
1571 npath = PyList_Size(meta_path);
1572 for (i = 0; i < npath; i++) {
1573 PyObject *loader;
1574 PyObject *hook = PyList_GetItem(meta_path, i);
1575 loader = PyObject_CallMethod(hook, "find_module",
1576 "sO", fullname,
1577 path != NULL ?
1578 path : Py_None);
1579 if (loader == NULL) {
1580 Py_DECREF(meta_path);
1581 return NULL; /* true error */
1582 }
1583 if (loader != Py_None) {
1584 /* a loader was found */
1585 *p_loader = loader;
1586 Py_DECREF(meta_path);
1587 return &importhookdescr;
1588 }
1589 Py_DECREF(loader);
1590 }
1591 Py_DECREF(meta_path);
1592 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 if (find_frozen(fullname) != NULL) {
1595 strcpy(buf, fullname);
1596 return &fd_frozen;
1597 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 if (path == NULL) {
1600 if (is_builtin(name)) {
1601 strcpy(buf, name);
1602 return &fd_builtin;
1603 }
Guido van Rossumac279101996-08-22 23:10:58 +00001604#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1606 if (fp != NULL) {
1607 *p_fp = fp;
1608 return fdp;
1609 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001610#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 path = PySys_GetObject("path");
1612 }
Benjamin Petersond968e272008-11-05 22:48:33 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (path == NULL || !PyList_Check(path)) {
1615 PyErr_SetString(PyExc_ImportError,
1616 "sys.path must be a list of directory names");
1617 return NULL;
1618 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 path_hooks = PySys_GetObject("path_hooks");
1621 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1622 PyErr_SetString(PyExc_ImportError,
1623 "sys.path_hooks must be a list of "
1624 "import hooks");
1625 return NULL;
1626 }
1627 path_importer_cache = PySys_GetObject("path_importer_cache");
1628 if (path_importer_cache == NULL ||
1629 !PyDict_Check(path_importer_cache)) {
1630 PyErr_SetString(PyExc_ImportError,
1631 "sys.path_importer_cache must be a dict");
1632 return NULL;
1633 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 npath = PyList_Size(path);
1636 namelen = strlen(name);
1637 for (i = 0; i < npath; i++) {
1638 PyObject *v = PyList_GetItem(path, i);
1639 PyObject *origv = v;
1640 const char *base;
1641 Py_ssize_t size;
1642 if (!v)
1643 return NULL;
1644 if (PyUnicode_Check(v)) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00001645 v = PyUnicode_EncodeFSDefault(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (v == NULL)
1647 return NULL;
1648 }
1649 else if (!PyBytes_Check(v))
1650 continue;
1651 else
1652 Py_INCREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 base = PyBytes_AS_STRING(v);
1655 size = PyBytes_GET_SIZE(v);
1656 len = size;
1657 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1658 Py_DECREF(v);
1659 continue; /* Too long */
1660 }
1661 strcpy(buf, base);
1662 Py_DECREF(v);
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (strlen(buf) != len) {
1665 continue; /* v contains '\0' */
1666 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 /* sys.path_hooks import hook */
1669 if (p_loader != NULL) {
1670 PyObject *importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 importer = get_path_importer(path_importer_cache,
1673 path_hooks, origv);
1674 if (importer == NULL) {
1675 return NULL;
1676 }
1677 /* Note: importer is a borrowed reference */
1678 if (importer != Py_None) {
1679 PyObject *loader;
1680 loader = PyObject_CallMethod(importer,
1681 "find_module",
1682 "s", fullname);
1683 if (loader == NULL)
1684 return NULL; /* error */
1685 if (loader != Py_None) {
1686 /* a loader was found */
1687 *p_loader = loader;
1688 return &importhookdescr;
1689 }
1690 Py_DECREF(loader);
1691 continue;
1692 }
1693 }
1694 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 if (len > 0 && buf[len-1] != SEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001697#ifdef ALTSEP
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 && buf[len-1] != ALTSEP
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001699#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 )
1701 buf[len++] = SEP;
1702 strcpy(buf+len, name);
1703 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 /* Check for package import (buf holds a directory name,
1706 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001707#ifdef HAVE_STAT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (stat(buf, &statbuf) == 0 && /* it exists */
1709 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1710 case_ok(buf, len, namelen, name)) { /* case matches */
1711 if (find_init_module(buf)) { /* and has __init__.py */
1712 return &fd_package;
1713 }
1714 else {
1715 char warnstr[MAXPATHLEN+80];
1716 sprintf(warnstr, "Not importing directory "
1717 "'%.*s': missing __init__.py",
1718 MAXPATHLEN, buf);
1719 if (PyErr_WarnEx(PyExc_ImportWarning,
1720 warnstr, 1)) {
1721 return NULL;
1722 }
1723 }
1724 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001725#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001726#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* take a snapshot of the module spec for restoration
1728 * after the 8 character DLL hackery
1729 */
1730 saved_buf = strdup(buf);
1731 saved_len = len;
1732 saved_namelen = namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001733#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001735#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* OS/2 limits DLLs to 8 character names (w/o
1737 extension)
1738 * so if the name is longer than that and its a
1739 * dynamically loaded module we're going to try,
1740 * truncate the name before trying
1741 */
1742 if (strlen(subname) > 8) {
1743 /* is this an attempt to load a C extension? */
1744 const struct filedescr *scan;
1745 scan = _PyImport_DynLoadFiletab;
1746 while (scan->suffix != NULL) {
1747 if (!strcmp(scan->suffix, fdp->suffix))
1748 break;
1749 else
1750 scan++;
1751 }
1752 if (scan->suffix != NULL) {
1753 /* yes, so truncate the name */
1754 namelen = 8;
1755 len -= strlen(subname) - namelen;
1756 buf[len] = '\0';
1757 }
1758 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001759#endif /* PYOS_OS2 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 strcpy(buf+len, fdp->suffix);
1761 if (Py_VerboseFlag > 1)
1762 PySys_WriteStderr("# trying %s\n", buf);
1763 filemode = fdp->mode;
1764 if (filemode[0] == 'U')
1765 filemode = "r" PY_STDIOTEXTMODE;
1766 fp = fopen(buf, filemode);
1767 if (fp != NULL) {
1768 if (case_ok(buf, len, namelen, name))
1769 break;
1770 else { /* continue search */
1771 fclose(fp);
1772 fp = NULL;
1773 }
1774 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001775#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* restore the saved snapshot */
1777 strcpy(buf, saved_buf);
1778 len = saved_len;
1779 namelen = saved_namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001780#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001782#if defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* don't need/want the module name snapshot anymore */
1784 if (saved_buf)
1785 {
1786 free(saved_buf);
1787 saved_buf = NULL;
1788 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001789#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (fp != NULL)
1791 break;
1792 }
1793 if (fp == NULL) {
1794 PyErr_Format(PyExc_ImportError,
1795 "No module named %.200s", name);
1796 return NULL;
1797 }
1798 *p_fp = fp;
1799 return fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001800}
1801
Martin v. Löwis18e16552006-02-15 17:27:45 +00001802/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001803 * The arguments here are tricky, best shown by example:
1804 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1805 * ^ ^ ^ ^
1806 * |--------------------- buf ---------------------|
1807 * |------------------- len ------------------|
1808 * |------ name -------|
1809 * |----- namelen -----|
1810 * buf is the full path, but len only counts up to (& exclusive of) the
1811 * extension. name is the module name, also exclusive of extension.
1812 *
1813 * We've already done a successful stat() or fopen() on buf, so know that
1814 * there's some match, possibly case-insensitive.
1815 *
Tim Peters50d8d372001-02-28 05:34:27 +00001816 * case_ok() is to return 1 if there's a case-sensitive match for
1817 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1818 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001819 *
Tim Peters50d8d372001-02-28 05:34:27 +00001820 * case_ok() is used to implement case-sensitive import semantics even
1821 * on platforms with case-insensitive filesystems. It's trivial to implement
1822 * for case-sensitive filesystems. It's pretty much a cross-platform
1823 * nightmare for systems with case-insensitive filesystems.
1824 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001825
Tim Peters50d8d372001-02-28 05:34:27 +00001826/* First we may need a pile of platform-specific header files; the sequence
1827 * of #if's here should match the sequence in the body of case_ok().
1828 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001829#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001830#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001831
Tim Peters50d8d372001-02-28 05:34:27 +00001832#elif defined(DJGPP)
1833#include <dir.h>
1834
Jason Tishler7961aa62005-05-20 00:56:54 +00001835#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001836#include <sys/types.h>
1837#include <dirent.h>
1838
Andrew MacIntyred9400542002-02-26 11:41:34 +00001839#elif defined(PYOS_OS2)
1840#define INCL_DOS
1841#define INCL_DOSERRORS
1842#define INCL_NOPMAPI
1843#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001844#endif
1845
Guido van Rossum0980bd91998-02-13 17:18:36 +00001846static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001847case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001848{
Tim Peters50d8d372001-02-28 05:34:27 +00001849/* Pick a platform-specific implementation; the sequence of #if's here should
1850 * match the sequence just above.
1851 */
1852
Jason Tishler7961aa62005-05-20 00:56:54 +00001853/* MS_WINDOWS */
1854#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 WIN32_FIND_DATA data;
1856 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (Py_GETENV("PYTHONCASEOK") != NULL)
1859 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 h = FindFirstFile(buf, &data);
1862 if (h == INVALID_HANDLE_VALUE) {
1863 PyErr_Format(PyExc_NameError,
1864 "Can't find file for module %.100s\n(filename %.300s)",
1865 name, buf);
1866 return 0;
1867 }
1868 FindClose(h);
1869 return strncmp(data.cFileName, name, namelen) == 0;
Tim Peters50d8d372001-02-28 05:34:27 +00001870
1871/* DJGPP */
1872#elif defined(DJGPP)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 struct ffblk ffblk;
1874 int done;
Tim Peters50d8d372001-02-28 05:34:27 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (Py_GETENV("PYTHONCASEOK") != NULL)
1877 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1880 if (done) {
1881 PyErr_Format(PyExc_NameError,
1882 "Can't find file for module %.100s\n(filename %.300s)",
1883 name, buf);
1884 return 0;
1885 }
1886 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001887
Jason Tishler7961aa62005-05-20 00:56:54 +00001888/* new-fangled macintosh (macosx) or Cygwin */
1889#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 DIR *dirp;
1891 struct dirent *dp;
1892 char dirname[MAXPATHLEN + 1];
1893 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 if (Py_GETENV("PYTHONCASEOK") != NULL)
1896 return 1;
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 /* Copy the dir component into dirname; substitute "." if empty */
1899 if (dirlen <= 0) {
1900 dirname[0] = '.';
1901 dirname[1] = '\0';
1902 }
1903 else {
1904 assert(dirlen <= MAXPATHLEN);
1905 memcpy(dirname, buf, dirlen);
1906 dirname[dirlen] = '\0';
1907 }
1908 /* Open the directory and search the entries for an exact match. */
1909 dirp = opendir(dirname);
1910 if (dirp) {
1911 char *nameWithExt = buf + len - namelen;
1912 while ((dp = readdir(dirp)) != NULL) {
1913 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001914#ifdef _DIRENT_HAVE_D_NAMELEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001916#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001918#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (thislen >= namelen &&
1920 strcmp(dp->d_name, nameWithExt) == 0) {
1921 (void)closedir(dirp);
1922 return 1; /* Found */
1923 }
1924 }
1925 (void)closedir(dirp);
1926 }
1927 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001928
Andrew MacIntyred9400542002-02-26 11:41:34 +00001929/* OS/2 */
1930#elif defined(PYOS_OS2)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 HDIR hdir = 1;
1932 ULONG srchcnt = 1;
1933 FILEFINDBUF3 ffbuf;
1934 APIRET rc;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (Py_GETENV("PYTHONCASEOK") != NULL)
1937 return 1;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 rc = DosFindFirst(buf,
1940 &hdir,
1941 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1942 &ffbuf, sizeof(ffbuf),
1943 &srchcnt,
1944 FIL_STANDARD);
1945 if (rc != NO_ERROR)
1946 return 0;
1947 return strncmp(ffbuf.achName, name, namelen) == 0;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001948
Tim Peters50d8d372001-02-28 05:34:27 +00001949/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1950#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001952
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001953#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001954}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001955
Guido van Rossum197346f1997-10-31 18:38:52 +00001956#ifdef HAVE_STAT
Victor Stinner4f4402c2010-08-14 14:50:26 +00001957
Guido van Rossum197346f1997-10-31 18:38:52 +00001958/* Helper to look for __init__.py or __init__.py[co] in potential package */
1959static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001960find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 const size_t save_len = strlen(buf);
1963 size_t i = save_len;
1964 char *pname; /* pointer to start of __init__ */
1965 struct stat statbuf;
Guido van Rossum197346f1997-10-31 18:38:52 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967/* For calling case_ok(buf, len, namelen, name):
1968 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1969 * ^ ^ ^ ^
1970 * |--------------------- buf ---------------------|
1971 * |------------------- len ------------------|
1972 * |------ name -------|
1973 * |----- namelen -----|
Tim Peters0f9431f2001-07-05 03:47:53 +00001974 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (save_len + 13 >= MAXPATHLEN)
1976 return 0;
1977 buf[i++] = SEP;
1978 pname = buf + i;
1979 strcpy(pname, "__init__.py");
1980 if (stat(buf, &statbuf) == 0) {
1981 if (case_ok(buf,
1982 save_len + 9, /* len("/__init__") */
1983 8, /* len("__init__") */
1984 pname)) {
1985 buf[save_len] = '\0';
1986 return 1;
1987 }
1988 }
1989 i += strlen(pname);
1990 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1991 if (stat(buf, &statbuf) == 0) {
1992 if (case_ok(buf,
1993 save_len + 9, /* len("/__init__") */
1994 8, /* len("__init__") */
1995 pname)) {
1996 buf[save_len] = '\0';
1997 return 1;
1998 }
1999 }
2000 buf[save_len] = '\0';
2001 return 0;
Guido van Rossum197346f1997-10-31 18:38:52 +00002002}
Guido van Rossum48a680c2001-03-02 06:34:14 +00002003
Guido van Rossum197346f1997-10-31 18:38:52 +00002004#endif /* HAVE_STAT */
2005
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002006
Tim Petersdbd9ba62000-07-09 03:09:57 +00002007static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002008
Victor Stinner44c6c152010-08-09 00:59:10 +00002009static PyObject*
2010load_builtin(char *name, char *pathname, int type)
2011{
2012 PyObject *m, *modules;
2013 int err;
2014
2015 if (pathname != NULL && pathname[0] != '\0')
2016 name = pathname;
2017
2018 if (type == C_BUILTIN)
2019 err = init_builtin(name);
2020 else
2021 err = PyImport_ImportFrozenModule(name);
2022 if (err < 0)
2023 return NULL;
2024 if (err == 0) {
2025 PyErr_Format(PyExc_ImportError,
2026 "Purported %s module %.200s not found",
2027 type == C_BUILTIN ?
2028 "builtin" : "frozen",
2029 name);
2030 return NULL;
2031 }
2032
2033 modules = PyImport_GetModuleDict();
2034 m = PyDict_GetItemString(modules, name);
2035 if (m == NULL) {
2036 PyErr_Format(
2037 PyExc_ImportError,
2038 "%s module %.200s not properly initialized",
2039 type == C_BUILTIN ?
2040 "builtin" : "frozen",
2041 name);
2042 return NULL;
2043 }
2044 Py_INCREF(m);
2045 return m;
2046}
2047
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002048/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002049 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002050
Guido van Rossum79f25d91997-04-29 20:08:16 +00002051static PyObject *
Alexandre Vassalottie223eb82009-07-29 20:12:15 +00002052load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* First check that there's an open file (if we need one) */
2057 switch (type) {
2058 case PY_SOURCE:
2059 case PY_COMPILED:
2060 if (fp == NULL) {
2061 PyErr_Format(PyExc_ValueError,
2062 "file object required for import (type code %d)",
2063 type);
2064 return NULL;
2065 }
2066 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 case PY_SOURCE:
2071 m = load_source_module(name, pathname, fp);
2072 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 case PY_COMPILED:
2075 m = load_compiled_module(name, pathname, fp);
2076 break;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002077
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002078#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 case C_EXTENSION:
2080 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2081 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002082#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 case PKG_DIRECTORY:
2085 m = load_package(name, pathname);
2086 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 case C_BUILTIN:
2089 case PY_FROZEN:
Victor Stinner44c6c152010-08-09 00:59:10 +00002090 m = load_builtin(name, pathname, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 break;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 case IMP_HOOK: {
2094 if (loader == NULL) {
2095 PyErr_SetString(PyExc_ImportError,
2096 "import hook without loader");
2097 return NULL;
2098 }
2099 m = PyObject_CallMethod(loader, "load_module", "s", name);
2100 break;
2101 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 default:
2104 PyErr_Format(PyExc_ImportError,
2105 "Don't know how to import %.200s (type code %d)",
2106 name, type);
2107 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002112}
2113
2114
2115/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00002116 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002117 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002118
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002119static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002120init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (_PyImport_FindExtension(name, name) != NULL)
2125 return 1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 for (p = PyImport_Inittab; p->name != NULL; p++) {
2128 PyObject *mod;
2129 if (strcmp(name, p->name) == 0) {
2130 if (p->initfunc == NULL) {
2131 PyErr_Format(PyExc_ImportError,
2132 "Cannot re-init internal module %.200s",
2133 name);
2134 return -1;
2135 }
2136 if (Py_VerboseFlag)
2137 PySys_WriteStderr("import %s # builtin\n", name);
2138 mod = (*p->initfunc)();
2139 if (mod == 0)
2140 return -1;
2141 if (_PyImport_FixupExtension(mod, name, name) < 0)
2142 return -1;
2143 /* FixupExtension has put the module into sys.modules,
2144 so we can release our own reference. */
2145 Py_DECREF(mod);
2146 return 1;
2147 }
2148 }
2149 return 0;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00002150}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002151
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002152
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002153/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002154
Guido van Rossumcfd0a221996-06-17 17:06:34 +00002155static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002156find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (!name)
2161 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 for (p = PyImport_FrozenModules; ; p++) {
2164 if (p->name == NULL)
2165 return NULL;
2166 if (strcmp(p->name, name) == 0)
2167 break;
2168 }
2169 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002170}
2171
Guido van Rossum79f25d91997-04-29 20:08:16 +00002172static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002173get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 struct _frozen *p = find_frozen(name);
2176 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (p == NULL) {
2179 PyErr_Format(PyExc_ImportError,
2180 "No such frozen object named %.200s",
2181 name);
2182 return NULL;
2183 }
2184 if (p->code == NULL) {
2185 PyErr_Format(PyExc_ImportError,
2186 "Excluded frozen object named %.200s",
2187 name);
2188 return NULL;
2189 }
2190 size = p->size;
2191 if (size < 0)
2192 size = -size;
2193 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002194}
2195
Brett Cannon8d110132009-03-15 02:20:16 +00002196static PyObject *
2197is_frozen_package(char *name)
2198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 struct _frozen *p = find_frozen(name);
2200 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (p == NULL) {
2203 PyErr_Format(PyExc_ImportError,
2204 "No such frozen object named %.200s",
2205 name);
2206 return NULL;
2207 }
Brett Cannon8d110132009-03-15 02:20:16 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (size < 0)
2212 Py_RETURN_TRUE;
2213 else
2214 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00002215}
2216
2217
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002218/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00002219 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002220 an exception set if the initialization failed.
2221 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00002222
2223int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002224PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 struct _frozen *p = find_frozen(name);
2227 PyObject *co;
2228 PyObject *m;
2229 int ispackage;
2230 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (p == NULL)
2233 return 0;
2234 if (p->code == NULL) {
2235 PyErr_Format(PyExc_ImportError,
2236 "Excluded frozen object named %.200s",
2237 name);
2238 return -1;
2239 }
2240 size = p->size;
2241 ispackage = (size < 0);
2242 if (ispackage)
2243 size = -size;
2244 if (Py_VerboseFlag)
2245 PySys_WriteStderr("import %s # frozen%s\n",
2246 name, ispackage ? " package" : "");
2247 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
2248 if (co == NULL)
2249 return -1;
2250 if (!PyCode_Check(co)) {
2251 PyErr_Format(PyExc_TypeError,
2252 "frozen object %.200s is not a code object",
2253 name);
2254 goto err_return;
2255 }
2256 if (ispackage) {
2257 /* Set __path__ to the package name */
2258 PyObject *d, *s, *l;
2259 int err;
2260 m = PyImport_AddModule(name);
2261 if (m == NULL)
2262 goto err_return;
2263 d = PyModule_GetDict(m);
2264 s = PyUnicode_InternFromString(name);
2265 if (s == NULL)
2266 goto err_return;
2267 l = PyList_New(1);
2268 if (l == NULL) {
2269 Py_DECREF(s);
2270 goto err_return;
2271 }
2272 PyList_SET_ITEM(l, 0, s);
2273 err = PyDict_SetItemString(d, "__path__", l);
2274 Py_DECREF(l);
2275 if (err != 0)
2276 goto err_return;
2277 }
2278 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
2279 if (m == NULL)
2280 goto err_return;
2281 Py_DECREF(co);
2282 Py_DECREF(m);
2283 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002284err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 Py_DECREF(co);
2286 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00002287}
Guido van Rossum74e6a111994-08-29 12:54:38 +00002288
2289
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002290/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002291 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00002292
Guido van Rossum79f25d91997-04-29 20:08:16 +00002293PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00002294PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00002295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 PyObject *pname;
2297 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 pname = PyUnicode_FromString(name);
2300 if (pname == NULL)
2301 return NULL;
2302 result = PyImport_Import(pname);
2303 Py_DECREF(pname);
2304 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002305}
2306
Christian Heimes072c0f12008-01-03 23:01:04 +00002307/* Import a module without blocking
2308 *
2309 * At first it tries to fetch the module from sys.modules. If the module was
2310 * never loaded before it loads it with PyImport_ImportModule() unless another
2311 * thread holds the import lock. In the latter case the function raises an
2312 * ImportError instead of blocking.
2313 *
2314 * Returns the module object with incremented ref count.
2315 */
2316PyObject *
2317PyImport_ImportModuleNoBlock(const char *name)
2318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyObject *result;
2320 PyObject *modules;
2321 long me;
Christian Heimes072c0f12008-01-03 23:01:04 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* Try to get the module from sys.modules[name] */
2324 modules = PyImport_GetModuleDict();
2325 if (modules == NULL)
2326 return NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 result = PyDict_GetItemString(modules, name);
2329 if (result != NULL) {
2330 Py_INCREF(result);
2331 return result;
2332 }
2333 else {
2334 PyErr_Clear();
2335 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002336#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* check the import lock
2338 * me might be -1 but I ignore the error here, the lock function
2339 * takes care of the problem */
2340 me = PyThread_get_thread_ident();
2341 if (import_lock_thread == -1 || import_lock_thread == me) {
2342 /* no thread or me is holding the lock */
2343 return PyImport_ImportModule(name);
2344 }
2345 else {
2346 PyErr_Format(PyExc_ImportError,
2347 "Failed to import %.200s because the import lock"
2348 "is held by another thread.",
2349 name);
2350 return NULL;
2351 }
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002352#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return PyImport_ImportModule(name);
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002354#endif
Christian Heimes072c0f12008-01-03 23:01:04 +00002355}
2356
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002357/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002358static PyObject *get_parent(PyObject *globals, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002360static PyObject *load_next(PyObject *mod, PyObject *altmod,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002362static int mark_miss(char *name);
2363static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002365static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002366
2367/* The Magnum Opus of dotted-name import :-) */
2368
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002369static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002370import_module_level(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 char buf[MAXPATHLEN+1];
2374 Py_ssize_t buflen = 0;
2375 PyObject *parent, *head, *next, *tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (strchr(name, '/') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002378#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 || strchr(name, '\\') != NULL
Christian Heimes454f37b2008-01-10 00:10:02 +00002380#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 ) {
2382 PyErr_SetString(PyExc_ImportError,
2383 "Import by filename is not supported.");
2384 return NULL;
2385 }
Christian Heimes454f37b2008-01-10 00:10:02 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 parent = get_parent(globals, buf, &buflen, level);
2388 if (parent == NULL)
2389 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002390
Benjamin Peterson556d8002010-06-27 22:37:28 +00002391 head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
2392 &buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 if (head == NULL)
2394 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 tail = head;
2397 Py_INCREF(tail);
2398 while (name) {
2399 next = load_next(tail, tail, &name, buf, &buflen);
2400 Py_DECREF(tail);
2401 if (next == NULL) {
2402 Py_DECREF(head);
2403 return NULL;
2404 }
2405 tail = next;
2406 }
2407 if (tail == Py_None) {
2408 /* If tail is Py_None, both get_parent and load_next found
2409 an empty module name: someone called __import__("") or
2410 doctored faulty bytecode */
2411 Py_DECREF(tail);
2412 Py_DECREF(head);
2413 PyErr_SetString(PyExc_ValueError,
2414 "Empty module name");
2415 return NULL;
2416 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (fromlist != NULL) {
2419 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2420 fromlist = NULL;
2421 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 if (fromlist == NULL) {
2424 Py_DECREF(tail);
2425 return head;
2426 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 Py_DECREF(head);
2429 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2430 Py_DECREF(tail);
2431 return NULL;
2432 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return tail;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002435}
2436
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002437PyObject *
2438PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 PyObject *fromlist, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 PyObject *result;
2442 _PyImport_AcquireLock();
2443 result = import_module_level(name, globals, locals, fromlist, level);
2444 if (_PyImport_ReleaseLock() < 0) {
2445 Py_XDECREF(result);
2446 PyErr_SetString(PyExc_RuntimeError,
2447 "not holding the import lock");
2448 return NULL;
2449 }
2450 return result;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002451}
2452
Fred Drake87590902004-05-28 20:21:36 +00002453/* Return the package that an import is being performed in. If globals comes
2454 from the module foo.bar.bat (not itself a package), this returns the
2455 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002456 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002457
2458 The *name* of the returned package is returned in buf, with the length of
2459 the name in *p_buflen.
2460
2461 If globals doesn't come from a package or a module in a package, or a
2462 corresponding entry is not found in sys.modules, Py_None is returned.
2463*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002464static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002465get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 static PyObject *namestr = NULL;
2468 static PyObject *pathstr = NULL;
2469 static PyObject *pkgstr = NULL;
2470 PyObject *pkgname, *modname, *modpath, *modules, *parent;
2471 int orig_level = level;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 if (globals == NULL || !PyDict_Check(globals) || !level)
2474 return Py_None;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 if (namestr == NULL) {
2477 namestr = PyUnicode_InternFromString("__name__");
2478 if (namestr == NULL)
2479 return NULL;
2480 }
2481 if (pathstr == NULL) {
2482 pathstr = PyUnicode_InternFromString("__path__");
2483 if (pathstr == NULL)
2484 return NULL;
2485 }
2486 if (pkgstr == NULL) {
2487 pkgstr = PyUnicode_InternFromString("__package__");
2488 if (pkgstr == NULL)
2489 return NULL;
2490 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 *buf = '\0';
2493 *p_buflen = 0;
2494 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if ((pkgname != NULL) && (pkgname != Py_None)) {
2497 /* __package__ is set, so use it */
2498 char *pkgname_str;
2499 Py_ssize_t len;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 if (!PyUnicode_Check(pkgname)) {
2502 PyErr_SetString(PyExc_ValueError,
2503 "__package__ set to non-string");
2504 return NULL;
2505 }
2506 pkgname_str = _PyUnicode_AsStringAndSize(pkgname, &len);
2507 if (len == 0) {
2508 if (level > 0) {
2509 PyErr_SetString(PyExc_ValueError,
2510 "Attempted relative import in non-package");
2511 return NULL;
2512 }
2513 return Py_None;
2514 }
2515 if (len > MAXPATHLEN) {
2516 PyErr_SetString(PyExc_ValueError,
2517 "Package name too long");
2518 return NULL;
2519 }
2520 strcpy(buf, pkgname_str);
2521 } else {
2522 /* __package__ not set, so figure it out and set it */
2523 modname = PyDict_GetItem(globals, namestr);
2524 if (modname == NULL || !PyUnicode_Check(modname))
2525 return Py_None;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 modpath = PyDict_GetItem(globals, pathstr);
2528 if (modpath != NULL) {
2529 /* __path__ is set, so modname is already the package name */
2530 char *modname_str;
2531 Py_ssize_t len;
2532 int error;
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 modname_str = _PyUnicode_AsStringAndSize(modname, &len);
2535 if (len > MAXPATHLEN) {
2536 PyErr_SetString(PyExc_ValueError,
2537 "Module name too long");
2538 return NULL;
2539 }
2540 strcpy(buf, modname_str);
2541 error = PyDict_SetItem(globals, pkgstr, modname);
2542 if (error) {
2543 PyErr_SetString(PyExc_ValueError,
2544 "Could not set __package__");
2545 return NULL;
2546 }
2547 } else {
2548 /* Normal module, so work out the package name if any */
2549 char *start = _PyUnicode_AsString(modname);
2550 char *lastdot = strrchr(start, '.');
2551 size_t len;
2552 int error;
2553 if (lastdot == NULL && level > 0) {
2554 PyErr_SetString(PyExc_ValueError,
2555 "Attempted relative import in non-package");
2556 return NULL;
2557 }
2558 if (lastdot == NULL) {
2559 error = PyDict_SetItem(globals, pkgstr, Py_None);
2560 if (error) {
2561 PyErr_SetString(PyExc_ValueError,
2562 "Could not set __package__");
2563 return NULL;
2564 }
2565 return Py_None;
2566 }
2567 len = lastdot - start;
2568 if (len >= MAXPATHLEN) {
2569 PyErr_SetString(PyExc_ValueError,
2570 "Module name too long");
2571 return NULL;
2572 }
2573 strncpy(buf, start, len);
2574 buf[len] = '\0';
2575 pkgname = PyUnicode_FromString(buf);
2576 if (pkgname == NULL) {
2577 return NULL;
2578 }
2579 error = PyDict_SetItem(globals, pkgstr, pkgname);
2580 Py_DECREF(pkgname);
2581 if (error) {
2582 PyErr_SetString(PyExc_ValueError,
2583 "Could not set __package__");
2584 return NULL;
2585 }
2586 }
2587 }
2588 while (--level > 0) {
2589 char *dot = strrchr(buf, '.');
2590 if (dot == NULL) {
2591 PyErr_SetString(PyExc_ValueError,
2592 "Attempted relative import beyond "
2593 "toplevel package");
2594 return NULL;
2595 }
2596 *dot = '\0';
2597 }
2598 *p_buflen = strlen(buf);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 modules = PyImport_GetModuleDict();
2601 parent = PyDict_GetItemString(modules, buf);
2602 if (parent == NULL) {
2603 if (orig_level < 1) {
2604 PyObject *err_msg = PyBytes_FromFormat(
2605 "Parent module '%.200s' not found "
2606 "while handling absolute import", buf);
2607 if (err_msg == NULL) {
2608 return NULL;
2609 }
2610 if (!PyErr_WarnEx(PyExc_RuntimeWarning,
2611 PyBytes_AsString(err_msg), 1)) {
2612 *buf = '\0';
2613 *p_buflen = 0;
2614 parent = Py_None;
2615 }
2616 Py_DECREF(err_msg);
2617 } else {
2618 PyErr_Format(PyExc_SystemError,
2619 "Parent module '%.200s' not loaded, "
2620 "cannot perform relative import", buf);
2621 }
2622 }
2623 return parent;
2624 /* We expect, but can't guarantee, if parent != None, that:
2625 - parent.__name__ == buf
2626 - parent.__dict__ is globals
2627 If this is violated... Who cares? */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002628}
2629
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002630/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002631static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002632load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 char *name = *p_name;
2636 char *dot = strchr(name, '.');
2637 size_t len;
2638 char *p;
2639 PyObject *result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 if (strlen(name) == 0) {
2642 /* completely empty module name should only happen in
2643 'from . import' (or '__import__("")')*/
2644 Py_INCREF(mod);
2645 *p_name = NULL;
2646 return mod;
2647 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (dot == NULL) {
2650 *p_name = NULL;
2651 len = strlen(name);
2652 }
2653 else {
2654 *p_name = dot+1;
2655 len = dot-name;
2656 }
2657 if (len == 0) {
2658 PyErr_SetString(PyExc_ValueError,
2659 "Empty module name");
2660 return NULL;
2661 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 p = buf + *p_buflen;
2664 if (p != buf)
2665 *p++ = '.';
2666 if (p+len-buf >= MAXPATHLEN) {
2667 PyErr_SetString(PyExc_ValueError,
2668 "Module name too long");
2669 return NULL;
2670 }
2671 strncpy(p, name, len);
2672 p[len] = '\0';
2673 *p_buflen = p+len-buf;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 result = import_submodule(mod, p, buf);
2676 if (result == Py_None && altmod != mod) {
2677 Py_DECREF(result);
2678 /* Here, altmod must be None and mod must not be None */
2679 result = import_submodule(altmod, p, p);
2680 if (result != NULL && result != Py_None) {
2681 if (mark_miss(buf) != 0) {
2682 Py_DECREF(result);
2683 return NULL;
2684 }
2685 strncpy(buf, name, len);
2686 buf[len] = '\0';
2687 *p_buflen = len;
2688 }
2689 }
2690 if (result == NULL)
2691 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 if (result == Py_None) {
2694 Py_DECREF(result);
2695 PyErr_Format(PyExc_ImportError,
2696 "No module named %.200s", name);
2697 return NULL;
2698 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 return result;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002701}
2702
2703static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002704mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 PyObject *modules = PyImport_GetModuleDict();
2707 return PyDict_SetItemString(modules, name, Py_None);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002708}
2709
2710static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002711ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 int i;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 if (!PyObject_HasAttrString(mod, "__path__"))
2717 return 1;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 for (i = 0; ; i++) {
2720 PyObject *item = PySequence_GetItem(fromlist, i);
2721 int hasit;
2722 if (item == NULL) {
2723 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2724 PyErr_Clear();
2725 return 1;
2726 }
2727 return 0;
2728 }
2729 if (!PyUnicode_Check(item)) {
2730 PyErr_SetString(PyExc_TypeError,
2731 "Item in ``from list'' not a string");
2732 Py_DECREF(item);
2733 return 0;
2734 }
2735 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
2736 PyObject *all;
2737 Py_DECREF(item);
2738 /* See if the package defines __all__ */
2739 if (recursive)
2740 continue; /* Avoid endless recursion */
2741 all = PyObject_GetAttrString(mod, "__all__");
2742 if (all == NULL)
2743 PyErr_Clear();
2744 else {
2745 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2746 Py_DECREF(all);
2747 if (!ret)
2748 return 0;
2749 }
2750 continue;
2751 }
2752 hasit = PyObject_HasAttr(mod, item);
2753 if (!hasit) {
2754 PyObject *item8;
2755 char *subname;
2756 PyObject *submod;
2757 char *p;
Victor Stinnerae6265f2010-05-15 16:27:27 +00002758 item8 = PyUnicode_EncodeFSDefault(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 if (!item8) {
2760 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2761 return 0;
2762 }
2763 subname = PyBytes_AS_STRING(item8);
2764 if (buflen + strlen(subname) >= MAXPATHLEN) {
2765 PyErr_SetString(PyExc_ValueError,
2766 "Module name too long");
2767 Py_DECREF(item);
2768 return 0;
2769 }
2770 p = buf + buflen;
2771 *p++ = '.';
2772 strcpy(p, subname);
2773 submod = import_submodule(mod, subname, buf);
2774 Py_DECREF(item8);
2775 Py_XDECREF(submod);
2776 if (submod == NULL) {
2777 Py_DECREF(item);
2778 return 0;
2779 }
2780 }
2781 Py_DECREF(item);
2782 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002785}
2786
Neil Schemenauer00b09662003-06-16 21:03:07 +00002787static int
2788add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 PyObject *modules)
Neil Schemenauer00b09662003-06-16 21:03:07 +00002790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 if (mod == Py_None)
2792 return 1;
2793 /* Irrespective of the success of this load, make a
2794 reference to it in the parent package module. A copy gets
2795 saved in the modules dictionary under the full name, so get a
2796 reference from there, if need be. (The exception is when the
2797 load failed with a SyntaxError -- then there's no trace in
2798 sys.modules. In that case, of course, do nothing extra.) */
2799 if (submod == NULL) {
2800 submod = PyDict_GetItemString(modules, fullname);
2801 if (submod == NULL)
2802 return 1;
2803 }
2804 if (PyModule_Check(mod)) {
2805 /* We can't use setattr here since it can give a
2806 * spurious warning if the submodule name shadows a
2807 * builtin name */
2808 PyObject *dict = PyModule_GetDict(mod);
2809 if (!dict)
2810 return 0;
2811 if (PyDict_SetItemString(dict, subname, submod) < 0)
2812 return 0;
2813 }
2814 else {
2815 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2816 return 0;
2817 }
2818 return 1;
Neil Schemenauer00b09662003-06-16 21:03:07 +00002819}
2820
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002821static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002822import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 PyObject *modules = PyImport_GetModuleDict();
2825 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* Require:
2828 if mod == None: subname == fullname
2829 else: mod.__name__ + "." + subname == fullname
2830 */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2833 Py_INCREF(m);
2834 }
2835 else {
2836 PyObject *path, *loader = NULL;
2837 char buf[MAXPATHLEN+1];
2838 struct filedescr *fdp;
2839 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 if (mod == Py_None)
2842 path = NULL;
2843 else {
2844 path = PyObject_GetAttrString(mod, "__path__");
2845 if (path == NULL) {
2846 PyErr_Clear();
2847 Py_INCREF(Py_None);
2848 return Py_None;
2849 }
2850 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 buf[0] = '\0';
2853 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2854 &fp, &loader);
2855 Py_XDECREF(path);
2856 if (fdp == NULL) {
2857 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2858 return NULL;
2859 PyErr_Clear();
2860 Py_INCREF(Py_None);
2861 return Py_None;
2862 }
2863 m = load_module(fullname, fp, buf, fdp->type, loader);
2864 Py_XDECREF(loader);
2865 if (fp)
2866 fclose(fp);
2867 if (!add_submodule(mod, m, fullname, subname, modules)) {
2868 Py_XDECREF(m);
2869 m = NULL;
2870 }
2871 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002874}
2875
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876
2877/* Re-import a module of any kind and return its module object, WITH
2878 INCREMENTED REFERENCE COUNT */
2879
Guido van Rossum79f25d91997-04-29 20:08:16 +00002880PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002881PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 PyInterpreterState *interp = PyThreadState_Get()->interp;
2884 PyObject *modules_reloading = interp->modules_reloading;
2885 PyObject *modules = PyImport_GetModuleDict();
2886 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2887 char *name, *subname;
2888 char buf[MAXPATHLEN+1];
2889 struct filedescr *fdp;
2890 FILE *fp = NULL;
2891 PyObject *newm;
Brett Cannon9a5b25a2010-03-01 02:09:17 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 if (modules_reloading == NULL) {
2894 Py_FatalError("PyImport_ReloadModule: "
2895 "no modules_reloading dictionary!");
2896 return NULL;
2897 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 if (m == NULL || !PyModule_Check(m)) {
2900 PyErr_SetString(PyExc_TypeError,
2901 "reload() argument must be module");
2902 return NULL;
2903 }
2904 name = (char*)PyModule_GetName(m);
2905 if (name == NULL)
2906 return NULL;
2907 if (m != PyDict_GetItemString(modules, name)) {
2908 PyErr_Format(PyExc_ImportError,
2909 "reload(): module %.200s not in sys.modules",
2910 name);
2911 return NULL;
2912 }
2913 existing_m = PyDict_GetItemString(modules_reloading, name);
2914 if (existing_m != NULL) {
2915 /* Due to a recursive reload, this module is already
2916 being reloaded. */
2917 Py_INCREF(existing_m);
2918 return existing_m;
2919 }
2920 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2921 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 subname = strrchr(name, '.');
2924 if (subname == NULL)
2925 subname = name;
2926 else {
2927 PyObject *parentname, *parent;
2928 parentname = PyUnicode_FromStringAndSize(name, (subname-name));
2929 if (parentname == NULL) {
2930 imp_modules_reloading_clear();
2931 return NULL;
2932 }
2933 parent = PyDict_GetItem(modules, parentname);
2934 if (parent == NULL) {
2935 PyErr_Format(PyExc_ImportError,
2936 "reload(): parent %U not in sys.modules",
2937 parentname);
2938 Py_DECREF(parentname);
2939 imp_modules_reloading_clear();
2940 return NULL;
2941 }
2942 Py_DECREF(parentname);
2943 subname++;
2944 path = PyObject_GetAttrString(parent, "__path__");
2945 if (path == NULL)
2946 PyErr_Clear();
2947 }
2948 buf[0] = '\0';
2949 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2950 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 if (fdp == NULL) {
2953 Py_XDECREF(loader);
2954 imp_modules_reloading_clear();
2955 return NULL;
2956 }
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 newm = load_module(name, fp, buf, fdp->type, loader);
2959 Py_XDECREF(loader);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 if (fp)
2962 fclose(fp);
2963 if (newm == NULL) {
2964 /* load_module probably removed name from modules because of
2965 * the error. Put back the original module object. We're
2966 * going to return NULL in this case regardless of whether
2967 * replacing name succeeds, so the return value is ignored.
2968 */
2969 PyDict_SetItemString(modules, name, m);
2970 }
2971 imp_modules_reloading_clear();
2972 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002973}
2974
2975
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002976/* Higher-level import emulator which emulates the "import" statement
2977 more accurately -- it invokes the __import__() function from the
2978 builtins of the current globals. This means that the import is
2979 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00002980 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00002981 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002982 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002983 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002984
2985PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002986PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 static PyObject *silly_list = NULL;
2989 static PyObject *builtins_str = NULL;
2990 static PyObject *import_str = NULL;
2991 PyObject *globals = NULL;
2992 PyObject *import = NULL;
2993 PyObject *builtins = NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00002994 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 /* Initialize constant string objects */
2998 if (silly_list == NULL) {
2999 import_str = PyUnicode_InternFromString("__import__");
3000 if (import_str == NULL)
3001 return NULL;
3002 builtins_str = PyUnicode_InternFromString("__builtins__");
3003 if (builtins_str == NULL)
3004 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00003005 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 if (silly_list == NULL)
3007 return NULL;
3008 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 /* Get the builtins from current globals */
3011 globals = PyEval_GetGlobals();
3012 if (globals != NULL) {
3013 Py_INCREF(globals);
3014 builtins = PyObject_GetItem(globals, builtins_str);
3015 if (builtins == NULL)
3016 goto err;
3017 }
3018 else {
3019 /* No globals -- use standard builtins, and fake globals */
3020 builtins = PyImport_ImportModuleLevel("builtins",
3021 NULL, NULL, NULL, 0);
3022 if (builtins == NULL)
3023 return NULL;
3024 globals = Py_BuildValue("{OO}", builtins_str, builtins);
3025 if (globals == NULL)
3026 goto err;
3027 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 /* Get the __import__ function from the builtins */
3030 if (PyDict_Check(builtins)) {
3031 import = PyObject_GetItem(builtins, import_str);
3032 if (import == NULL)
3033 PyErr_SetObject(PyExc_KeyError, import_str);
3034 }
3035 else
3036 import = PyObject_GetAttr(builtins, import_str);
3037 if (import == NULL)
3038 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00003041 Always use absolute import here.
3042 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
3044 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00003045 if (r == NULL)
3046 goto err;
3047 Py_DECREF(r);
3048
3049 modules = PyImport_GetModuleDict();
3050 r = PyDict_GetItem(modules, module_name);
3051 if (r != NULL)
3052 Py_INCREF(r);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003053
3054 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 Py_XDECREF(globals);
3056 Py_XDECREF(builtins);
3057 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00003058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00003060}
3061
3062
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003063/* Module 'imp' provides Python access to the primitives used for
3064 importing modules.
3065*/
3066
Guido van Rossum79f25d91997-04-29 20:08:16 +00003067static PyObject *
Barry Warsaw28a691b2010-04-17 00:19:56 +00003068imp_make_magic(long magic)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 char buf[4];
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 buf[0] = (char) ((magic >> 0) & 0xff);
3073 buf[1] = (char) ((magic >> 8) & 0xff);
3074 buf[2] = (char) ((magic >> 16) & 0xff);
3075 buf[3] = (char) ((magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 return PyBytes_FromStringAndSize(buf, 4);
3078};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003079
3080static PyObject *
3081imp_get_magic(PyObject *self, PyObject *noargs)
3082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 return imp_make_magic(pyc_magic);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003084}
3085
3086static PyObject *
3087imp_get_tag(PyObject *self, PyObject *noargs)
3088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 return PyUnicode_FromString(pyc_tag);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003090}
3091
Guido van Rossum79f25d91997-04-29 20:08:16 +00003092static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003093imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 PyObject *list;
3096 struct filedescr *fdp;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 list = PyList_New(0);
3099 if (list == NULL)
3100 return NULL;
3101 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
3102 PyObject *item = Py_BuildValue("ssi",
3103 fdp->suffix, fdp->mode, fdp->type);
3104 if (item == NULL) {
3105 Py_DECREF(list);
3106 return NULL;
3107 }
3108 if (PyList_Append(list, item) < 0) {
3109 Py_DECREF(list);
3110 Py_DECREF(item);
3111 return NULL;
3112 }
3113 Py_DECREF(item);
3114 }
3115 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003116}
3117
Guido van Rossum79f25d91997-04-29 20:08:16 +00003118static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003119call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 extern int fclose(FILE *);
3122 PyObject *fob, *ret;
3123 PyObject *pathobj;
3124 struct filedescr *fdp;
3125 char pathname[MAXPATHLEN+1];
3126 FILE *fp = NULL;
3127 int fd = -1;
3128 char *found_encoding = NULL;
3129 char *encoding = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 pathname[0] = '\0';
3132 if (path == Py_None)
3133 path = NULL;
3134 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
3135 if (fdp == NULL)
3136 return NULL;
3137 if (fp != NULL) {
3138 fd = fileno(fp);
3139 if (fd != -1)
3140 fd = dup(fd);
3141 fclose(fp);
3142 fp = NULL;
3143 }
3144 if (fd != -1) {
3145 if (strchr(fdp->mode, 'b') == NULL) {
3146 /* PyTokenizer_FindEncoding() returns PyMem_MALLOC'ed
3147 memory. */
3148 found_encoding = PyTokenizer_FindEncoding(fd);
3149 lseek(fd, 0, 0); /* Reset position */
3150 if (found_encoding == NULL && PyErr_Occurred())
3151 return NULL;
3152 encoding = (found_encoding != NULL) ? found_encoding :
3153 (char*)PyUnicode_GetDefaultEncoding();
3154 }
3155 fob = PyFile_FromFd(fd, pathname, fdp->mode, -1,
3156 (char*)encoding, NULL, NULL, 1);
3157 if (fob == NULL) {
3158 close(fd);
3159 PyMem_FREE(found_encoding);
3160 return NULL;
3161 }
3162 }
3163 else {
3164 fob = Py_None;
3165 Py_INCREF(fob);
3166 }
3167 pathobj = PyUnicode_DecodeFSDefault(pathname);
3168 ret = Py_BuildValue("NN(ssi)",
3169 fob, pathobj, fdp->suffix, fdp->mode, fdp->type);
3170 PyMem_FREE(found_encoding);
Brett Cannon3bb42d92007-10-20 03:43:15 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 return ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003173}
3174
Guido van Rossum79f25d91997-04-29 20:08:16 +00003175static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003176imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 char *name;
3179 PyObject *ret, *path = NULL;
3180 if (!PyArg_ParseTuple(args, "es|O:find_module",
3181 Py_FileSystemDefaultEncoding, &name,
3182 &path))
3183 return NULL;
3184 ret = call_find_module(name, path);
3185 PyMem_Free(name);
3186 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003187}
3188
3189static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003190imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 char *name;
3193 int ret;
3194 PyObject *m;
3195 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
3196 return NULL;
3197 ret = init_builtin(name);
3198 if (ret < 0)
3199 return NULL;
3200 if (ret == 0) {
3201 Py_INCREF(Py_None);
3202 return Py_None;
3203 }
3204 m = PyImport_AddModule(name);
3205 Py_XINCREF(m);
3206 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003207}
3208
Guido van Rossum79f25d91997-04-29 20:08:16 +00003209static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003210imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 char *name;
3213 int ret;
3214 PyObject *m;
3215 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
3216 return NULL;
3217 ret = PyImport_ImportFrozenModule(name);
3218 if (ret < 0)
3219 return NULL;
3220 if (ret == 0) {
3221 Py_INCREF(Py_None);
3222 return Py_None;
3223 }
3224 m = PyImport_AddModule(name);
3225 Py_XINCREF(m);
3226 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003227}
3228
Guido van Rossum79f25d91997-04-29 20:08:16 +00003229static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003230imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
3235 return NULL;
3236 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00003237}
3238
Guido van Rossum79f25d91997-04-29 20:08:16 +00003239static PyObject *
Brett Cannon8d110132009-03-15 02:20:16 +00003240imp_is_frozen_package(PyObject *self, PyObject *args)
3241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 char *name;
Brett Cannon8d110132009-03-15 02:20:16 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 if (!PyArg_ParseTuple(args, "s:is_frozen_package", &name))
3245 return NULL;
3246 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00003247}
3248
3249static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003250imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 char *name;
3253 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
3254 return NULL;
3255 return PyLong_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003256}
3257
Guido van Rossum79f25d91997-04-29 20:08:16 +00003258static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003259imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 char *name;
3262 struct _frozen *p;
3263 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
3264 return NULL;
3265 p = find_frozen(name);
3266 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003267}
3268
3269static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003270get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 FILE *fp;
3273 if (mode[0] == 'U')
3274 mode = "r" PY_STDIOTEXTMODE;
3275 if (fob == NULL) {
3276 fp = fopen(pathname, mode);
3277 }
3278 else {
3279 int fd = PyObject_AsFileDescriptor(fob);
3280 if (fd == -1)
3281 return NULL;
3282 if (!_PyVerify_fd(fd))
3283 goto error;
3284 /* the FILE struct gets a new fd, so that it can be closed
3285 * independently of the file descriptor given
3286 */
3287 fd = dup(fd);
3288 if (fd == -1)
3289 goto error;
3290 fp = fdopen(fd, mode);
3291 }
3292 if (fp)
3293 return fp;
Kristján Valur Jónssone1b04452009-03-31 17:43:39 +00003294error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 PyErr_SetFromErrno(PyExc_IOError);
3296 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003297}
3298
Guido van Rossum79f25d91997-04-29 20:08:16 +00003299static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003300imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 char *name;
3303 char *pathname;
3304 PyObject *fob = NULL;
3305 PyObject *m;
3306 FILE *fp;
3307 if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
3308 &name,
3309 Py_FileSystemDefaultEncoding, &pathname,
3310 &fob))
3311 return NULL;
3312 fp = get_file(pathname, fob, "rb");
3313 if (fp == NULL) {
3314 PyMem_Free(pathname);
3315 return NULL;
3316 }
3317 m = load_compiled_module(name, pathname, fp);
3318 fclose(fp);
3319 PyMem_Free(pathname);
3320 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003321}
3322
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003323#ifdef HAVE_DYNAMIC_LOADING
3324
Guido van Rossum79f25d91997-04-29 20:08:16 +00003325static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003326imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 char *name;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003329 PyObject *pathbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 char *pathname;
3331 PyObject *fob = NULL;
3332 PyObject *m;
3333 FILE *fp = NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003334 if (!PyArg_ParseTuple(args, "sO&|O:load_dynamic",
3335 &name, PyUnicode_FSConverter, &pathbytes, &fob))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 return NULL;
Victor Stinner8dbf6292010-10-15 12:48:01 +00003337 pathname = PyBytes_AS_STRING(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 if (fob) {
3339 fp = get_file(pathname, fob, "r");
3340 if (fp == NULL) {
Victor Stinner8dbf6292010-10-15 12:48:01 +00003341 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 return NULL;
3343 }
3344 }
3345 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Victor Stinner8dbf6292010-10-15 12:48:01 +00003346 Py_DECREF(pathbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (fp)
3348 fclose(fp);
3349 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003350}
3351
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003352#endif /* HAVE_DYNAMIC_LOADING */
3353
Guido van Rossum79f25d91997-04-29 20:08:16 +00003354static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003355imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 char *name;
3358 char *pathname;
3359 PyObject *fob = NULL;
3360 PyObject *m;
3361 FILE *fp;
3362 if (!PyArg_ParseTuple(args, "ses|O:load_source",
3363 &name,
3364 Py_FileSystemDefaultEncoding, &pathname,
3365 &fob))
3366 return NULL;
3367 fp = get_file(pathname, fob, "r");
3368 if (fp == NULL) {
3369 PyMem_Free(pathname);
3370 return NULL;
3371 }
3372 m = load_source_module(name, pathname, fp);
3373 PyMem_Free(pathname);
3374 fclose(fp);
3375 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003376}
3377
Guido van Rossum79f25d91997-04-29 20:08:16 +00003378static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003379imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 char *name;
3382 PyObject *fob;
3383 char *pathname;
3384 PyObject * ret;
3385 char *suffix; /* Unused */
3386 char *mode;
3387 int type;
3388 FILE *fp;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 if (!PyArg_ParseTuple(args, "sOes(ssi):load_module",
3391 &name, &fob,
3392 Py_FileSystemDefaultEncoding, &pathname,
3393 &suffix, &mode, &type))
3394 return NULL;
3395 if (*mode) {
3396 /* Mode must start with 'r' or 'U' and must not contain '+'.
3397 Implicit in this test is the assumption that the mode
3398 may contain other modifiers like 'b' or 't'. */
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
3401 PyErr_Format(PyExc_ValueError,
3402 "invalid file open mode %.200s", mode);
3403 PyMem_Free(pathname);
3404 return NULL;
3405 }
3406 }
3407 if (fob == Py_None)
3408 fp = NULL;
3409 else {
3410 fp = get_file(NULL, fob, mode);
3411 if (fp == NULL) {
3412 PyMem_Free(pathname);
3413 return NULL;
3414 }
3415 }
3416 ret = load_module(name, fp, pathname, type, NULL);
3417 PyMem_Free(pathname);
3418 if (fp)
3419 fclose(fp);
3420 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003421}
3422
3423static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003424imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 char *name;
3427 char *pathname;
3428 PyObject * ret;
3429 if (!PyArg_ParseTuple(args, "ses:load_package",
3430 &name, Py_FileSystemDefaultEncoding, &pathname))
3431 return NULL;
3432 ret = load_package(name, pathname);
3433 PyMem_Free(pathname);
3434 return ret;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003435}
3436
3437static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003438imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 char *name;
3441 if (!PyArg_ParseTuple(args, "s:new_module", &name))
3442 return NULL;
3443 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003444}
3445
Christian Heimes13a7a212008-01-07 17:13:09 +00003446static PyObject *
3447imp_reload(PyObject *self, PyObject *v)
3448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 return PyImport_ReloadModule(v);
Christian Heimes13a7a212008-01-07 17:13:09 +00003450}
3451
3452PyDoc_STRVAR(doc_reload,
3453"reload(module) -> module\n\
3454\n\
3455Reload the module. The module must have been successfully imported before.");
3456
Barry Warsaw28a691b2010-04-17 00:19:56 +00003457static PyObject *
3458imp_cache_from_source(PyObject *self, PyObject *args, PyObject *kws)
3459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 static char *kwlist[] = {"path", "debug_override", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 char buf[MAXPATHLEN+1];
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003463 PyObject *pathbytes;
3464 char *cpathname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 PyObject *debug_override = Py_None;
3466 int debug = !Py_OptimizeFlag;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 if (!PyArg_ParseTupleAndKeywords(
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003469 args, kws, "O&|O", kwlist,
3470 PyUnicode_FSConverter, &pathbytes, &debug_override))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 if (debug_override != Py_None)
3474 if ((debug = PyObject_IsTrue(debug_override)) < 0)
3475 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003476
Victor Stinner3ea23dd2010-10-15 20:34:32 +00003477 cpathname = make_compiled_pathname(
3478 PyBytes_AS_STRING(pathbytes),
3479 buf, MAXPATHLEN+1, debug);
3480 Py_DECREF(pathbytes);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 if (cpathname == NULL) {
3483 PyErr_Format(PyExc_SystemError, "path buffer too short");
3484 return NULL;
3485 }
3486 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003487}
3488
3489PyDoc_STRVAR(doc_cache_from_source,
3490"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\
3491\n\
3492The .py file does not need to exist; this simply returns the path to the\n\
3493.pyc/.pyo file calculated as if the .py file were imported. The extension\n\
3494will be .pyc unless __debug__ is not defined, then it will be .pyo.\n\
3495\n\
3496If debug_override is not None, then it must be a boolean and is taken as\n\
3497the value of __debug__ instead.");
3498
3499static PyObject *
3500imp_source_from_cache(PyObject *self, PyObject *args, PyObject *kws)
3501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 static char *kwlist[] = {"path", NULL};
Barry Warsaw28a691b2010-04-17 00:19:56 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 char *pathname;
3505 char buf[MAXPATHLEN+1];
Barry Warsaw28a691b2010-04-17 00:19:56 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 if (!PyArg_ParseTupleAndKeywords(
3508 args, kws, "es", kwlist,
3509 Py_FileSystemDefaultEncoding, &pathname))
3510 return NULL;
Barry Warsaw28a691b2010-04-17 00:19:56 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 if (make_source_pathname(pathname, buf) == NULL) {
3513 PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
3514 pathname);
3515 PyMem_Free(pathname);
3516 return NULL;
3517 }
3518 PyMem_Free(pathname);
3519 return PyUnicode_FromString(buf);
Barry Warsaw28a691b2010-04-17 00:19:56 +00003520}
3521
3522PyDoc_STRVAR(doc_source_from_cache,
3523"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\
3524\n\
3525The .pyc/.pyo file does not need to exist; this simply returns the path to\n\
3526the .py file calculated to correspond to the .pyc/.pyo file. If path\n\
3527does not conform to PEP 3147 format, ValueError will be raised.");
3528
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003529/* Doc strings */
3530
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003531PyDoc_STRVAR(doc_imp,
3532"This module provides the components needed to build your own\n\
3533__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003535PyDoc_STRVAR(doc_find_module,
3536"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003537Search for a module. If path is omitted or None, search for a\n\
3538built-in, frozen or special module and continue search in sys.path.\n\
3539The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003540package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003542PyDoc_STRVAR(doc_load_module,
3543"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003544Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003545The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003546
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003547PyDoc_STRVAR(doc_get_magic,
3548"get_magic() -> string\n\
3549Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003550
Barry Warsaw28a691b2010-04-17 00:19:56 +00003551PyDoc_STRVAR(doc_get_tag,
3552"get_tag() -> string\n\
3553Return the magic tag for .pyc or .pyo files.");
3554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003555PyDoc_STRVAR(doc_get_suffixes,
3556"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003557Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003558that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003560PyDoc_STRVAR(doc_new_module,
3561"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003562Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003563The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003565PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003566"lock_held() -> boolean\n\
3567Return True if the import lock is currently held, else False.\n\
3568On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003569
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003570PyDoc_STRVAR(doc_acquire_lock,
3571"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003572Acquires the interpreter's import lock for the current thread.\n\
3573This lock should be used by import hooks to ensure thread-safety\n\
3574when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003575On platforms without threads, this function does nothing.");
3576
3577PyDoc_STRVAR(doc_release_lock,
3578"release_lock() -> None\n\
3579Release the interpreter's import lock.\n\
3580On platforms without threads, this function does nothing.");
3581
Guido van Rossum79f25d91997-04-29 20:08:16 +00003582static PyMethodDef imp_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3584 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3585 {"get_tag", imp_get_tag, METH_NOARGS, doc_get_tag},
3586 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3587 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3588 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3589 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3590 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3591 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
3592 {"reload", imp_reload, METH_O, doc_reload},
3593 {"cache_from_source", (PyCFunction)imp_cache_from_source,
3594 METH_VARARGS | METH_KEYWORDS, doc_cache_from_source},
3595 {"source_from_cache", (PyCFunction)imp_source_from_cache,
3596 METH_VARARGS | METH_KEYWORDS, doc_source_from_cache},
3597 /* The rest are obsolete */
3598 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3599 {"is_frozen_package", imp_is_frozen_package, METH_VARARGS},
3600 {"init_builtin", imp_init_builtin, METH_VARARGS},
3601 {"init_frozen", imp_init_frozen, METH_VARARGS},
3602 {"is_builtin", imp_is_builtin, METH_VARARGS},
3603 {"is_frozen", imp_is_frozen, METH_VARARGS},
3604 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003605#ifdef HAVE_DYNAMIC_LOADING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003607#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 {"load_package", imp_load_package, METH_VARARGS},
3609 {"load_source", imp_load_source, METH_VARARGS},
3610 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003611};
3612
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003613static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003614setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 PyObject *v;
3617 int err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 v = PyLong_FromLong((long)value);
3620 err = PyDict_SetItemString(d, name, v);
3621 Py_XDECREF(v);
3622 return err;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003623}
3624
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003625typedef struct {
3626 PyObject_HEAD
3627} NullImporter;
3628
3629static int
3630NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3631{
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003632#ifndef MS_WINDOWS
3633 PyObject *path;
3634 struct stat statbuf;
3635 int rv;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3638 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003639
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003640 if (!PyArg_ParseTuple(args, "O&:NullImporter",
3641 PyUnicode_FSConverter, &path))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003643
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003644 if (PyBytes_GET_SIZE(path) == 0) {
3645 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 PyErr_SetString(PyExc_ImportError, "empty pathname");
3647 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 }
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003649
3650 rv = stat(PyBytes_AS_STRING(path), &statbuf);
3651 Py_DECREF(path);
3652 if (rv == 0) {
3653 /* it exists */
3654 if (S_ISDIR(statbuf.st_mode)) {
3655 /* it's a directory */
3656 PyErr_SetString(PyExc_ImportError, "existing directory");
3657 return -1;
3658 }
3659 }
3660#else /* MS_WINDOWS */
3661 PyObject *pathobj;
3662 DWORD rv;
Victor Stinner255dfdb2010-09-29 10:28:51 +00003663 wchar_t *path;
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003664
3665 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3666 return -1;
3667
3668 if (!PyArg_ParseTuple(args, "U:NullImporter",
3669 &pathobj))
3670 return -1;
3671
3672 if (PyUnicode_GET_SIZE(pathobj) == 0) {
3673 PyErr_SetString(PyExc_ImportError, "empty pathname");
3674 return -1;
3675 }
3676
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003677 path = PyUnicode_AsWideCharString(pathobj, NULL);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003678 if (path == NULL)
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003679 return -1;
3680 /* see issue1293 and issue3677:
3681 * stat() on Windows doesn't recognise paths like
3682 * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
3683 */
3684 rv = GetFileAttributesW(path);
Victor Stinner255dfdb2010-09-29 10:28:51 +00003685 PyMem_Free(path);
Victor Stinner1a4d12d2010-08-13 13:07:29 +00003686 if (rv != INVALID_FILE_ATTRIBUTES) {
3687 /* it exists */
3688 if (rv & FILE_ATTRIBUTE_DIRECTORY) {
3689 /* it's a directory */
3690 PyErr_SetString(PyExc_ImportError, "existing directory");
3691 return -1;
3692 }
3693 }
3694#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 return 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003696}
3697
3698static PyObject *
3699NullImporter_find_module(NullImporter *self, PyObject *args)
3700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003702}
3703
3704static PyMethodDef NullImporter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3706 "Always return None"
3707 },
3708 {NULL} /* Sentinel */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003709};
3710
3711
Christian Heimes9cd17752007-11-18 19:35:23 +00003712PyTypeObject PyNullImporter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 PyVarObject_HEAD_INIT(NULL, 0)
3714 "imp.NullImporter", /*tp_name*/
3715 sizeof(NullImporter), /*tp_basicsize*/
3716 0, /*tp_itemsize*/
3717 0, /*tp_dealloc*/
3718 0, /*tp_print*/
3719 0, /*tp_getattr*/
3720 0, /*tp_setattr*/
3721 0, /*tp_reserved*/
3722 0, /*tp_repr*/
3723 0, /*tp_as_number*/
3724 0, /*tp_as_sequence*/
3725 0, /*tp_as_mapping*/
3726 0, /*tp_hash */
3727 0, /*tp_call*/
3728 0, /*tp_str*/
3729 0, /*tp_getattro*/
3730 0, /*tp_setattro*/
3731 0, /*tp_as_buffer*/
3732 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3733 "Null importer object", /* tp_doc */
3734 0, /* tp_traverse */
3735 0, /* tp_clear */
3736 0, /* tp_richcompare */
3737 0, /* tp_weaklistoffset */
3738 0, /* tp_iter */
3739 0, /* tp_iternext */
3740 NullImporter_methods, /* tp_methods */
3741 0, /* tp_members */
3742 0, /* tp_getset */
3743 0, /* tp_base */
3744 0, /* tp_dict */
3745 0, /* tp_descr_get */
3746 0, /* tp_descr_set */
3747 0, /* tp_dictoffset */
3748 (initproc)NullImporter_init, /* tp_init */
3749 0, /* tp_alloc */
3750 PyType_GenericNew /* tp_new */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003751};
3752
Martin v. Löwis1a214512008-06-11 05:26:20 +00003753static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 PyModuleDef_HEAD_INIT,
3755 "imp",
3756 doc_imp,
3757 0,
3758 imp_methods,
3759 NULL,
3760 NULL,
3761 NULL,
3762 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003763};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003764
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003765PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003766PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 if (PyType_Ready(&PyNullImporter_Type) < 0)
3771 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 m = PyModule_Create(&impmodule);
3774 if (m == NULL)
3775 goto failure;
3776 d = PyModule_GetDict(m);
3777 if (d == NULL)
3778 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3781 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3782 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3783 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3784 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3785 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3786 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3787 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3788 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3789 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 Py_INCREF(&PyNullImporter_Type);
3792 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
3793 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003794 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 Py_XDECREF(m);
3796 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003797}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003798
3799
Guido van Rossumb18618d2000-05-03 23:44:39 +00003800/* API for embedding applications that want to add their own entries
3801 to the table of built-in modules. This should normally be called
3802 *before* Py_Initialize(). When the table resize fails, -1 is
3803 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003804
3805 After a similar function by Just van Rossum. */
3806
3807int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003808PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 static struct _inittab *our_copy = NULL;
3811 struct _inittab *p;
3812 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 /* Count the number of entries in both tables */
3815 for (n = 0; newtab[n].name != NULL; n++)
3816 ;
3817 if (n == 0)
3818 return 0; /* Nothing to do */
3819 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3820 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 /* Allocate new memory for the combined table */
3823 p = our_copy;
3824 PyMem_RESIZE(p, struct _inittab, i+n+1);
3825 if (p == NULL)
3826 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 /* Copy the tables into the new memory */
3829 if (our_copy != PyImport_Inittab)
3830 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3831 PyImport_Inittab = our_copy = p;
3832 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003835}
3836
3837/* Shorthand to add a single entry given a name and a function */
3838
3839int
Brett Cannona826f322009-04-02 03:41:46 +00003840PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 newtab[0].name = (char *)name;
3847 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003850}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003851
3852#ifdef __cplusplus
3853}
3854#endif