blob: b64594d8988eda680c9029c3e4499c01ed0124c7 [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
Guido van Rossum45aecf42006-03-15 04:58:47 +000031 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000032 -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
43 Python 2.0: 50823
44 Python 2.0.1: 50823
45 Python 2.1: 60202
46 Python 2.1.1: 60202
47 Python 2.1.2: 60202
48 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000049 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000050 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000051 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000052 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000053 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000054 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000055 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000056 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000057 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000058 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Guido van Rossum45aecf42006-03-15 04:58:47 +000059 Python 3000: 3000
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000060.
Tim Peters36515e22001-11-18 04:06:29 +000061*/
Guido van Rossum45aecf42006-03-15 04:58:47 +000062#define MAGIC (3000 | ((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;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001220 len = PyString_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 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001225 strcpy(buf, PyString_AsString(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 }
1937
1938 if (fromlist != NULL) {
1939 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1940 fromlist = NULL;
1941 }
1942
1943 if (fromlist == NULL) {
1944 Py_DECREF(tail);
1945 return head;
1946 }
1947
1948 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001949 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001950 Py_DECREF(tail);
1951 return NULL;
1952 }
1953
1954 return tail;
1955}
1956
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001957/* For DLL compatibility */
1958#undef PyImport_ImportModuleEx
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001959PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001960PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1961 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001962{
1963 PyObject *result;
1964 lock_import();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001965 result = import_module_level(name, globals, locals, fromlist, -1);
1966 if (unlock_import() < 0) {
1967 Py_XDECREF(result);
1968 PyErr_SetString(PyExc_RuntimeError,
1969 "not holding the import lock");
1970 return NULL;
1971 }
1972 return result;
1973}
1974#define PyImport_ImportModuleEx(n, g, l, f) \
1975 PyImport_ImportModuleLevel(n, g, l, f, -1);
1976
1977PyObject *
1978PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
1979 PyObject *fromlist, int level)
1980{
1981 PyObject *result;
1982 lock_import();
1983 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001984 if (unlock_import() < 0) {
1985 Py_XDECREF(result);
1986 PyErr_SetString(PyExc_RuntimeError,
1987 "not holding the import lock");
1988 return NULL;
1989 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001990 return result;
1991}
1992
Fred Drake87590902004-05-28 20:21:36 +00001993/* Return the package that an import is being performed in. If globals comes
1994 from the module foo.bar.bat (not itself a package), this returns the
1995 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
1996 the package's entry in sys.modules is returned.
1997
1998 The *name* of the returned package is returned in buf, with the length of
1999 the name in *p_buflen.
2000
2001 If globals doesn't come from a package or a module in a package, or a
2002 corresponding entry is not found in sys.modules, Py_None is returned.
2003*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002004static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002005get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002006{
2007 static PyObject *namestr = NULL;
2008 static PyObject *pathstr = NULL;
2009 PyObject *modname, *modpath, *modules, *parent;
2010
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002011 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002012 return Py_None;
2013
2014 if (namestr == NULL) {
2015 namestr = PyString_InternFromString("__name__");
2016 if (namestr == NULL)
2017 return NULL;
2018 }
2019 if (pathstr == NULL) {
2020 pathstr = PyString_InternFromString("__path__");
2021 if (pathstr == NULL)
2022 return NULL;
2023 }
2024
2025 *buf = '\0';
2026 *p_buflen = 0;
2027 modname = PyDict_GetItem(globals, namestr);
2028 if (modname == NULL || !PyString_Check(modname))
2029 return Py_None;
2030
2031 modpath = PyDict_GetItem(globals, pathstr);
2032 if (modpath != NULL) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00002033 Py_ssize_t len = PyString_GET_SIZE(modname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002034 if (len > MAXPATHLEN) {
2035 PyErr_SetString(PyExc_ValueError,
2036 "Module name too long");
2037 return NULL;
2038 }
2039 strcpy(buf, PyString_AS_STRING(modname));
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002040 }
2041 else {
2042 char *start = PyString_AS_STRING(modname);
2043 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002044 size_t len;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002045 if (lastdot == NULL && level > 0) {
2046 PyErr_SetString(PyExc_ValueError,
2047 "Relative importpath too deep");
2048 return NULL;
2049 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002050 if (lastdot == NULL)
2051 return Py_None;
2052 len = lastdot - start;
2053 if (len >= MAXPATHLEN) {
2054 PyErr_SetString(PyExc_ValueError,
2055 "Module name too long");
2056 return NULL;
2057 }
2058 strncpy(buf, start, len);
2059 buf[len] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002060 }
2061
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002062 while (--level > 0) {
2063 char *dot = strrchr(buf, '.');
2064 if (dot == NULL) {
2065 PyErr_SetString(PyExc_ValueError,
2066 "Relative importpath too deep");
2067 return NULL;
2068 }
2069 *dot = '\0';
2070 }
2071 *p_buflen = strlen(buf);
2072
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002073 modules = PyImport_GetModuleDict();
2074 parent = PyDict_GetItemString(modules, buf);
2075 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002076 PyErr_Format(PyExc_SystemError,
2077 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002078 return parent;
2079 /* We expect, but can't guarantee, if parent != None, that:
2080 - parent.__name__ == buf
2081 - parent.__dict__ is globals
2082 If this is violated... Who cares? */
2083}
2084
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002085/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002086static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002087load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002088 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002089{
2090 char *name = *p_name;
2091 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002092 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002093 char *p;
2094 PyObject *result;
2095
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002096 if (strlen(name) == 0) {
2097 /* empty module name only happens in 'from . import' */
2098 Py_INCREF(mod);
2099 *p_name = NULL;
2100 return mod;
2101 }
2102
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002103 if (dot == NULL) {
2104 *p_name = NULL;
2105 len = strlen(name);
2106 }
2107 else {
2108 *p_name = dot+1;
2109 len = dot-name;
2110 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002111 if (len == 0) {
2112 PyErr_SetString(PyExc_ValueError,
2113 "Empty module name");
2114 return NULL;
2115 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002116
2117 p = buf + *p_buflen;
2118 if (p != buf)
2119 *p++ = '.';
2120 if (p+len-buf >= MAXPATHLEN) {
2121 PyErr_SetString(PyExc_ValueError,
2122 "Module name too long");
2123 return NULL;
2124 }
2125 strncpy(p, name, len);
2126 p[len] = '\0';
2127 *p_buflen = p+len-buf;
2128
2129 result = import_submodule(mod, p, buf);
2130 if (result == Py_None && altmod != mod) {
2131 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002132 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002133 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002134 if (result != NULL && result != Py_None) {
2135 if (mark_miss(buf) != 0) {
2136 Py_DECREF(result);
2137 return NULL;
2138 }
2139 strncpy(buf, name, len);
2140 buf[len] = '\0';
2141 *p_buflen = len;
2142 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002143 }
2144 if (result == NULL)
2145 return NULL;
2146
2147 if (result == Py_None) {
2148 Py_DECREF(result);
2149 PyErr_Format(PyExc_ImportError,
2150 "No module named %.200s", name);
2151 return NULL;
2152 }
2153
2154 return result;
2155}
2156
2157static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002158mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002159{
2160 PyObject *modules = PyImport_GetModuleDict();
2161 return PyDict_SetItemString(modules, name, Py_None);
2162}
2163
2164static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002165ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002166 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002167{
2168 int i;
2169
2170 if (!PyObject_HasAttrString(mod, "__path__"))
2171 return 1;
2172
2173 for (i = 0; ; i++) {
2174 PyObject *item = PySequence_GetItem(fromlist, i);
2175 int hasit;
2176 if (item == NULL) {
2177 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2178 PyErr_Clear();
2179 return 1;
2180 }
2181 return 0;
2182 }
2183 if (!PyString_Check(item)) {
2184 PyErr_SetString(PyExc_TypeError,
2185 "Item in ``from list'' not a string");
2186 Py_DECREF(item);
2187 return 0;
2188 }
2189 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002190 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002191 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002192 /* See if the package defines __all__ */
2193 if (recursive)
2194 continue; /* Avoid endless recursion */
2195 all = PyObject_GetAttrString(mod, "__all__");
2196 if (all == NULL)
2197 PyErr_Clear();
2198 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002199 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002200 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002201 if (!ret)
2202 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002203 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002204 continue;
2205 }
2206 hasit = PyObject_HasAttr(mod, item);
2207 if (!hasit) {
2208 char *subname = PyString_AS_STRING(item);
2209 PyObject *submod;
2210 char *p;
2211 if (buflen + strlen(subname) >= MAXPATHLEN) {
2212 PyErr_SetString(PyExc_ValueError,
2213 "Module name too long");
2214 Py_DECREF(item);
2215 return 0;
2216 }
2217 p = buf + buflen;
2218 *p++ = '.';
2219 strcpy(p, subname);
2220 submod = import_submodule(mod, subname, buf);
2221 Py_XDECREF(submod);
2222 if (submod == NULL) {
2223 Py_DECREF(item);
2224 return 0;
2225 }
2226 }
2227 Py_DECREF(item);
2228 }
2229
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002230 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002231}
2232
Neil Schemenauer00b09662003-06-16 21:03:07 +00002233static int
2234add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2235 PyObject *modules)
2236{
2237 if (mod == Py_None)
2238 return 1;
2239 /* Irrespective of the success of this load, make a
2240 reference to it in the parent package module. A copy gets
2241 saved in the modules dictionary under the full name, so get a
2242 reference from there, if need be. (The exception is when the
2243 load failed with a SyntaxError -- then there's no trace in
2244 sys.modules. In that case, of course, do nothing extra.) */
2245 if (submod == NULL) {
2246 submod = PyDict_GetItemString(modules, fullname);
2247 if (submod == NULL)
2248 return 1;
2249 }
2250 if (PyModule_Check(mod)) {
2251 /* We can't use setattr here since it can give a
2252 * spurious warning if the submodule name shadows a
2253 * builtin name */
2254 PyObject *dict = PyModule_GetDict(mod);
2255 if (!dict)
2256 return 0;
2257 if (PyDict_SetItemString(dict, subname, submod) < 0)
2258 return 0;
2259 }
2260 else {
2261 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2262 return 0;
2263 }
2264 return 1;
2265}
2266
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002267static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002268import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002269{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002270 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002271 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002272
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002273 /* Require:
2274 if mod == None: subname == fullname
2275 else: mod.__name__ + "." + subname == fullname
2276 */
2277
Tim Peters50d8d372001-02-28 05:34:27 +00002278 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002279 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002280 }
2281 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002282 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002283 char buf[MAXPATHLEN+1];
2284 struct filedescr *fdp;
2285 FILE *fp = NULL;
2286
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002287 if (mod == Py_None)
2288 path = NULL;
2289 else {
2290 path = PyObject_GetAttrString(mod, "__path__");
2291 if (path == NULL) {
2292 PyErr_Clear();
2293 Py_INCREF(Py_None);
2294 return Py_None;
2295 }
2296 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002297
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002298 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002299 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2300 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002301 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002302 if (fdp == NULL) {
2303 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2304 return NULL;
2305 PyErr_Clear();
2306 Py_INCREF(Py_None);
2307 return Py_None;
2308 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002309 m = load_module(fullname, fp, buf, fdp->type, loader);
2310 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002311 if (fp)
2312 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002313 if (!add_submodule(mod, m, fullname, subname, modules)) {
2314 Py_XDECREF(m);
2315 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002316 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002317 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002318
2319 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002320}
2321
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002322
2323/* Re-import a module of any kind and return its module object, WITH
2324 INCREMENTED REFERENCE COUNT */
2325
Guido van Rossum79f25d91997-04-29 20:08:16 +00002326PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002327PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002328{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002329 PyObject *modules = PyImport_GetModuleDict();
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002330 PyObject *path = NULL, *loader = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002331 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002332 char buf[MAXPATHLEN+1];
2333 struct filedescr *fdp;
2334 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002335 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002336
Guido van Rossum79f25d91997-04-29 20:08:16 +00002337 if (m == NULL || !PyModule_Check(m)) {
2338 PyErr_SetString(PyExc_TypeError,
2339 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002340 return NULL;
2341 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002342 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002343 if (name == NULL)
2344 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002345 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002346 PyErr_Format(PyExc_ImportError,
2347 "reload(): module %.200s not in sys.modules",
2348 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002349 return NULL;
2350 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002351 subname = strrchr(name, '.');
2352 if (subname == NULL)
2353 subname = name;
2354 else {
2355 PyObject *parentname, *parent;
2356 parentname = PyString_FromStringAndSize(name, (subname-name));
2357 if (parentname == NULL)
2358 return NULL;
2359 parent = PyDict_GetItem(modules, parentname);
2360 if (parent == NULL) {
2361 PyErr_Format(PyExc_ImportError,
2362 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002363 PyString_AS_STRING(parentname));
2364 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002365 return NULL;
2366 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002367 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002368 subname++;
2369 path = PyObject_GetAttrString(parent, "__path__");
2370 if (path == NULL)
2371 PyErr_Clear();
2372 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002373 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002374 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002375 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002376
2377 if (fdp == NULL) {
2378 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002379 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002380 }
2381
2382 newm = load_module(name, fp, buf, fdp->type, loader);
2383 Py_XDECREF(loader);
2384
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002385 if (fp)
2386 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002387 if (newm == NULL) {
2388 /* load_module probably removed name from modules because of
2389 * the error. Put back the original module object. We're
2390 * going to return NULL in this case regardless of whether
2391 * replacing name succeeds, so the return value is ignored.
2392 */
2393 PyDict_SetItemString(modules, name, m);
2394 }
2395 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002396}
2397
2398
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002399/* Higher-level import emulator which emulates the "import" statement
2400 more accurately -- it invokes the __import__() function from the
2401 builtins of the current globals. This means that the import is
2402 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002403 environment, e.g. by "rexec".
2404 A dummy list ["__doc__"] is passed as the 4th argument so that
2405 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2406 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002407
2408PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002409PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002410{
2411 static PyObject *silly_list = NULL;
2412 static PyObject *builtins_str = NULL;
2413 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002414 PyObject *globals = NULL;
2415 PyObject *import = NULL;
2416 PyObject *builtins = NULL;
2417 PyObject *r = NULL;
2418
2419 /* Initialize constant string objects */
2420 if (silly_list == NULL) {
2421 import_str = PyString_InternFromString("__import__");
2422 if (import_str == NULL)
2423 return NULL;
2424 builtins_str = PyString_InternFromString("__builtins__");
2425 if (builtins_str == NULL)
2426 return NULL;
2427 silly_list = Py_BuildValue("[s]", "__doc__");
2428 if (silly_list == NULL)
2429 return NULL;
2430 }
2431
2432 /* Get the builtins from current globals */
2433 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002434 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002435 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002436 builtins = PyObject_GetItem(globals, builtins_str);
2437 if (builtins == NULL)
2438 goto err;
2439 }
2440 else {
2441 /* No globals -- use standard builtins, and fake globals */
2442 PyErr_Clear();
2443
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002444 builtins = PyImport_ImportModuleLevel("__builtin__",
2445 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002446 if (builtins == NULL)
2447 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002448 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2449 if (globals == NULL)
2450 goto err;
2451 }
2452
2453 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002455 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002456 if (import == NULL)
2457 PyErr_SetObject(PyExc_KeyError, import_str);
2458 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002459 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002460 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002461 if (import == NULL)
2462 goto err;
2463
2464 /* Call the _import__ function with the proper argument list */
2465 r = PyObject_CallFunction(import, "OOOO",
2466 module_name, globals, globals, silly_list);
2467
2468 err:
2469 Py_XDECREF(globals);
2470 Py_XDECREF(builtins);
2471 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002472
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002473 return r;
2474}
2475
2476
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002477/* Module 'imp' provides Python access to the primitives used for
2478 importing modules.
2479*/
2480
Guido van Rossum79f25d91997-04-29 20:08:16 +00002481static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002482imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002483{
2484 char buf[4];
2485
Guido van Rossum96774c12000-05-01 20:19:08 +00002486 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2487 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2488 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2489 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490
Guido van Rossum79f25d91997-04-29 20:08:16 +00002491 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002492}
2493
Guido van Rossum79f25d91997-04-29 20:08:16 +00002494static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002495imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002496{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002497 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002498 struct filedescr *fdp;
2499
Guido van Rossum79f25d91997-04-29 20:08:16 +00002500 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002501 if (list == NULL)
2502 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002503 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2504 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002505 fdp->suffix, fdp->mode, fdp->type);
2506 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002507 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002508 return NULL;
2509 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002510 if (PyList_Append(list, item) < 0) {
2511 Py_DECREF(list);
2512 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002513 return NULL;
2514 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002515 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002516 }
2517 return list;
2518}
2519
Guido van Rossum79f25d91997-04-29 20:08:16 +00002520static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002521call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002522{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002523 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002524 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002525 struct filedescr *fdp;
2526 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002527 FILE *fp = NULL;
2528
2529 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002530 if (path == Py_None)
2531 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002532 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002533 if (fdp == NULL)
2534 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002535 if (fp != NULL) {
2536 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2537 if (fob == NULL) {
2538 fclose(fp);
2539 return NULL;
2540 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002541 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002542 else {
2543 fob = Py_None;
2544 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002545 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002546 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002547 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002548 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002549 return ret;
2550}
2551
Guido van Rossum79f25d91997-04-29 20:08:16 +00002552static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002553imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002554{
2555 char *name;
2556 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002557 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002558 return NULL;
2559 return call_find_module(name, path);
2560}
2561
2562static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002563imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002564{
2565 char *name;
2566 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002567 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002568 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002569 return NULL;
2570 ret = init_builtin(name);
2571 if (ret < 0)
2572 return NULL;
2573 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002574 Py_INCREF(Py_None);
2575 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002576 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002577 m = PyImport_AddModule(name);
2578 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002579 return m;
2580}
2581
Guido van Rossum79f25d91997-04-29 20:08:16 +00002582static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002583imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002584{
2585 char *name;
2586 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002587 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002588 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002589 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002590 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002591 if (ret < 0)
2592 return NULL;
2593 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002594 Py_INCREF(Py_None);
2595 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002596 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002597 m = PyImport_AddModule(name);
2598 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002599 return m;
2600}
2601
Guido van Rossum79f25d91997-04-29 20:08:16 +00002602static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002603imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002604{
2605 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002606
Guido van Rossum43713e52000-02-29 13:59:29 +00002607 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002608 return NULL;
2609 return get_frozen_object(name);
2610}
2611
Guido van Rossum79f25d91997-04-29 20:08:16 +00002612static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002613imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002614{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002615 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002616 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002617 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002618 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002619}
2620
Guido van Rossum79f25d91997-04-29 20:08:16 +00002621static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002622imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002623{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002624 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002625 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002626 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002627 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002628 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002629 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002630}
2631
2632static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002633get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002634{
2635 FILE *fp;
2636 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002637 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002638 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002639 fp = fopen(pathname, mode);
2640 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002641 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002642 }
2643 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002644 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002645 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002646 PyErr_SetString(PyExc_ValueError,
2647 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002648 }
2649 return fp;
2650}
2651
Guido van Rossum79f25d91997-04-29 20:08:16 +00002652static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002653imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002654{
2655 char *name;
2656 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002657 PyObject *fob = NULL;
2658 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002659 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002660 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002661 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002662 return NULL;
2663 fp = get_file(pathname, fob, "rb");
2664 if (fp == NULL)
2665 return NULL;
2666 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002667 if (fob == NULL)
2668 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002669 return m;
2670}
2671
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002672#ifdef HAVE_DYNAMIC_LOADING
2673
Guido van Rossum79f25d91997-04-29 20:08:16 +00002674static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002675imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002676{
2677 char *name;
2678 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002679 PyObject *fob = NULL;
2680 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002681 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002682 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002683 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002684 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002685 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002686 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002687 if (fp == NULL)
2688 return NULL;
2689 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002690 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002691 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002692}
2693
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002694#endif /* HAVE_DYNAMIC_LOADING */
2695
Guido van Rossum79f25d91997-04-29 20:08:16 +00002696static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002697imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002698{
2699 char *name;
2700 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002701 PyObject *fob = NULL;
2702 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002703 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002704 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002705 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002706 return NULL;
2707 fp = get_file(pathname, fob, "r");
2708 if (fp == NULL)
2709 return NULL;
2710 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002711 if (fob == NULL)
2712 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002713 return m;
2714}
2715
Guido van Rossum79f25d91997-04-29 20:08:16 +00002716static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002717imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002718{
2719 char *name;
2720 PyObject *fob;
2721 char *pathname;
2722 char *suffix; /* Unused */
2723 char *mode;
2724 int type;
2725 FILE *fp;
2726
Guido van Rossum43713e52000-02-29 13:59:29 +00002727 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002728 &name, &fob, &pathname,
2729 &suffix, &mode, &type))
2730 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002731 if (*mode) {
2732 /* Mode must start with 'r' or 'U' and must not contain '+'.
2733 Implicit in this test is the assumption that the mode
2734 may contain other modifiers like 'b' or 't'. */
2735
2736 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002737 PyErr_Format(PyExc_ValueError,
2738 "invalid file open mode %.200s", mode);
2739 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002740 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002741 }
2742 if (fob == Py_None)
2743 fp = NULL;
2744 else {
2745 if (!PyFile_Check(fob)) {
2746 PyErr_SetString(PyExc_ValueError,
2747 "load_module arg#2 should be a file or None");
2748 return NULL;
2749 }
2750 fp = get_file(pathname, fob, mode);
2751 if (fp == NULL)
2752 return NULL;
2753 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002754 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002755}
2756
2757static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002758imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002759{
2760 char *name;
2761 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002762 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002763 return NULL;
2764 return load_package(name, pathname);
2765}
2766
2767static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002768imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002769{
2770 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002771 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002772 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002773 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002774}
2775
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002776/* Doc strings */
2777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002778PyDoc_STRVAR(doc_imp,
2779"This module provides the components needed to build your own\n\
2780__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002782PyDoc_STRVAR(doc_find_module,
2783"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002784Search for a module. If path is omitted or None, search for a\n\
2785built-in, frozen or special module and continue search in sys.path.\n\
2786The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002787package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002789PyDoc_STRVAR(doc_load_module,
2790"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002791Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002792The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002794PyDoc_STRVAR(doc_get_magic,
2795"get_magic() -> string\n\
2796Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002798PyDoc_STRVAR(doc_get_suffixes,
2799"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002800Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002801that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002803PyDoc_STRVAR(doc_new_module,
2804"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002805Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002806The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002808PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002809"lock_held() -> boolean\n\
2810Return True if the import lock is currently held, else False.\n\
2811On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002812
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002813PyDoc_STRVAR(doc_acquire_lock,
2814"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002815Acquires the interpreter's import lock for the current thread.\n\
2816This lock should be used by import hooks to ensure thread-safety\n\
2817when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002818On platforms without threads, this function does nothing.");
2819
2820PyDoc_STRVAR(doc_release_lock,
2821"release_lock() -> None\n\
2822Release the interpreter's import lock.\n\
2823On platforms without threads, this function does nothing.");
2824
Guido van Rossum79f25d91997-04-29 20:08:16 +00002825static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002826 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2827 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2828 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2829 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2830 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2831 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2832 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2833 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002834 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002835 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2836 {"init_builtin", imp_init_builtin, METH_VARARGS},
2837 {"init_frozen", imp_init_frozen, METH_VARARGS},
2838 {"is_builtin", imp_is_builtin, METH_VARARGS},
2839 {"is_frozen", imp_is_frozen, METH_VARARGS},
2840 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002841#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002842 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002843#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002844 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002845 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002846 {NULL, NULL} /* sentinel */
2847};
2848
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002849static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002850setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002851{
2852 PyObject *v;
2853 int err;
2854
2855 v = PyInt_FromLong((long)value);
2856 err = PyDict_SetItemString(d, name, v);
2857 Py_XDECREF(v);
2858 return err;
2859}
2860
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002861PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002862initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002863{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002864 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002865
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002866 m = Py_InitModule4("imp", imp_methods, doc_imp,
2867 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00002868 if (m == NULL)
2869 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002870 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002871
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002872 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2873 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2874 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2875 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2876 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2877 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2878 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2879 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002880 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00002881 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002883 failure:
2884 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002885}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002886
2887
Guido van Rossumb18618d2000-05-03 23:44:39 +00002888/* API for embedding applications that want to add their own entries
2889 to the table of built-in modules. This should normally be called
2890 *before* Py_Initialize(). When the table resize fails, -1 is
2891 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002892
2893 After a similar function by Just van Rossum. */
2894
2895int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002896PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002897{
2898 static struct _inittab *our_copy = NULL;
2899 struct _inittab *p;
2900 int i, n;
2901
2902 /* Count the number of entries in both tables */
2903 for (n = 0; newtab[n].name != NULL; n++)
2904 ;
2905 if (n == 0)
2906 return 0; /* Nothing to do */
2907 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2908 ;
2909
2910 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002911 p = our_copy;
2912 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002913 if (p == NULL)
2914 return -1;
2915
2916 /* Copy the tables into the new memory */
2917 if (our_copy != PyImport_Inittab)
2918 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2919 PyImport_Inittab = our_copy = p;
2920 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2921
2922 return 0;
2923}
2924
2925/* Shorthand to add a single entry given a name and a function */
2926
2927int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002928PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002929{
2930 struct _inittab newtab[2];
2931
2932 memset(newtab, '\0', sizeof newtab);
2933
2934 newtab[0].name = name;
2935 newtab[0].initfunc = initfunc;
2936
2937 return PyImport_ExtendInittab(newtab);
2938}