blob: c3bd275104d8537d8d3d95ff1d4cb0fb3358c43b [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"
Neal Norwitzadb69fc2005-12-17 20:54:49 +00007#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00008#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000010#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000012#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000014#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000015#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016
Guido van Rossum55a83382000-09-20 20:31:38 +000017#ifdef HAVE_FCNTL_H
18#include <fcntl.h>
19#endif
20
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000021extern time_t PyOS_GetLastModificationTime(char *, FILE *);
22 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000023
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000024/* Magic word to reject .pyc files generated by other Python versions.
25 It should change for each incompatible change to the bytecode.
26
27 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000028 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000029 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000030
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000031 The magic numbers must be spaced apart atleast 2 values, as the
32 -U interpeter flag will cause MAGIC+1 being used. They have been
33 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000034
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000035 There were a variety of old schemes for setting the magic number.
36 The current working scheme is to increment the previous value by
37 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000038
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039 Known values:
40 Python 1.5: 20121
41 Python 1.5.1: 20121
42 Python 1.5.2: 20121
Skip Montanaro4ec3c262006-03-25 14:12:03 +000043 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000044 Python 2.0: 50823
45 Python 2.0.1: 50823
46 Python 2.1: 60202
47 Python 2.1.1: 60202
48 Python 2.1.2: 60202
49 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000050 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000051 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000052 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000053 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000054 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000055 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000056 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000057 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000058 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000059 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000060.
Tim Peters36515e22001-11-18 04:06:29 +000061*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +000062#define MAGIC (62092 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000063
Guido van Rossum96774c12000-05-01 20:19:08 +000064/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000065 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000066 compiler works which are enabled by command line switches. */
67static long pyc_magic = MAGIC;
68
Guido van Rossum25ce5661997-08-02 03:10:38 +000069/* See _PyImport_FixupExtension() below */
70static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000071
Guido van Rossum771c6c81997-10-31 18:37:24 +000072/* This table is defined in config.c: */
73extern struct _inittab _PyImport_Inittab[];
74
75struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000076
Guido van Rossumed1170e1999-12-20 21:23:41 +000077/* these tables define the module suffixes that Python recognizes */
78struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000079
80#ifdef RISCOS
81static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000082 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000083 {"/pyc", "rb", PY_COMPILED},
84 {0, 0}
85};
86#else
Guido van Rossumed1170e1999-12-20 21:23:41 +000087static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000088 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000089#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +000090 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +000091#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +000092 {".pyc", "rb", PY_COMPILED},
93 {0, 0}
94};
Guido van Rossum48a680c2001-03-02 06:34:14 +000095#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +000096
Guido van Rossum1ae940a1995-01-02 19:04:15 +000097/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098
99void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000100_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000102 const struct filedescr *scan;
103 struct filedescr *filetab;
104 int countD = 0;
105 int countS = 0;
106
107 /* prepare _PyImport_Filetab: copy entries from
108 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
109 */
110 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
111 ++countD;
112 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
113 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000114 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Guido van Rossumed1170e1999-12-20 21:23:41 +0000115 memcpy(filetab, _PyImport_DynLoadFiletab,
116 countD * sizeof(struct filedescr));
117 memcpy(filetab + countD, _PyImport_StandardFiletab,
118 countS * sizeof(struct filedescr));
119 filetab[countD + countS].suffix = NULL;
120
121 _PyImport_Filetab = filetab;
122
Guido van Rossum0824f631997-03-11 18:37:35 +0000123 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000124 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
125 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000126#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000127 if (strcmp(filetab->suffix, ".pyc") == 0)
128 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000129#else
130 if (strcmp(filetab->suffix, "/pyc") == 0)
131 filetab->suffix = "/pyo";
132#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000133 }
134 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000135
136 if (Py_UnicodeFlag) {
137 /* Fix the pyc_magic so that byte compiled code created
138 using the all-Unicode method doesn't interfere with
139 code created in normal operation mode. */
140 pyc_magic = MAGIC + 1;
141 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142}
143
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144void
Just van Rossum52e14d62002-12-30 22:08:05 +0000145_PyImportHooks_Init(void)
146{
147 PyObject *v, *path_hooks = NULL, *zimpimport;
148 int err = 0;
149
150 /* adding sys.path_hooks and sys.path_importer_cache, setting up
151 zipimport */
152
153 if (Py_VerboseFlag)
154 PySys_WriteStderr("# installing zipimport hook\n");
155
156 v = PyList_New(0);
157 if (v == NULL)
158 goto error;
159 err = PySys_SetObject("meta_path", v);
160 Py_DECREF(v);
161 if (err)
162 goto error;
163 v = PyDict_New();
164 if (v == NULL)
165 goto error;
166 err = PySys_SetObject("path_importer_cache", v);
167 Py_DECREF(v);
168 if (err)
169 goto error;
170 path_hooks = PyList_New(0);
171 if (path_hooks == NULL)
172 goto error;
173 err = PySys_SetObject("path_hooks", path_hooks);
174 if (err) {
175 error:
176 PyErr_Print();
177 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
178 "path_importer_cache failed");
179 }
180 zimpimport = PyImport_ImportModule("zipimport");
181 if (zimpimport == NULL) {
182 PyErr_Clear(); /* No zip import module -- okay */
183 if (Py_VerboseFlag)
184 PySys_WriteStderr("# can't import zipimport\n");
185 }
186 else {
187 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
188 "zipimporter");
189 Py_DECREF(zimpimport);
190 if (zipimporter == NULL) {
191 PyErr_Clear(); /* No zipimporter object -- okay */
192 if (Py_VerboseFlag)
193 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000194 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000195 }
196 else {
197 /* sys.path_hooks.append(zipimporter) */
198 err = PyList_Append(path_hooks, zipimporter);
199 Py_DECREF(zipimporter);
200 if (err)
201 goto error;
202 if (Py_VerboseFlag)
203 PySys_WriteStderr(
204 "# installed zipimport hook\n");
205 }
206 }
207 Py_DECREF(path_hooks);
208}
209
210void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000211_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000212{
213 Py_XDECREF(extensions);
214 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000215 PyMem_DEL(_PyImport_Filetab);
216 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000217}
218
219
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000220/* Locking primitives to prevent parallel imports of the same module
221 in different threads to return with a partially loaded module.
222 These calls are serialized by the global interpreter lock. */
223
224#ifdef WITH_THREAD
225
Guido van Rossum49b56061998-10-01 20:42:43 +0000226#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000227
Guido van Rossum65d5b571998-12-21 19:32:43 +0000228static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000229static long import_lock_thread = -1;
230static int import_lock_level = 0;
231
232static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000233lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000234{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000235 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000236 if (me == -1)
237 return; /* Too bad */
238 if (import_lock == NULL)
Guido van Rossum65d5b571998-12-21 19:32:43 +0000239 import_lock = PyThread_allocate_lock();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000240 if (import_lock_thread == me) {
241 import_lock_level++;
242 return;
243 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000244 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
245 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000246 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000247 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000248 PyEval_RestoreThread(tstate);
249 }
250 import_lock_thread = me;
251 import_lock_level = 1;
252}
253
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000254static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000255unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000256{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000257 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000258 if (me == -1)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000259 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000260 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000261 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000262 import_lock_level--;
263 if (import_lock_level == 0) {
264 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000265 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000266 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000267 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000268}
269
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000270/* This function is called from PyOS_AfterFork to ensure that newly
271 created child processes do not share locks with the parent. */
272
273void
274_PyImport_ReInitLock(void)
275{
276#ifdef _AIX
277 if (import_lock != NULL)
278 import_lock = PyThread_allocate_lock();
279#endif
280}
281
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000282#else
283
284#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000285#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000286
287#endif
288
Tim Peters69232342001-08-30 05:16:13 +0000289static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000290imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000291{
Tim Peters69232342001-08-30 05:16:13 +0000292#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000293 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000294#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000295 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000296#endif
297}
298
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000299static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000300imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000301{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000302#ifdef WITH_THREAD
303 lock_import();
304#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000305 Py_INCREF(Py_None);
306 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000307}
308
309static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000310imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000311{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000312#ifdef WITH_THREAD
313 if (unlock_import() < 0) {
314 PyErr_SetString(PyExc_RuntimeError,
315 "not holding the import lock");
316 return NULL;
317 }
318#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000319 Py_INCREF(Py_None);
320 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000321}
322
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323/* Helper for sys */
324
325PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000326PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000328 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000329 if (interp->modules == NULL)
330 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
331 return interp->modules;
332}
333
Guido van Rossum3f5da241990-12-20 15:06:42 +0000334
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000335/* List of names to clear in sys */
336static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000337 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000338 "exc_type", "exc_value", "exc_traceback",
339 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000340 "path_hooks", "path_importer_cache", "meta_path",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000341 NULL
342};
343
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000344static char* sys_files[] = {
345 "stdin", "__stdin__",
346 "stdout", "__stdout__",
347 "stderr", "__stderr__",
348 NULL
349};
350
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000351
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000352/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000353
Guido van Rossum3f5da241990-12-20 15:06:42 +0000354void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000355PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000356{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000357 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000358 char *name;
359 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000360 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000361 PyObject *modules = interp->modules;
362
363 if (modules == NULL)
364 return; /* Already done */
365
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000366 /* Delete some special variables first. These are common
367 places where user values hide and people complain when their
368 destructors fail. Since the modules containing them are
369 deleted *last* of all, they would come too late in the normal
370 destruction order. Sigh. */
371
372 value = PyDict_GetItemString(modules, "__builtin__");
373 if (value != NULL && PyModule_Check(value)) {
374 dict = PyModule_GetDict(value);
375 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000376 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000377 PyDict_SetItemString(dict, "_", Py_None);
378 }
379 value = PyDict_GetItemString(modules, "sys");
380 if (value != NULL && PyModule_Check(value)) {
381 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000382 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000383 dict = PyModule_GetDict(value);
384 for (p = sys_deletes; *p != NULL; p++) {
385 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000386 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000387 PyDict_SetItemString(dict, *p, Py_None);
388 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000389 for (p = sys_files; *p != NULL; p+=2) {
390 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000391 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000392 v = PyDict_GetItemString(dict, *(p+1));
393 if (v == NULL)
394 v = Py_None;
395 PyDict_SetItemString(dict, *p, v);
396 }
397 }
398
399 /* First, delete __main__ */
400 value = PyDict_GetItemString(modules, "__main__");
401 if (value != NULL && PyModule_Check(value)) {
402 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000403 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000404 _PyModule_Clear(value);
405 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000406 }
407
Guido van Rossum758eec01998-01-19 21:58:26 +0000408 /* The special treatment of __builtin__ here is because even
409 when it's not referenced as a module, its dictionary is
410 referenced by almost every module's __builtins__. Since
411 deleting a module clears its dictionary (even if there are
412 references left to it), we need to delete the __builtin__
413 module last. Likewise, we don't delete sys until the very
414 end because it is implicitly referenced (e.g. by print).
415
416 Also note that we 'delete' modules by replacing their entry
417 in the modules dict with None, rather than really deleting
418 them; this avoids a rehash of the modules dictionary and
419 also marks them as "non existent" so they won't be
420 re-imported. */
421
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000422 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000423 one (skipping __builtin__ and sys) and delete them */
424 do {
425 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000426 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000427 while (PyDict_Next(modules, &pos, &key, &value)) {
428 if (value->ob_refcnt != 1)
429 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000430 if (PyString_Check(key) && PyModule_Check(value)) {
431 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000432 if (strcmp(name, "__builtin__") == 0)
433 continue;
434 if (strcmp(name, "sys") == 0)
435 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000436 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000437 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000438 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000439 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000440 PyDict_SetItem(modules, key, Py_None);
441 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000442 }
443 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000444 } while (ndone > 0);
445
Guido van Rossum758eec01998-01-19 21:58:26 +0000446 /* Next, delete all modules (still skipping __builtin__ and sys) */
447 pos = 0;
448 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000449 if (PyString_Check(key) && PyModule_Check(value)) {
450 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000451 if (strcmp(name, "__builtin__") == 0)
452 continue;
453 if (strcmp(name, "sys") == 0)
454 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000455 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000456 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000457 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000458 PyDict_SetItem(modules, key, Py_None);
459 }
460 }
461
462 /* Next, delete sys and __builtin__ (in that order) */
463 value = PyDict_GetItemString(modules, "sys");
464 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000465 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000466 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000467 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000468 PyDict_SetItemString(modules, "sys", Py_None);
469 }
470 value = PyDict_GetItemString(modules, "__builtin__");
471 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000472 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000473 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000474 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000475 PyDict_SetItemString(modules, "__builtin__", Py_None);
476 }
477
478 /* Finally, clear and delete the modules directory */
479 PyDict_Clear(modules);
480 interp->modules = NULL;
481 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000482}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000483
484
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000485/* Helper for pythonrun.c -- return magic number */
486
487long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000488PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000489{
Guido van Rossum96774c12000-05-01 20:19:08 +0000490 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000491}
492
493
Guido van Rossum25ce5661997-08-02 03:10:38 +0000494/* Magic for extension modules (built-in as well as dynamically
495 loaded). To prevent initializing an extension module more than
496 once, we keep a static dictionary 'extensions' keyed by module name
497 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000498 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000499 dictionary is stored by calling _PyImport_FixupExtension()
500 immediately after the module initialization function succeeds. A
501 copy can be retrieved from there by calling
502 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000503
Guido van Rossum79f25d91997-04-29 20:08:16 +0000504PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000505_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000506{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000507 PyObject *modules, *mod, *dict, *copy;
508 if (extensions == NULL) {
509 extensions = PyDict_New();
510 if (extensions == NULL)
511 return NULL;
512 }
513 modules = PyImport_GetModuleDict();
514 mod = PyDict_GetItemString(modules, name);
515 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000516 PyErr_Format(PyExc_SystemError,
517 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000518 return NULL;
519 }
520 dict = PyModule_GetDict(mod);
521 if (dict == NULL)
522 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000523 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000524 if (copy == NULL)
525 return NULL;
526 PyDict_SetItemString(extensions, filename, copy);
527 Py_DECREF(copy);
528 return copy;
529}
530
531PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000532_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000533{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000534 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535 if (extensions == NULL)
536 return NULL;
537 dict = PyDict_GetItemString(extensions, filename);
538 if (dict == NULL)
539 return NULL;
540 mod = PyImport_AddModule(name);
541 if (mod == NULL)
542 return NULL;
543 mdict = PyModule_GetDict(mod);
544 if (mdict == NULL)
545 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000546 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000549 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550 name, filename);
551 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000552}
553
554
555/* Get the module object corresponding to a module name.
556 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000557 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000558 Because the former action is most common, THIS DOES NOT RETURN A
559 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000560
Guido van Rossum79f25d91997-04-29 20:08:16 +0000561PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000562PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000563{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000565 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000566
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000568 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000569 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000570 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000571 if (m == NULL)
572 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000574 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000575 return NULL;
576 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000577 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000578
579 return m;
580}
581
Tim Peters1cd70172004-08-02 03:52:12 +0000582/* Remove name from sys.modules, if it's there. */
583static void
584_RemoveModule(const char *name)
585{
586 PyObject *modules = PyImport_GetModuleDict();
587 if (PyDict_GetItemString(modules, name) == NULL)
588 return;
589 if (PyDict_DelItemString(modules, name) < 0)
590 Py_FatalError("import: deleting existing key in"
591 "sys.modules failed");
592}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000593
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000594/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000595 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
596 * removed from sys.modules, to avoid leaving damaged module objects
597 * in sys.modules. The caller may wish to restore the original
598 * module object (if any) in this case; PyImport_ReloadModule is an
599 * example.
600 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000601PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000602PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000603{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000604 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
605}
606
607PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000608PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000609{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000611 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000612
Guido van Rossum79f25d91997-04-29 20:08:16 +0000613 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000614 if (m == NULL)
615 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000616 /* If the module is being reloaded, we get the old module back
617 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000618 d = PyModule_GetDict(m);
619 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
620 if (PyDict_SetItemString(d, "__builtins__",
621 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000622 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000623 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000624 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000625 v = NULL;
626 if (pathname != NULL) {
627 v = PyString_FromString(pathname);
628 if (v == NULL)
629 PyErr_Clear();
630 }
631 if (v == NULL) {
632 v = ((PyCodeObject *)co)->co_filename;
633 Py_INCREF(v);
634 }
635 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000636 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000637 Py_DECREF(v);
638
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000639 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000640 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000641 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000642 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000643
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000645 PyErr_Format(PyExc_ImportError,
646 "Loaded module %.200s not found in sys.modules",
647 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000648 return NULL;
649 }
650
Guido van Rossum79f25d91997-04-29 20:08:16 +0000651 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000652
653 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000654
655 error:
656 _RemoveModule(name);
657 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000658}
659
660
661/* Given a pathname for a Python source file, fill a buffer with the
662 pathname for the corresponding compiled file. Return the pathname
663 for the compiled file, or NULL if there's no space in the buffer.
664 Doesn't set an exception. */
665
666static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000668{
Tim Petersc1731372001-08-04 08:12:36 +0000669 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000670 if (len+2 > buflen)
671 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000672
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000673#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000674 /* Treat .pyw as if it were .py. The case of ".pyw" must match
675 that used in _PyImport_StandardFiletab. */
676 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
677 --len; /* pretend 'w' isn't there */
678#endif
679 memcpy(buf, pathname, len);
680 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
681 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000682
683 return buf;
684}
685
686
687/* Given a pathname for a Python source file, its time of last
688 modification, and a pathname for a compiled file, check whether the
689 compiled file represents the same version of the source. If so,
690 return a FILE pointer for the compiled file, positioned just after
691 the header; if not, return NULL.
692 Doesn't set an exception. */
693
694static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000695check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696{
697 FILE *fp;
698 long magic;
699 long pyc_mtime;
700
701 fp = fopen(cpathname, "rb");
702 if (fp == NULL)
703 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000704 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000705 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000706 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000707 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000708 fclose(fp);
709 return NULL;
710 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000712 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000713 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000714 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000715 fclose(fp);
716 return NULL;
717 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000718 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000719 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000720 return fp;
721}
722
723
724/* Read a code object from a file and check it for validity */
725
Guido van Rossum79f25d91997-04-29 20:08:16 +0000726static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000727read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000728{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000729 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000730
Tim Petersd9b9ac82001-01-28 00:27:39 +0000731 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000732 if (co == NULL)
733 return NULL;
734 if (!PyCode_Check(co)) {
735 PyErr_Format(PyExc_ImportError,
736 "Non-code object in %.200s", cpathname);
737 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000738 return NULL;
739 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000740 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000741}
742
743
744/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000745 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000746
Guido van Rossum79f25d91997-04-29 20:08:16 +0000747static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000748load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000749{
750 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000751 PyCodeObject *co;
752 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000753
Guido van Rossum79f25d91997-04-29 20:08:16 +0000754 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000755 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000756 PyErr_Format(PyExc_ImportError,
757 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000758 return NULL;
759 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000760 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000761 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000762 if (co == NULL)
763 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000764 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000765 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000766 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000767 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000768 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769
770 return m;
771}
772
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000773/* Parse a source file and return the corresponding code object */
774
Guido van Rossum79f25d91997-04-29 20:08:16 +0000775static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000777{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000778 PyCodeObject *co = NULL;
779 mod_ty mod;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000780 PyArena *arena = PyArena_New();
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000783 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000785 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000786 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000787 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788 return co;
789}
790
791
Guido van Rossum55a83382000-09-20 20:31:38 +0000792/* Helper to open a bytecode file for writing in exclusive mode */
793
794static FILE *
795open_exclusive(char *filename)
796{
797#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
798 /* Use O_EXCL to avoid a race condition when another process tries to
799 write the same file. When that happens, our open() call fails,
800 which is just fine (since it's only a cache).
801 XXX If the file exists and is writable but the directory is not
802 writable, the file will never be written. Oh well.
803 */
804 int fd;
805 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000806 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
807#ifdef O_BINARY
808 |O_BINARY /* necessary for Windows */
809#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000810#ifdef __VMS
Martin v. Löwis18e16552006-02-15 17:27:45 +0000811 , 0666, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000812#else
Martin v. Löwis18e16552006-02-15 17:27:45 +0000813 , 0666
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000814#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000815 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000816 if (fd < 0)
817 return NULL;
818 return fdopen(fd, "wb");
819#else
820 /* Best we can do -- on Windows this can't happen anyway */
821 return fopen(filename, "wb");
822#endif
823}
824
825
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000826/* Write a compiled module to a file, placing the time of last
827 modification of its source into the header.
828 Errors are ignored, if a write error occurs an attempt is made to
829 remove the file. */
830
831static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000832write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000833{
834 FILE *fp;
835
Guido van Rossum55a83382000-09-20 20:31:38 +0000836 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000837 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000838 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000839 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000840 "# can't create %s\n", cpathname);
841 return;
842 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000843 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000844 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000845 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
846 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000847 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000848 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000849 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000850 /* Don't keep partial file */
851 fclose(fp);
852 (void) unlink(cpathname);
853 return;
854 }
855 /* Now write the true mtime */
856 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000857 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000858 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000859 fflush(fp);
860 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000861 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000862 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000863}
864
865
866/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000867 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
868 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000869
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000871load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000872{
Fred Drake4c82b232000-06-30 16:18:57 +0000873 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874 FILE *fpc;
875 char buf[MAXPATHLEN+1];
876 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000877 PyCodeObject *co;
878 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000880 mtime = PyOS_GetLastModificationTime(pathname, fp);
Neal Norwitz708e51a2005-10-03 04:48:15 +0000881 if (mtime == (time_t)(-1)) {
882 PyErr_Format(PyExc_RuntimeError,
883 "unable to get modification time from '%s'",
884 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000885 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000886 }
Fred Drake4c82b232000-06-30 16:18:57 +0000887#if SIZEOF_TIME_T > 4
888 /* Python's .pyc timestamp handling presumes that the timestamp fits
889 in 4 bytes. This will be fine until sometime in the year 2038,
890 when a 4-byte signed time_t will overflow.
891 */
892 if (mtime >> 32) {
893 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000894 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000895 return NULL;
896 }
897#endif
Tim Peters36515e22001-11-18 04:06:29 +0000898 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000899 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000900 if (cpathname != NULL &&
901 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000902 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000903 fclose(fpc);
904 if (co == NULL)
905 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000906 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000907 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000908 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000909 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000910 }
911 else {
912 co = parse_source_module(pathname, fp);
913 if (co == NULL)
914 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000915 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000916 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000917 name, pathname);
918 write_compiled_module(co, cpathname, mtime);
919 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000920 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000921 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000922
923 return m;
924}
925
926
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000927/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000928static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
929static struct filedescr *find_module(char *, char *, PyObject *,
930 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000931static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000932
933/* Load a package and return its module object WITH INCREMENTED
934 REFERENCE COUNT */
935
936static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000937load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000938{
Tim Peters1cd70172004-08-02 03:52:12 +0000939 PyObject *m, *d;
940 PyObject *file = NULL;
941 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000942 int err;
943 char buf[MAXPATHLEN+1];
944 FILE *fp = NULL;
945 struct filedescr *fdp;
946
947 m = PyImport_AddModule(name);
948 if (m == NULL)
949 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000950 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000951 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000952 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000953 d = PyModule_GetDict(m);
954 file = PyString_FromString(pathname);
955 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000956 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000957 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +0000958 if (path == NULL)
959 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000960 err = PyDict_SetItemString(d, "__file__", file);
961 if (err == 0)
962 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +0000963 if (err != 0)
964 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000965 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +0000966 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000967 if (fdp == NULL) {
968 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
969 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +0000970 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000971 }
972 else
973 m = NULL;
974 goto cleanup;
975 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000976 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000977 if (fp != NULL)
978 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +0000979 goto cleanup;
980
981 error:
982 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000983 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000984 Py_XDECREF(path);
985 Py_XDECREF(file);
986 return m;
987}
988
989
990/* Helper to test for built-in module */
991
992static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000993is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000994{
995 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +0000996 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
997 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
998 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000999 return -1;
1000 else
1001 return 1;
1002 }
1003 }
1004 return 0;
1005}
1006
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001007
Just van Rossum52e14d62002-12-30 22:08:05 +00001008/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1009 possibly by fetching it from the path_importer_cache dict. If it
1010 wasn't yet cached, traverse path_hooks until it a hook is found
1011 that can handle the path item. Return None if no hook could;
1012 this tells our caller it should fall back to the builtin
1013 import mechanism. Cache the result in path_importer_cache.
1014 Returns a borrowed reference. */
1015
1016static PyObject *
1017get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1018 PyObject *p)
1019{
1020 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001021 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001022
1023 /* These conditions are the caller's responsibility: */
1024 assert(PyList_Check(path_hooks));
1025 assert(PyDict_Check(path_importer_cache));
1026
1027 nhooks = PyList_Size(path_hooks);
1028 if (nhooks < 0)
1029 return NULL; /* Shouldn't happen */
1030
1031 importer = PyDict_GetItem(path_importer_cache, p);
1032 if (importer != NULL)
1033 return importer;
1034
1035 /* set path_importer_cache[p] to None to avoid recursion */
1036 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1037 return NULL;
1038
1039 for (j = 0; j < nhooks; j++) {
1040 PyObject *hook = PyList_GetItem(path_hooks, j);
1041 if (hook == NULL)
1042 return NULL;
1043 importer = PyObject_CallFunction(hook, "O", p);
1044 if (importer != NULL)
1045 break;
1046
1047 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1048 return NULL;
1049 }
1050 PyErr_Clear();
1051 }
1052 if (importer == NULL)
1053 importer = Py_None;
1054 else if (importer != Py_None) {
1055 int err = PyDict_SetItem(path_importer_cache, p, importer);
1056 Py_DECREF(importer);
1057 if (err != 0)
1058 return NULL;
1059 }
1060 return importer;
1061}
1062
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001063/* Search the path (default sys.path) for a module. Return the
1064 corresponding filedescr struct, and (via return arguments) the
1065 pathname and an open file. Return NULL if the module is not found. */
1066
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001067#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001068extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001069 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001070#endif
1071
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001073static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001074static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001075
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001076static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001077find_module(char *fullname, char *subname, PyObject *path, char *buf,
1078 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001079{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001080 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001081 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001082 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001083 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001084 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001085 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001086#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001087 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001088#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001089 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1090 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1091 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001092 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001093#if defined(PYOS_OS2)
1094 size_t saved_len;
1095 size_t saved_namelen;
1096 char *saved_buf = NULL;
1097#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001098 if (p_loader != NULL)
1099 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001100
Just van Rossum52e14d62002-12-30 22:08:05 +00001101 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001102 PyErr_SetString(PyExc_OverflowError,
1103 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001104 return NULL;
1105 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001106 strcpy(name, subname);
1107
1108 /* sys.meta_path import hook */
1109 if (p_loader != NULL) {
1110 PyObject *meta_path;
1111
1112 meta_path = PySys_GetObject("meta_path");
1113 if (meta_path == NULL || !PyList_Check(meta_path)) {
1114 PyErr_SetString(PyExc_ImportError,
1115 "sys.meta_path must be a list of "
1116 "import hooks");
1117 return NULL;
1118 }
1119 Py_INCREF(meta_path); /* zap guard */
1120 npath = PyList_Size(meta_path);
1121 for (i = 0; i < npath; i++) {
1122 PyObject *loader;
1123 PyObject *hook = PyList_GetItem(meta_path, i);
1124 loader = PyObject_CallMethod(hook, "find_module",
1125 "sO", fullname,
1126 path != NULL ?
1127 path : Py_None);
1128 if (loader == NULL) {
1129 Py_DECREF(meta_path);
1130 return NULL; /* true error */
1131 }
1132 if (loader != Py_None) {
1133 /* a loader was found */
1134 *p_loader = loader;
1135 Py_DECREF(meta_path);
1136 return &importhookdescr;
1137 }
1138 Py_DECREF(loader);
1139 }
1140 Py_DECREF(meta_path);
1141 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001142
1143 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001144 /* The only type of submodule allowed inside a "frozen"
1145 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001146 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1147 PyErr_SetString(PyExc_ImportError,
1148 "full frozen module name too long");
1149 return NULL;
1150 }
1151 strcpy(buf, PyString_AsString(path));
1152 strcat(buf, ".");
1153 strcat(buf, name);
1154 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001155 if (find_frozen(name) != NULL) {
1156 strcpy(buf, name);
1157 return &fd_frozen;
1158 }
1159 PyErr_Format(PyExc_ImportError,
1160 "No frozen submodule named %.200s", name);
1161 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001162 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001163 if (path == NULL) {
1164 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001165 strcpy(buf, name);
1166 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001167 }
Greg Ward201baee2001-10-04 14:52:06 +00001168 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001169 strcpy(buf, name);
1170 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001171 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001172
Guido van Rossumac279101996-08-22 23:10:58 +00001173#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001174 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1175 if (fp != NULL) {
1176 *p_fp = fp;
1177 return fdp;
1178 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001179#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001180 path = PySys_GetObject("path");
1181 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001182 if (path == NULL || !PyList_Check(path)) {
1183 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001184 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001185 return NULL;
1186 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001187
1188 path_hooks = PySys_GetObject("path_hooks");
1189 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1190 PyErr_SetString(PyExc_ImportError,
1191 "sys.path_hooks must be a list of "
1192 "import hooks");
1193 return NULL;
1194 }
1195 path_importer_cache = PySys_GetObject("path_importer_cache");
1196 if (path_importer_cache == NULL ||
1197 !PyDict_Check(path_importer_cache)) {
1198 PyErr_SetString(PyExc_ImportError,
1199 "sys.path_importer_cache must be a dict");
1200 return NULL;
1201 }
1202
Guido van Rossum79f25d91997-04-29 20:08:16 +00001203 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001204 namelen = strlen(name);
1205 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001206 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001207 PyObject *v = PyList_GetItem(path, i);
Walter Dörwald3430d702002-06-17 10:43:59 +00001208#ifdef Py_USING_UNICODE
1209 if (PyUnicode_Check(v)) {
1210 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1211 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1212 if (copy == NULL)
1213 return NULL;
1214 v = copy;
1215 }
1216 else
1217#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001218 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001219 continue;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001220 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001221 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1222 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001224 }
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001225 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001226 if (strlen(buf) != len) {
1227 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001228 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001229 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001230
1231 /* sys.path_hooks import hook */
1232 if (p_loader != NULL) {
1233 PyObject *importer;
1234
1235 importer = get_path_importer(path_importer_cache,
1236 path_hooks, v);
1237 if (importer == NULL)
1238 return NULL;
1239 /* Note: importer is a borrowed reference */
1240 if (importer != Py_None) {
1241 PyObject *loader;
1242 loader = PyObject_CallMethod(importer,
1243 "find_module",
1244 "s", fullname);
1245 if (loader == NULL)
1246 return NULL; /* error */
1247 if (loader != Py_None) {
1248 /* a loader was found */
1249 *p_loader = loader;
1250 return &importhookdescr;
1251 }
1252 Py_DECREF(loader);
1253 }
1254 /* no hook was successful, use builtin import */
1255 }
1256
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001257 if (len > 0 && buf[len-1] != SEP
1258#ifdef ALTSEP
1259 && buf[len-1] != ALTSEP
1260#endif
1261 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001262 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001263 strcpy(buf+len, name);
1264 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001265
1266 /* Check for package import (buf holds a directory name,
1267 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001268#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001269 if (stat(buf, &statbuf) == 0 && /* it exists */
1270 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1271 find_init_module(buf) && /* it has __init__.py */
1272 case_ok(buf, len, namelen, name)) { /* and case matches */
1273 Py_XDECREF(copy);
Tim Peterscab3f682001-04-29 22:21:25 +00001274 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001275 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001276#else
1277 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001278#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001279 if (isdir(buf) &&
1280 find_init_module(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001281 case_ok(buf, len, namelen, name)) {
1282 Py_XDECREF(copy);
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001283 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001284 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001285#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001286#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001287#if defined(PYOS_OS2)
1288 /* take a snapshot of the module spec for restoration
1289 * after the 8 character DLL hackery
1290 */
1291 saved_buf = strdup(buf);
1292 saved_len = len;
1293 saved_namelen = namelen;
1294#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001295 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001296#if defined(PYOS_OS2)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001297 /* OS/2 limits DLLs to 8 character names (w/o
1298 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001299 * so if the name is longer than that and its a
1300 * dynamically loaded module we're going to try,
1301 * truncate the name before trying
1302 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001303 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001304 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001305 const struct filedescr *scan;
1306 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001307 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001308 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001309 break;
1310 else
1311 scan++;
1312 }
1313 if (scan->suffix != NULL) {
1314 /* yes, so truncate the name */
1315 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001316 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001317 buf[len] = '\0';
1318 }
1319 }
1320#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001321 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001322 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001323 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001324 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001325 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001326 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001327 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001328 if (fp != NULL) {
1329 if (case_ok(buf, len, namelen, name))
1330 break;
1331 else { /* continue search */
1332 fclose(fp);
1333 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001334 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001335 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001336#if defined(PYOS_OS2)
1337 /* restore the saved snapshot */
1338 strcpy(buf, saved_buf);
1339 len = saved_len;
1340 namelen = saved_namelen;
1341#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001342 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001343#if defined(PYOS_OS2)
1344 /* don't need/want the module name snapshot anymore */
1345 if (saved_buf)
1346 {
1347 free(saved_buf);
1348 saved_buf = NULL;
1349 }
1350#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001351 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001352 if (fp != NULL)
1353 break;
1354 }
1355 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001356 PyErr_Format(PyExc_ImportError,
1357 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001358 return NULL;
1359 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001360 *p_fp = fp;
1361 return fdp;
1362}
1363
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001364/* Helpers for main.c
1365 * Find the source file corresponding to a named module
1366 */
1367struct filedescr *
1368_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1369 size_t buflen, FILE **p_fp, PyObject **p_loader)
1370{
1371 return find_module((char *) name, (char *) name, path,
1372 buf, buflen, p_fp, p_loader);
1373}
1374
1375PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1376{
1377 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1378}
1379
Martin v. Löwis18e16552006-02-15 17:27:45 +00001380/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001381 * The arguments here are tricky, best shown by example:
1382 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1383 * ^ ^ ^ ^
1384 * |--------------------- buf ---------------------|
1385 * |------------------- len ------------------|
1386 * |------ name -------|
1387 * |----- namelen -----|
1388 * buf is the full path, but len only counts up to (& exclusive of) the
1389 * extension. name is the module name, also exclusive of extension.
1390 *
1391 * We've already done a successful stat() or fopen() on buf, so know that
1392 * there's some match, possibly case-insensitive.
1393 *
Tim Peters50d8d372001-02-28 05:34:27 +00001394 * case_ok() is to return 1 if there's a case-sensitive match for
1395 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1396 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001397 *
Tim Peters50d8d372001-02-28 05:34:27 +00001398 * case_ok() is used to implement case-sensitive import semantics even
1399 * on platforms with case-insensitive filesystems. It's trivial to implement
1400 * for case-sensitive filesystems. It's pretty much a cross-platform
1401 * nightmare for systems with case-insensitive filesystems.
1402 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001403
Tim Peters50d8d372001-02-28 05:34:27 +00001404/* First we may need a pile of platform-specific header files; the sequence
1405 * of #if's here should match the sequence in the body of case_ok().
1406 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001407#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001408#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001409
Tim Peters50d8d372001-02-28 05:34:27 +00001410#elif defined(DJGPP)
1411#include <dir.h>
1412
Jason Tishler7961aa62005-05-20 00:56:54 +00001413#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001414#include <sys/types.h>
1415#include <dirent.h>
1416
Andrew MacIntyred9400542002-02-26 11:41:34 +00001417#elif defined(PYOS_OS2)
1418#define INCL_DOS
1419#define INCL_DOSERRORS
1420#define INCL_NOPMAPI
1421#include <os2.h>
1422
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001423#elif defined(RISCOS)
1424#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001425#endif
1426
Guido van Rossum0980bd91998-02-13 17:18:36 +00001427static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001428case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001429{
Tim Peters50d8d372001-02-28 05:34:27 +00001430/* Pick a platform-specific implementation; the sequence of #if's here should
1431 * match the sequence just above.
1432 */
1433
Jason Tishler7961aa62005-05-20 00:56:54 +00001434/* MS_WINDOWS */
1435#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001436 WIN32_FIND_DATA data;
1437 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001438
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001439 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001440 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001441
Guido van Rossum0980bd91998-02-13 17:18:36 +00001442 h = FindFirstFile(buf, &data);
1443 if (h == INVALID_HANDLE_VALUE) {
1444 PyErr_Format(PyExc_NameError,
1445 "Can't find file for module %.100s\n(filename %.300s)",
1446 name, buf);
1447 return 0;
1448 }
1449 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001450 return strncmp(data.cFileName, name, namelen) == 0;
1451
1452/* DJGPP */
1453#elif defined(DJGPP)
1454 struct ffblk ffblk;
1455 int done;
1456
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001457 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001458 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001459
1460 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1461 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001462 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001463 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001464 name, buf);
1465 return 0;
1466 }
Tim Peters50d8d372001-02-28 05:34:27 +00001467 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001468
Jason Tishler7961aa62005-05-20 00:56:54 +00001469/* new-fangled macintosh (macosx) or Cygwin */
1470#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001471 DIR *dirp;
1472 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001473 char dirname[MAXPATHLEN + 1];
1474 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001475
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001476 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001477 return 1;
1478
Tim Petersd1e87a82001-03-01 18:12:00 +00001479 /* Copy the dir component into dirname; substitute "." if empty */
1480 if (dirlen <= 0) {
1481 dirname[0] = '.';
1482 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001483 }
1484 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001485 assert(dirlen <= MAXPATHLEN);
1486 memcpy(dirname, buf, dirlen);
1487 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001488 }
1489 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001490 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001491 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001492 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001493 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001494 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001495#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001496 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001497#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001498 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001499#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001500 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001501 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001502 (void)closedir(dirp);
1503 return 1; /* Found */
1504 }
1505 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001506 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001507 }
Tim Peters430f5d42001-03-01 01:30:56 +00001508 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001509
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001510/* RISC OS */
1511#elif defined(RISCOS)
1512 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1513 char buf2[MAXPATHLEN+2];
1514 char *nameWithExt = buf+len-namelen;
1515 int canonlen;
1516 os_error *e;
1517
1518 if (Py_GETENV("PYTHONCASEOK") != NULL)
1519 return 1;
1520
1521 /* workaround:
1522 append wildcard, otherwise case of filename wouldn't be touched */
1523 strcpy(buf2, buf);
1524 strcat(buf2, "*");
1525
1526 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1527 canonlen = MAXPATHLEN+1-canonlen;
1528 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1529 return 0;
1530 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1531 return 1; /* match */
1532
1533 return 0;
1534
Andrew MacIntyred9400542002-02-26 11:41:34 +00001535/* OS/2 */
1536#elif defined(PYOS_OS2)
1537 HDIR hdir = 1;
1538 ULONG srchcnt = 1;
1539 FILEFINDBUF3 ffbuf;
1540 APIRET rc;
1541
1542 if (getenv("PYTHONCASEOK") != NULL)
1543 return 1;
1544
1545 rc = DosFindFirst(buf,
1546 &hdir,
1547 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1548 &ffbuf, sizeof(ffbuf),
1549 &srchcnt,
1550 FIL_STANDARD);
1551 if (rc != NO_ERROR)
1552 return 0;
1553 return strncmp(ffbuf.achName, name, namelen) == 0;
1554
Tim Peters50d8d372001-02-28 05:34:27 +00001555/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1556#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001557 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001558
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001559#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001560}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001561
Guido van Rossum0980bd91998-02-13 17:18:36 +00001562
Guido van Rossum197346f1997-10-31 18:38:52 +00001563#ifdef HAVE_STAT
1564/* Helper to look for __init__.py or __init__.py[co] in potential package */
1565static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001566find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001567{
Tim Peters0f9431f2001-07-05 03:47:53 +00001568 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001569 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001570 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001571 struct stat statbuf;
1572
Tim Peters0f9431f2001-07-05 03:47:53 +00001573/* For calling case_ok(buf, len, namelen, name):
1574 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1575 * ^ ^ ^ ^
1576 * |--------------------- buf ---------------------|
1577 * |------------------- len ------------------|
1578 * |------ name -------|
1579 * |----- namelen -----|
1580 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001581 if (save_len + 13 >= MAXPATHLEN)
1582 return 0;
1583 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001584 pname = buf + i;
1585 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001586 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001587 if (case_ok(buf,
1588 save_len + 9, /* len("/__init__") */
1589 8, /* len("__init__") */
1590 pname)) {
1591 buf[save_len] = '\0';
1592 return 1;
1593 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001594 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001595 i += strlen(pname);
1596 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001597 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001598 if (case_ok(buf,
1599 save_len + 9, /* len("/__init__") */
1600 8, /* len("__init__") */
1601 pname)) {
1602 buf[save_len] = '\0';
1603 return 1;
1604 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001605 }
1606 buf[save_len] = '\0';
1607 return 0;
1608}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001609
1610#else
1611
1612#ifdef RISCOS
1613static int
1614find_init_module(buf)
1615 char *buf;
1616{
1617 int save_len = strlen(buf);
1618 int i = save_len;
1619
1620 if (save_len + 13 >= MAXPATHLEN)
1621 return 0;
1622 buf[i++] = SEP;
1623 strcpy(buf+i, "__init__/py");
1624 if (isfile(buf)) {
1625 buf[save_len] = '\0';
1626 return 1;
1627 }
1628
1629 if (Py_OptimizeFlag)
1630 strcpy(buf+i, "o");
1631 else
1632 strcpy(buf+i, "c");
1633 if (isfile(buf)) {
1634 buf[save_len] = '\0';
1635 return 1;
1636 }
1637 buf[save_len] = '\0';
1638 return 0;
1639}
1640#endif /*RISCOS*/
1641
Guido van Rossum197346f1997-10-31 18:38:52 +00001642#endif /* HAVE_STAT */
1643
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001644
Tim Petersdbd9ba62000-07-09 03:09:57 +00001645static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001646
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001647/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001648 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001649
Guido van Rossum79f25d91997-04-29 20:08:16 +00001650static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001651load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001652{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001653 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001654 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001655 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001656
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001657 /* First check that there's an open file (if we need one) */
1658 switch (type) {
1659 case PY_SOURCE:
1660 case PY_COMPILED:
1661 if (fp == NULL) {
1662 PyErr_Format(PyExc_ValueError,
1663 "file object required for import (type code %d)",
1664 type);
1665 return NULL;
1666 }
1667 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001668
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001669 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001670
1671 case PY_SOURCE:
1672 m = load_source_module(name, buf, fp);
1673 break;
1674
1675 case PY_COMPILED:
1676 m = load_compiled_module(name, buf, fp);
1677 break;
1678
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001679#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001680 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001681 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001682 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001683#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001684
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001685 case PKG_DIRECTORY:
1686 m = load_package(name, buf);
1687 break;
1688
1689 case C_BUILTIN:
1690 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001691 if (buf != NULL && buf[0] != '\0')
1692 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001693 if (type == C_BUILTIN)
1694 err = init_builtin(name);
1695 else
1696 err = PyImport_ImportFrozenModule(name);
1697 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001698 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001699 if (err == 0) {
1700 PyErr_Format(PyExc_ImportError,
1701 "Purported %s module %.200s not found",
1702 type == C_BUILTIN ?
1703 "builtin" : "frozen",
1704 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001705 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001706 }
1707 modules = PyImport_GetModuleDict();
1708 m = PyDict_GetItemString(modules, name);
1709 if (m == NULL) {
1710 PyErr_Format(
1711 PyExc_ImportError,
1712 "%s module %.200s not properly initialized",
1713 type == C_BUILTIN ?
1714 "builtin" : "frozen",
1715 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001716 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001717 }
1718 Py_INCREF(m);
1719 break;
1720
Just van Rossum52e14d62002-12-30 22:08:05 +00001721 case IMP_HOOK: {
1722 if (loader == NULL) {
1723 PyErr_SetString(PyExc_ImportError,
1724 "import hook without loader");
1725 return NULL;
1726 }
1727 m = PyObject_CallMethod(loader, "load_module", "s", name);
1728 break;
1729 }
1730
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001731 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001732 PyErr_Format(PyExc_ImportError,
1733 "Don't know how to import %.200s (type code %d)",
1734 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001735 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001736
1737 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001738
1739 return m;
1740}
1741
1742
1743/* Initialize a built-in module.
1744 Return 1 for succes, 0 if the module is not found, and -1 with
1745 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001746
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001747static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001748init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001749{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001750 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001751
Greg Ward201baee2001-10-04 14:52:06 +00001752 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001753 return 1;
1754
Guido van Rossum771c6c81997-10-31 18:37:24 +00001755 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001756 if (strcmp(name, p->name) == 0) {
1757 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001758 PyErr_Format(PyExc_ImportError,
1759 "Cannot re-init internal module %.200s",
1760 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001761 return -1;
1762 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001763 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001764 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001765 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001766 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001767 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001768 if (_PyImport_FixupExtension(name, name) == NULL)
1769 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001770 return 1;
1771 }
1772 }
1773 return 0;
1774}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001775
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001777/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001778
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001779static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001780find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001781{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001782 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001783
Guido van Rossum79f25d91997-04-29 20:08:16 +00001784 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001785 if (p->name == NULL)
1786 return NULL;
1787 if (strcmp(p->name, name) == 0)
1788 break;
1789 }
1790 return p;
1791}
1792
Guido van Rossum79f25d91997-04-29 20:08:16 +00001793static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001794get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001795{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001796 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001797 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001798
1799 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001800 PyErr_Format(PyExc_ImportError,
1801 "No such frozen object named %.200s",
1802 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001803 return NULL;
1804 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001805 if (p->code == NULL) {
1806 PyErr_Format(PyExc_ImportError,
1807 "Excluded frozen object named %.200s",
1808 name);
1809 return NULL;
1810 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001811 size = p->size;
1812 if (size < 0)
1813 size = -size;
1814 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001815}
1816
1817/* Initialize a frozen module.
1818 Return 1 for succes, 0 if the module is not found, and -1 with
1819 an exception set if the initialization failed.
1820 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001821
1822int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001823PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001824{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001825 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001826 PyObject *co;
1827 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001828 int ispackage;
1829 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001830
1831 if (p == NULL)
1832 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001833 if (p->code == NULL) {
1834 PyErr_Format(PyExc_ImportError,
1835 "Excluded frozen object named %.200s",
1836 name);
1837 return -1;
1838 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001839 size = p->size;
1840 ispackage = (size < 0);
1841 if (ispackage)
1842 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001843 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001844 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001845 name, ispackage ? " package" : "");
1846 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001847 if (co == NULL)
1848 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001849 if (!PyCode_Check(co)) {
1850 Py_DECREF(co);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001851 PyErr_Format(PyExc_TypeError,
1852 "frozen object %.200s is not a code object",
1853 name);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001854 return -1;
1855 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001856 if (ispackage) {
1857 /* Set __path__ to the package name */
1858 PyObject *d, *s;
1859 int err;
1860 m = PyImport_AddModule(name);
1861 if (m == NULL)
1862 return -1;
1863 d = PyModule_GetDict(m);
1864 s = PyString_InternFromString(name);
1865 if (s == NULL)
1866 return -1;
1867 err = PyDict_SetItemString(d, "__path__", s);
1868 Py_DECREF(s);
1869 if (err != 0)
1870 return err;
1871 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001872 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum79f25d91997-04-29 20:08:16 +00001873 Py_DECREF(co);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001874 if (m == NULL)
1875 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001876 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001877 return 1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001878}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001879
1880
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001881/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001882 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001883
Guido van Rossum79f25d91997-04-29 20:08:16 +00001884PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001885PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001886{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001887 PyObject *pname;
1888 PyObject *result;
1889
1890 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001891 if (pname == NULL)
1892 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001893 result = PyImport_Import(pname);
1894 Py_DECREF(pname);
1895 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001896}
1897
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001898/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001899static PyObject *get_parent(PyObject *globals, char *buf,
1900 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001901static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001902 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001903static int mark_miss(char *name);
1904static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001905 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001906static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001907
1908/* The Magnum Opus of dotted-name import :-) */
1909
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001910static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001911import_module_level(char *name, PyObject *globals, PyObject *locals,
1912 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001913{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001914 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00001915 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001916 PyObject *parent, *head, *next, *tail;
1917
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001918 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001919 if (parent == NULL)
1920 return NULL;
1921
1922 head = load_next(parent, Py_None, &name, buf, &buflen);
1923 if (head == NULL)
1924 return NULL;
1925
1926 tail = head;
1927 Py_INCREF(tail);
1928 while (name) {
1929 next = load_next(tail, tail, &name, buf, &buflen);
1930 Py_DECREF(tail);
1931 if (next == NULL) {
1932 Py_DECREF(head);
1933 return NULL;
1934 }
1935 tail = next;
1936 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00001937 if (tail == Py_None) {
1938 /* If tail is Py_None, both get_parent and load_next found
1939 an empty module name: someone called __import__("") or
1940 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00001941 Py_DECREF(tail);
1942 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00001943 PyErr_SetString(PyExc_ValueError,
1944 "Empty module name");
1945 return NULL;
1946 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001947
1948 if (fromlist != NULL) {
1949 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1950 fromlist = NULL;
1951 }
1952
1953 if (fromlist == NULL) {
1954 Py_DECREF(tail);
1955 return head;
1956 }
1957
1958 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001959 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001960 Py_DECREF(tail);
1961 return NULL;
1962 }
1963
1964 return tail;
1965}
1966
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001967/* For DLL compatibility */
1968#undef PyImport_ImportModuleEx
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001969PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001970PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1971 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001972{
1973 PyObject *result;
1974 lock_import();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001975 result = import_module_level(name, globals, locals, fromlist, -1);
1976 if (unlock_import() < 0) {
1977 Py_XDECREF(result);
1978 PyErr_SetString(PyExc_RuntimeError,
1979 "not holding the import lock");
1980 return NULL;
1981 }
1982 return result;
1983}
1984#define PyImport_ImportModuleEx(n, g, l, f) \
1985 PyImport_ImportModuleLevel(n, g, l, f, -1);
1986
1987PyObject *
1988PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
1989 PyObject *fromlist, int level)
1990{
1991 PyObject *result;
1992 lock_import();
1993 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001994 if (unlock_import() < 0) {
1995 Py_XDECREF(result);
1996 PyErr_SetString(PyExc_RuntimeError,
1997 "not holding the import lock");
1998 return NULL;
1999 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002000 return result;
2001}
2002
Fred Drake87590902004-05-28 20:21:36 +00002003/* Return the package that an import is being performed in. If globals comes
2004 from the module foo.bar.bat (not itself a package), this returns the
2005 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2006 the package's entry in sys.modules is returned.
2007
2008 The *name* of the returned package is returned in buf, with the length of
2009 the name in *p_buflen.
2010
2011 If globals doesn't come from a package or a module in a package, or a
2012 corresponding entry is not found in sys.modules, Py_None is returned.
2013*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002014static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002015get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002016{
2017 static PyObject *namestr = NULL;
2018 static PyObject *pathstr = NULL;
2019 PyObject *modname, *modpath, *modules, *parent;
2020
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002021 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002022 return Py_None;
2023
2024 if (namestr == NULL) {
2025 namestr = PyString_InternFromString("__name__");
2026 if (namestr == NULL)
2027 return NULL;
2028 }
2029 if (pathstr == NULL) {
2030 pathstr = PyString_InternFromString("__path__");
2031 if (pathstr == NULL)
2032 return NULL;
2033 }
2034
2035 *buf = '\0';
2036 *p_buflen = 0;
2037 modname = PyDict_GetItem(globals, namestr);
2038 if (modname == NULL || !PyString_Check(modname))
2039 return Py_None;
2040
2041 modpath = PyDict_GetItem(globals, pathstr);
2042 if (modpath != NULL) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00002043 Py_ssize_t len = PyString_GET_SIZE(modname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002044 if (len > MAXPATHLEN) {
2045 PyErr_SetString(PyExc_ValueError,
2046 "Module name too long");
2047 return NULL;
2048 }
2049 strcpy(buf, PyString_AS_STRING(modname));
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002050 }
2051 else {
2052 char *start = PyString_AS_STRING(modname);
2053 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002054 size_t len;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002055 if (lastdot == NULL && level > 0) {
2056 PyErr_SetString(PyExc_ValueError,
2057 "Relative importpath too deep");
2058 return NULL;
2059 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002060 if (lastdot == NULL)
2061 return Py_None;
2062 len = lastdot - start;
2063 if (len >= MAXPATHLEN) {
2064 PyErr_SetString(PyExc_ValueError,
2065 "Module name too long");
2066 return NULL;
2067 }
2068 strncpy(buf, start, len);
2069 buf[len] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002070 }
2071
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002072 while (--level > 0) {
2073 char *dot = strrchr(buf, '.');
2074 if (dot == NULL) {
2075 PyErr_SetString(PyExc_ValueError,
2076 "Relative importpath too deep");
2077 return NULL;
2078 }
2079 *dot = '\0';
2080 }
2081 *p_buflen = strlen(buf);
2082
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002083 modules = PyImport_GetModuleDict();
2084 parent = PyDict_GetItemString(modules, buf);
2085 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002086 PyErr_Format(PyExc_SystemError,
2087 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002088 return parent;
2089 /* We expect, but can't guarantee, if parent != None, that:
2090 - parent.__name__ == buf
2091 - parent.__dict__ is globals
2092 If this is violated... Who cares? */
2093}
2094
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002095/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002096static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002097load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002098 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002099{
2100 char *name = *p_name;
2101 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002102 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002103 char *p;
2104 PyObject *result;
2105
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002106 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002107 /* completely empty module name should only happen in
2108 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002109 Py_INCREF(mod);
2110 *p_name = NULL;
2111 return mod;
2112 }
2113
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002114 if (dot == NULL) {
2115 *p_name = NULL;
2116 len = strlen(name);
2117 }
2118 else {
2119 *p_name = dot+1;
2120 len = dot-name;
2121 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002122 if (len == 0) {
2123 PyErr_SetString(PyExc_ValueError,
2124 "Empty module name");
2125 return NULL;
2126 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002127
2128 p = buf + *p_buflen;
2129 if (p != buf)
2130 *p++ = '.';
2131 if (p+len-buf >= MAXPATHLEN) {
2132 PyErr_SetString(PyExc_ValueError,
2133 "Module name too long");
2134 return NULL;
2135 }
2136 strncpy(p, name, len);
2137 p[len] = '\0';
2138 *p_buflen = p+len-buf;
2139
2140 result = import_submodule(mod, p, buf);
2141 if (result == Py_None && altmod != mod) {
2142 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002143 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002144 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002145 if (result != NULL && result != Py_None) {
2146 if (mark_miss(buf) != 0) {
2147 Py_DECREF(result);
2148 return NULL;
2149 }
2150 strncpy(buf, name, len);
2151 buf[len] = '\0';
2152 *p_buflen = len;
2153 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002154 }
2155 if (result == NULL)
2156 return NULL;
2157
2158 if (result == Py_None) {
2159 Py_DECREF(result);
2160 PyErr_Format(PyExc_ImportError,
2161 "No module named %.200s", name);
2162 return NULL;
2163 }
2164
2165 return result;
2166}
2167
2168static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002169mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002170{
2171 PyObject *modules = PyImport_GetModuleDict();
2172 return PyDict_SetItemString(modules, name, Py_None);
2173}
2174
2175static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002176ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002177 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002178{
2179 int i;
2180
2181 if (!PyObject_HasAttrString(mod, "__path__"))
2182 return 1;
2183
2184 for (i = 0; ; i++) {
2185 PyObject *item = PySequence_GetItem(fromlist, i);
2186 int hasit;
2187 if (item == NULL) {
2188 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2189 PyErr_Clear();
2190 return 1;
2191 }
2192 return 0;
2193 }
2194 if (!PyString_Check(item)) {
2195 PyErr_SetString(PyExc_TypeError,
2196 "Item in ``from list'' not a string");
2197 Py_DECREF(item);
2198 return 0;
2199 }
2200 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002201 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002202 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002203 /* See if the package defines __all__ */
2204 if (recursive)
2205 continue; /* Avoid endless recursion */
2206 all = PyObject_GetAttrString(mod, "__all__");
2207 if (all == NULL)
2208 PyErr_Clear();
2209 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002210 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002211 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002212 if (!ret)
2213 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002214 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002215 continue;
2216 }
2217 hasit = PyObject_HasAttr(mod, item);
2218 if (!hasit) {
2219 char *subname = PyString_AS_STRING(item);
2220 PyObject *submod;
2221 char *p;
2222 if (buflen + strlen(subname) >= MAXPATHLEN) {
2223 PyErr_SetString(PyExc_ValueError,
2224 "Module name too long");
2225 Py_DECREF(item);
2226 return 0;
2227 }
2228 p = buf + buflen;
2229 *p++ = '.';
2230 strcpy(p, subname);
2231 submod = import_submodule(mod, subname, buf);
2232 Py_XDECREF(submod);
2233 if (submod == NULL) {
2234 Py_DECREF(item);
2235 return 0;
2236 }
2237 }
2238 Py_DECREF(item);
2239 }
2240
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002241 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002242}
2243
Neil Schemenauer00b09662003-06-16 21:03:07 +00002244static int
2245add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2246 PyObject *modules)
2247{
2248 if (mod == Py_None)
2249 return 1;
2250 /* Irrespective of the success of this load, make a
2251 reference to it in the parent package module. A copy gets
2252 saved in the modules dictionary under the full name, so get a
2253 reference from there, if need be. (The exception is when the
2254 load failed with a SyntaxError -- then there's no trace in
2255 sys.modules. In that case, of course, do nothing extra.) */
2256 if (submod == NULL) {
2257 submod = PyDict_GetItemString(modules, fullname);
2258 if (submod == NULL)
2259 return 1;
2260 }
2261 if (PyModule_Check(mod)) {
2262 /* We can't use setattr here since it can give a
2263 * spurious warning if the submodule name shadows a
2264 * builtin name */
2265 PyObject *dict = PyModule_GetDict(mod);
2266 if (!dict)
2267 return 0;
2268 if (PyDict_SetItemString(dict, subname, submod) < 0)
2269 return 0;
2270 }
2271 else {
2272 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2273 return 0;
2274 }
2275 return 1;
2276}
2277
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002278static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002279import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002280{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002281 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002282 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002283
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002284 /* Require:
2285 if mod == None: subname == fullname
2286 else: mod.__name__ + "." + subname == fullname
2287 */
2288
Tim Peters50d8d372001-02-28 05:34:27 +00002289 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002290 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002291 }
2292 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002293 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002294 char buf[MAXPATHLEN+1];
2295 struct filedescr *fdp;
2296 FILE *fp = NULL;
2297
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002298 if (mod == Py_None)
2299 path = NULL;
2300 else {
2301 path = PyObject_GetAttrString(mod, "__path__");
2302 if (path == NULL) {
2303 PyErr_Clear();
2304 Py_INCREF(Py_None);
2305 return Py_None;
2306 }
2307 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002308
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002309 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002310 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2311 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002312 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002313 if (fdp == NULL) {
2314 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2315 return NULL;
2316 PyErr_Clear();
2317 Py_INCREF(Py_None);
2318 return Py_None;
2319 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002320 m = load_module(fullname, fp, buf, fdp->type, loader);
2321 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002322 if (fp)
2323 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002324 if (!add_submodule(mod, m, fullname, subname, modules)) {
2325 Py_XDECREF(m);
2326 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002327 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002328 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002329
2330 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002331}
2332
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002333
2334/* Re-import a module of any kind and return its module object, WITH
2335 INCREMENTED REFERENCE COUNT */
2336
Guido van Rossum79f25d91997-04-29 20:08:16 +00002337PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002338PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002339{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002340 PyObject *modules = PyImport_GetModuleDict();
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002341 PyObject *path = NULL, *loader = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002342 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002343 char buf[MAXPATHLEN+1];
2344 struct filedescr *fdp;
2345 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002346 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002347
Guido van Rossum79f25d91997-04-29 20:08:16 +00002348 if (m == NULL || !PyModule_Check(m)) {
2349 PyErr_SetString(PyExc_TypeError,
2350 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002351 return NULL;
2352 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002353 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002354 if (name == NULL)
2355 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002356 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002357 PyErr_Format(PyExc_ImportError,
2358 "reload(): module %.200s not in sys.modules",
2359 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002360 return NULL;
2361 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002362 subname = strrchr(name, '.');
2363 if (subname == NULL)
2364 subname = name;
2365 else {
2366 PyObject *parentname, *parent;
2367 parentname = PyString_FromStringAndSize(name, (subname-name));
2368 if (parentname == NULL)
2369 return NULL;
2370 parent = PyDict_GetItem(modules, parentname);
2371 if (parent == NULL) {
2372 PyErr_Format(PyExc_ImportError,
2373 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002374 PyString_AS_STRING(parentname));
2375 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002376 return NULL;
2377 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002378 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002379 subname++;
2380 path = PyObject_GetAttrString(parent, "__path__");
2381 if (path == NULL)
2382 PyErr_Clear();
2383 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002384 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002385 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002386 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002387
2388 if (fdp == NULL) {
2389 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002390 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002391 }
2392
2393 newm = load_module(name, fp, buf, fdp->type, loader);
2394 Py_XDECREF(loader);
2395
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002396 if (fp)
2397 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002398 if (newm == NULL) {
2399 /* load_module probably removed name from modules because of
2400 * the error. Put back the original module object. We're
2401 * going to return NULL in this case regardless of whether
2402 * replacing name succeeds, so the return value is ignored.
2403 */
2404 PyDict_SetItemString(modules, name, m);
2405 }
2406 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002407}
2408
2409
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002410/* Higher-level import emulator which emulates the "import" statement
2411 more accurately -- it invokes the __import__() function from the
2412 builtins of the current globals. This means that the import is
2413 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002414 environment, e.g. by "rexec".
2415 A dummy list ["__doc__"] is passed as the 4th argument so that
2416 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2417 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002418
2419PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002420PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002421{
2422 static PyObject *silly_list = NULL;
2423 static PyObject *builtins_str = NULL;
2424 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002425 PyObject *globals = NULL;
2426 PyObject *import = NULL;
2427 PyObject *builtins = NULL;
2428 PyObject *r = NULL;
2429
2430 /* Initialize constant string objects */
2431 if (silly_list == NULL) {
2432 import_str = PyString_InternFromString("__import__");
2433 if (import_str == NULL)
2434 return NULL;
2435 builtins_str = PyString_InternFromString("__builtins__");
2436 if (builtins_str == NULL)
2437 return NULL;
2438 silly_list = Py_BuildValue("[s]", "__doc__");
2439 if (silly_list == NULL)
2440 return NULL;
2441 }
2442
2443 /* Get the builtins from current globals */
2444 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002445 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002446 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002447 builtins = PyObject_GetItem(globals, builtins_str);
2448 if (builtins == NULL)
2449 goto err;
2450 }
2451 else {
2452 /* No globals -- use standard builtins, and fake globals */
2453 PyErr_Clear();
2454
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002455 builtins = PyImport_ImportModuleLevel("__builtin__",
2456 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002457 if (builtins == NULL)
2458 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002459 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2460 if (globals == NULL)
2461 goto err;
2462 }
2463
2464 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002465 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002466 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002467 if (import == NULL)
2468 PyErr_SetObject(PyExc_KeyError, import_str);
2469 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002470 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002471 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002472 if (import == NULL)
2473 goto err;
2474
2475 /* Call the _import__ function with the proper argument list */
2476 r = PyObject_CallFunction(import, "OOOO",
2477 module_name, globals, globals, silly_list);
2478
2479 err:
2480 Py_XDECREF(globals);
2481 Py_XDECREF(builtins);
2482 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002483
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002484 return r;
2485}
2486
2487
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002488/* Module 'imp' provides Python access to the primitives used for
2489 importing modules.
2490*/
2491
Guido van Rossum79f25d91997-04-29 20:08:16 +00002492static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002493imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002494{
2495 char buf[4];
2496
Guido van Rossum96774c12000-05-01 20:19:08 +00002497 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2498 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2499 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2500 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002501
Guido van Rossum79f25d91997-04-29 20:08:16 +00002502 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002503}
2504
Guido van Rossum79f25d91997-04-29 20:08:16 +00002505static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002506imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002507{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002508 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002509 struct filedescr *fdp;
2510
Guido van Rossum79f25d91997-04-29 20:08:16 +00002511 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002512 if (list == NULL)
2513 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002514 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2515 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002516 fdp->suffix, fdp->mode, fdp->type);
2517 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002518 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002519 return NULL;
2520 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002521 if (PyList_Append(list, item) < 0) {
2522 Py_DECREF(list);
2523 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002524 return NULL;
2525 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002526 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002527 }
2528 return list;
2529}
2530
Guido van Rossum79f25d91997-04-29 20:08:16 +00002531static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002532call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002533{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002534 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002535 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002536 struct filedescr *fdp;
2537 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002538 FILE *fp = NULL;
2539
2540 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002541 if (path == Py_None)
2542 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002543 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002544 if (fdp == NULL)
2545 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002546 if (fp != NULL) {
2547 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2548 if (fob == NULL) {
2549 fclose(fp);
2550 return NULL;
2551 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002552 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002553 else {
2554 fob = Py_None;
2555 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002556 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002557 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002558 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002559 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002560 return ret;
2561}
2562
Guido van Rossum79f25d91997-04-29 20:08:16 +00002563static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002564imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002565{
2566 char *name;
2567 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002568 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002569 return NULL;
2570 return call_find_module(name, path);
2571}
2572
2573static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002574imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002575{
2576 char *name;
2577 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002578 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002579 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002580 return NULL;
2581 ret = init_builtin(name);
2582 if (ret < 0)
2583 return NULL;
2584 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002585 Py_INCREF(Py_None);
2586 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002587 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002588 m = PyImport_AddModule(name);
2589 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002590 return m;
2591}
2592
Guido van Rossum79f25d91997-04-29 20:08:16 +00002593static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002594imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002595{
2596 char *name;
2597 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002598 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002599 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002600 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002601 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002602 if (ret < 0)
2603 return NULL;
2604 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002605 Py_INCREF(Py_None);
2606 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002607 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002608 m = PyImport_AddModule(name);
2609 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002610 return m;
2611}
2612
Guido van Rossum79f25d91997-04-29 20:08:16 +00002613static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002614imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002615{
2616 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002617
Guido van Rossum43713e52000-02-29 13:59:29 +00002618 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002619 return NULL;
2620 return get_frozen_object(name);
2621}
2622
Guido van Rossum79f25d91997-04-29 20:08:16 +00002623static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002624imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002625{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002626 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002627 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002628 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002629 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002630}
2631
Guido van Rossum79f25d91997-04-29 20:08:16 +00002632static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002633imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002634{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002635 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002636 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002637 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002638 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002639 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002640 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002641}
2642
2643static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002644get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002645{
2646 FILE *fp;
2647 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002648 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002649 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002650 fp = fopen(pathname, mode);
2651 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002652 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002653 }
2654 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002655 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002656 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002657 PyErr_SetString(PyExc_ValueError,
2658 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002659 }
2660 return fp;
2661}
2662
Guido van Rossum79f25d91997-04-29 20:08:16 +00002663static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002664imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002665{
2666 char *name;
2667 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002668 PyObject *fob = NULL;
2669 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002670 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002671 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002672 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002673 return NULL;
2674 fp = get_file(pathname, fob, "rb");
2675 if (fp == NULL)
2676 return NULL;
2677 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002678 if (fob == NULL)
2679 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002680 return m;
2681}
2682
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002683#ifdef HAVE_DYNAMIC_LOADING
2684
Guido van Rossum79f25d91997-04-29 20:08:16 +00002685static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002686imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002687{
2688 char *name;
2689 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002690 PyObject *fob = NULL;
2691 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002692 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002693 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002694 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002695 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002696 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002697 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002698 if (fp == NULL)
2699 return NULL;
2700 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002701 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002702 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002703}
2704
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002705#endif /* HAVE_DYNAMIC_LOADING */
2706
Guido van Rossum79f25d91997-04-29 20:08:16 +00002707static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002708imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002709{
2710 char *name;
2711 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002712 PyObject *fob = NULL;
2713 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002714 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002715 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002716 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002717 return NULL;
2718 fp = get_file(pathname, fob, "r");
2719 if (fp == NULL)
2720 return NULL;
2721 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002722 if (fob == NULL)
2723 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002724 return m;
2725}
2726
Guido van Rossum79f25d91997-04-29 20:08:16 +00002727static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002728imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002729{
2730 char *name;
2731 PyObject *fob;
2732 char *pathname;
2733 char *suffix; /* Unused */
2734 char *mode;
2735 int type;
2736 FILE *fp;
2737
Guido van Rossum43713e52000-02-29 13:59:29 +00002738 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002739 &name, &fob, &pathname,
2740 &suffix, &mode, &type))
2741 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002742 if (*mode) {
2743 /* Mode must start with 'r' or 'U' and must not contain '+'.
2744 Implicit in this test is the assumption that the mode
2745 may contain other modifiers like 'b' or 't'. */
2746
2747 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002748 PyErr_Format(PyExc_ValueError,
2749 "invalid file open mode %.200s", mode);
2750 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002751 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002752 }
2753 if (fob == Py_None)
2754 fp = NULL;
2755 else {
2756 if (!PyFile_Check(fob)) {
2757 PyErr_SetString(PyExc_ValueError,
2758 "load_module arg#2 should be a file or None");
2759 return NULL;
2760 }
2761 fp = get_file(pathname, fob, mode);
2762 if (fp == NULL)
2763 return NULL;
2764 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002765 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002766}
2767
2768static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002769imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002770{
2771 char *name;
2772 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002773 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002774 return NULL;
2775 return load_package(name, pathname);
2776}
2777
2778static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002779imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002780{
2781 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002782 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002783 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002784 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002785}
2786
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002787/* Doc strings */
2788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002789PyDoc_STRVAR(doc_imp,
2790"This module provides the components needed to build your own\n\
2791__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002793PyDoc_STRVAR(doc_find_module,
2794"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002795Search for a module. If path is omitted or None, search for a\n\
2796built-in, frozen or special module and continue search in sys.path.\n\
2797The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002798package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002800PyDoc_STRVAR(doc_load_module,
2801"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002802Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002803The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002805PyDoc_STRVAR(doc_get_magic,
2806"get_magic() -> string\n\
2807Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002809PyDoc_STRVAR(doc_get_suffixes,
2810"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002811Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002812that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002813
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002814PyDoc_STRVAR(doc_new_module,
2815"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002816Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002817The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002819PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002820"lock_held() -> boolean\n\
2821Return True if the import lock is currently held, else False.\n\
2822On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002823
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002824PyDoc_STRVAR(doc_acquire_lock,
2825"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002826Acquires the interpreter's import lock for the current thread.\n\
2827This lock should be used by import hooks to ensure thread-safety\n\
2828when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002829On platforms without threads, this function does nothing.");
2830
2831PyDoc_STRVAR(doc_release_lock,
2832"release_lock() -> None\n\
2833Release the interpreter's import lock.\n\
2834On platforms without threads, this function does nothing.");
2835
Guido van Rossum79f25d91997-04-29 20:08:16 +00002836static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002837 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2838 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2839 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2840 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2841 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2842 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2843 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2844 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002845 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002846 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2847 {"init_builtin", imp_init_builtin, METH_VARARGS},
2848 {"init_frozen", imp_init_frozen, METH_VARARGS},
2849 {"is_builtin", imp_is_builtin, METH_VARARGS},
2850 {"is_frozen", imp_is_frozen, METH_VARARGS},
2851 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002852#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002853 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002854#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002855 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002856 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002857 {NULL, NULL} /* sentinel */
2858};
2859
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002860static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002861setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002862{
2863 PyObject *v;
2864 int err;
2865
2866 v = PyInt_FromLong((long)value);
2867 err = PyDict_SetItemString(d, name, v);
2868 Py_XDECREF(v);
2869 return err;
2870}
2871
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002872PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002873initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002874{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002875 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002877 m = Py_InitModule4("imp", imp_methods, doc_imp,
2878 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00002879 if (m == NULL)
2880 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002881 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002883 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2884 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2885 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2886 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2887 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2888 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2889 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2890 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002891 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00002892 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002893
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002894 failure:
2895 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002896}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002897
2898
Guido van Rossumb18618d2000-05-03 23:44:39 +00002899/* API for embedding applications that want to add their own entries
2900 to the table of built-in modules. This should normally be called
2901 *before* Py_Initialize(). When the table resize fails, -1 is
2902 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002903
2904 After a similar function by Just van Rossum. */
2905
2906int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002907PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002908{
2909 static struct _inittab *our_copy = NULL;
2910 struct _inittab *p;
2911 int i, n;
2912
2913 /* Count the number of entries in both tables */
2914 for (n = 0; newtab[n].name != NULL; n++)
2915 ;
2916 if (n == 0)
2917 return 0; /* Nothing to do */
2918 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2919 ;
2920
2921 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002922 p = our_copy;
2923 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002924 if (p == NULL)
2925 return -1;
2926
2927 /* Copy the tables into the new memory */
2928 if (our_copy != PyImport_Inittab)
2929 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2930 PyImport_Inittab = our_copy = p;
2931 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2932
2933 return 0;
2934}
2935
2936/* Shorthand to add a single entry given a name and a function */
2937
2938int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002939PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002940{
2941 struct _inittab newtab[2];
2942
2943 memset(newtab, '\0', sizeof newtab);
2944
2945 newtab[0].name = name;
2946 newtab[0].initfunc = initfunc;
2947
2948 return PyImport_ExtendInittab(newtab);
2949}