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