blob: 542a91b9e6c71daa7ccf1ed9a052f946fbf6335a [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020011#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000014
Guido van Rossum55a83382000-09-20 20:31:38 +000015#ifdef HAVE_FCNTL_H
16#include <fcntl.h>
17#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000019extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000021
Barry Warsaw28a691b2010-04-17 00:19:56 +000022#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000023
Victor Stinner95872862011-03-07 18:20:56 +010024/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000025static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Guido van Rossum771c6c81997-10-31 18:37:24 +000027/* This table is defined in config.c: */
28extern struct _inittab _PyImport_Inittab[];
29
30struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000031
Victor Stinnerd0296212011-03-14 14:04:10 -040032static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033
Brett Cannon4caa61d2014-01-09 19:03:32 -050034/*[clinic input]
35module _imp
36[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030037/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040038
39#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050040
Guido van Rossum1ae940a1995-01-02 19:04:15 +000041/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000042
43void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000044_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000045{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020046 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040047 initstr = PyUnicode_InternFromString("__init__");
48 if (initstr == NULL)
49 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020050 interp->builtins_copy = PyDict_Copy(interp->builtins);
51 if (interp->builtins_copy == NULL)
52 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053}
54
Guido van Rossum25ce5661997-08-02 03:10:38 +000055void
Just van Rossum52e14d62002-12-30 22:08:05 +000056_PyImportHooks_Init(void)
57{
Brett Cannonfd074152012-04-14 14:10:13 -040058 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000060
Brett Cannonfd074152012-04-14 14:10:13 -040061 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 v = PyList_New(0);
63 if (v == NULL)
64 goto error;
65 err = PySys_SetObject("meta_path", v);
66 Py_DECREF(v);
67 if (err)
68 goto error;
69 v = PyDict_New();
70 if (v == NULL)
71 goto error;
72 err = PySys_SetObject("path_importer_cache", v);
73 Py_DECREF(v);
74 if (err)
75 goto error;
76 path_hooks = PyList_New(0);
77 if (path_hooks == NULL)
78 goto error;
79 err = PySys_SetObject("path_hooks", path_hooks);
80 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000081 error:
Brett Cannonfd074152012-04-14 14:10:13 -040082 PyErr_Print();
83 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020084 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 }
Brett Cannonfd074152012-04-14 14:10:13 -040086 Py_DECREF(path_hooks);
87}
88
89void
90_PyImportZip_Init(void)
91{
92 PyObject *path_hooks, *zimpimport;
93 int err = 0;
94
95 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020096 if (path_hooks == NULL) {
97 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040098 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +020099 }
Brett Cannonfd074152012-04-14 14:10:13 -0400100
101 if (Py_VerboseFlag)
102 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 zimpimport = PyImport_ImportModule("zipimport");
105 if (zimpimport == NULL) {
106 PyErr_Clear(); /* No zip import module -- okay */
107 if (Py_VerboseFlag)
108 PySys_WriteStderr("# can't import zipimport\n");
109 }
110 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200111 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200112 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
113 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 Py_DECREF(zimpimport);
115 if (zipimporter == NULL) {
116 PyErr_Clear(); /* No zipimporter object -- okay */
117 if (Py_VerboseFlag)
118 PySys_WriteStderr(
119 "# can't import zipimport.zipimporter\n");
120 }
121 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400122 /* sys.path_hooks.insert(0, zipimporter) */
123 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400125 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (Py_VerboseFlag)
129 PySys_WriteStderr(
130 "# installed zipimport hook\n");
131 }
132 }
Brett Cannonfd074152012-04-14 14:10:13 -0400133
134 return;
135
136 error:
137 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400138 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000139}
140
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000141/* Locking primitives to prevent parallel imports of the same module
142 in different threads to return with a partially loaded module.
143 These calls are serialized by the global interpreter lock. */
144
145#ifdef WITH_THREAD
146
Guido van Rossum49b56061998-10-01 20:42:43 +0000147#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148
Guido van Rossum65d5b571998-12-21 19:32:43 +0000149static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200150static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000151static int import_lock_level = 0;
152
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000153void
154_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000155{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200156 unsigned long me = PyThread_get_thread_ident();
157 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 return; /* Too bad */
159 if (import_lock == NULL) {
160 import_lock = PyThread_allocate_lock();
161 if (import_lock == NULL)
162 return; /* Nothing much we can do. */
163 }
164 if (import_lock_thread == me) {
165 import_lock_level++;
166 return;
167 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200168 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
169 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 {
171 PyThreadState *tstate = PyEval_SaveThread();
172 PyThread_acquire_lock(import_lock, 1);
173 PyEval_RestoreThread(tstate);
174 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100175 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 import_lock_thread = me;
177 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000178}
179
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000180int
181_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000182{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200183 unsigned long me = PyThread_get_thread_ident();
184 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return 0; /* Too bad */
186 if (import_lock_thread != me)
187 return -1;
188 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100189 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200191 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyThread_release_lock(import_lock);
193 }
194 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000195}
196
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200197/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000198 created child processes do not share locks with the parent.
199 We now acquire the import lock around fork() calls but on some platforms
200 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000201
202void
203_PyImport_ReInitLock(void)
204{
Christian Heimes418fd742015-04-19 21:08:42 +0200205 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200207 if (import_lock == NULL) {
208 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
209 }
210 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000211 if (import_lock_level > 1) {
212 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200213 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500214 /* The following could fail if the lock is already held, but forking as
215 a side-effect of an import is a) rare, b) nuts, and c) difficult to
216 do thanks to the lock only being held when doing individual module
217 locks per import. */
218 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000219 import_lock_thread = me;
220 import_lock_level--;
221 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200222 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000223 import_lock_level = 0;
224 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000225}
226
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000227#endif
228
Brett Cannon4caa61d2014-01-09 19:03:32 -0500229/*[clinic input]
230_imp.lock_held
231
232Return True if the import lock is currently held, else False.
233
234On platforms without threads, return False.
235[clinic start generated code]*/
236
Brett Cannon4caa61d2014-01-09 19:03:32 -0500237static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300238_imp_lock_held_impl(PyObject *module)
239/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000240{
Tim Peters69232342001-08-30 05:16:13 +0000241#ifdef WITH_THREAD
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200242 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000243#else
Serhiy Storchaka370fd202017-03-08 20:47:48 +0200244 Py_RETURN_FALSE;
Tim Peters69232342001-08-30 05:16:13 +0000245#endif
246}
247
Brett Cannon4caa61d2014-01-09 19:03:32 -0500248/*[clinic input]
249_imp.acquire_lock
250
251Acquires the interpreter's import lock for the current thread.
252
253This lock should be used by import hooks to ensure thread-safety when importing
254modules. On platforms without threads, this function does nothing.
255[clinic start generated code]*/
256
Brett Cannon4caa61d2014-01-09 19:03:32 -0500257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300258_imp_acquire_lock_impl(PyObject *module)
259/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000260{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000261#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 _PyImport_AcquireLock();
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000263#endif
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200264 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265}
266
Brett Cannon4caa61d2014-01-09 19:03:32 -0500267/*[clinic input]
268_imp.release_lock
269
270Release the interpreter's import lock.
271
272On platforms without threads, this function does nothing.
273[clinic start generated code]*/
274
Brett Cannon4caa61d2014-01-09 19:03:32 -0500275static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300276_imp_release_lock_impl(PyObject *module)
277/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000278{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000279#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (_PyImport_ReleaseLock() < 0) {
281 PyErr_SetString(PyExc_RuntimeError,
282 "not holding the import lock");
283 return NULL;
284 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000285#endif
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200286 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000287}
288
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100289void
290_PyImport_Fini(void)
291{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200292 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100293#ifdef WITH_THREAD
294 if (import_lock != NULL) {
295 PyThread_free_lock(import_lock);
296 import_lock = NULL;
297 }
298#endif
299}
300
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301/* Helper for sys */
302
303PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000304PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305{
Eric Snow86b7afd2017-09-04 17:54:09 -0600306 PyObject *sysdict = PyThreadState_GET()->interp->sysdict;
307 if (sysdict == NULL) {
308 Py_FatalError("PyImport_GetModuleDict: no sys module!");
309 }
310
311 _Py_IDENTIFIER(modules);
312 PyObject *modules = _PyDict_GetItemId(sysdict, &PyId_modules);
313 if (modules == NULL) {
314 Py_FatalError("lost sys.modules");
315 }
316 return modules;
317}
318
319/* In some corner cases it is important to be sure that the import
320 machinery has been initialized (or not cleaned up yet). For
321 example, see issue #4236 and PyModule_Create2(). */
322
323int
324_PyImport_IsInitialized(PyInterpreterState *interp)
325{
326 if (interp->sysdict == NULL)
327 return 0;
328 _Py_IDENTIFIER(modules);
329 PyObject *modules = _PyDict_GetItemId(interp->sysdict, &PyId_modules);
330 if (modules == NULL)
331 return 0;
332 return 1;
333}
334
335PyObject *
336_PyImport_GetModule(PyObject *name)
337{
338 PyObject *modules = PyImport_GetModuleDict();
339 if (PyDict_CheckExact(modules)) {
340 return PyDict_GetItem(modules, name);
341 }
342
343 PyObject *mod = PyObject_GetItem(modules, name);
344 // For backward-comaptibility we copy the behavior of PyDict_GetItem().
345 if (PyErr_Occurred()) {
346 PyErr_Clear();
347 }
348 Py_XDECREF(mod);
349 return mod;
350}
351
352PyObject *
353_PyImport_GetModuleWithError(PyObject *name)
354{
355 PyObject *modules = PyImport_GetModuleDict();
356 if (PyDict_CheckExact(modules)) {
357 return PyDict_GetItemWithError(modules, name);
358 }
359
360 PyObject *mod = PyObject_GetItem(modules, name);
361 // For backward-comaptibility we copy the behavior
362 // of PyDict_GetItemWithError().
363 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
364 PyErr_Clear();
365 }
366 return mod;
367}
368
369PyObject *
370_PyImport_GetModuleId(struct _Py_Identifier *nameid)
371{
372 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
373 if (name == NULL) {
374 return NULL;
375 }
376 return _PyImport_GetModule(name);
377}
378
379int
380_PyImport_SetModule(PyObject *name, PyObject *m)
381{
382 PyObject *modules = PyImport_GetModuleDict();
383 return PyObject_SetItem(modules, name, m);
384}
385
386int
387_PyImport_SetModuleString(const char *name, PyObject *m)
388{
389 PyObject *modules = PyImport_GetModuleDict();
390 return PyMapping_SetItemString(modules, name, m);
391}
392
393PyObject *
394PyImport_GetModule(PyObject *name)
395{
396 PyObject *m;
397 PyObject *modules = PyImport_GetModuleDict();
398 if (modules == NULL) {
399 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
400 return NULL;
401 }
402 Py_INCREF(modules);
403 if (PyDict_CheckExact(modules)) {
404 m = PyDict_GetItemWithError(modules, name); /* borrowed */
405 Py_XINCREF(m);
406 }
407 else {
408 m = PyObject_GetItem(modules, name);
409 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
410 PyErr_Clear();
411 }
412 }
413 Py_DECREF(modules);
414 return m;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000415}
416
Guido van Rossum3f5da241990-12-20 15:06:42 +0000417
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000418/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200419static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 "path", "argv", "ps1", "ps2",
421 "last_type", "last_value", "last_traceback",
422 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200423 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* misc stuff */
425 "flags", "float_info",
426 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000427};
428
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200429static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 "stdin", "__stdin__",
431 "stdout", "__stdout__",
432 "stderr", "__stderr__",
433 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000434};
435
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000436/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000437
Guido van Rossum3f5da241990-12-20 15:06:42 +0000438void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000439PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000440{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200441 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyObject *key, *value, *dict;
443 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow86b7afd2017-09-04 17:54:09 -0600444 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200445 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200446 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (modules == NULL)
449 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* Delete some special variables first. These are common
452 places where user values hide and people complain when their
453 destructors fail. Since the modules containing them are
454 deleted *last* of all, they would come too late in the normal
455 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000456
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200457 /* XXX Perhaps these precautions are obsolete. Who knows? */
458
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200459 if (Py_VerboseFlag)
460 PySys_WriteStderr("# clear builtins._\n");
461 PyDict_SetItemString(interp->builtins, "_", Py_None);
462
463 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200465 PySys_WriteStderr("# clear sys.%s\n", *p);
466 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200468 for (p = sys_files; *p != NULL; p+=2) {
469 if (Py_VerboseFlag)
470 PySys_WriteStderr("# restore sys.%s\n", *p);
471 value = PyDict_GetItemString(interp->sysdict, *(p+1));
472 if (value == NULL)
473 value = Py_None;
474 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000476
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200477 /* We prepare a list which will receive (name, weakref) tuples of
478 modules when they are removed from sys.modules. The name is used
479 for diagnosis messages (in verbose mode), while the weakref helps
480 detect those modules which have been held alive. */
481 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200482 if (weaklist == NULL)
483 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200484
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200485#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200486 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200487 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
488 if (name && wr) { \
489 PyObject *tup = PyTuple_Pack(2, name, wr); \
490 PyList_Append(weaklist, tup); \
491 Py_XDECREF(tup); \
492 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200493 Py_XDECREF(wr); \
494 if (PyErr_Occurred()) \
495 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000497
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200498 /* Remove all modules from sys.modules, hoping that garbage collection
499 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 pos = 0;
501 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200502 if (PyModule_Check(value)) {
503 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200504 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200505 STORE_MODULE_WEAKREF(key, value);
Eric Snow86b7afd2017-09-04 17:54:09 -0600506 PyObject_SetItem(modules, key, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 }
508 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000509
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200510 /* Clear the modules dict. */
511 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200512 /* Restore the original builtins dict, to ensure that any
513 user data gets cleared. */
514 dict = PyDict_Copy(interp->builtins);
515 if (dict == NULL)
516 PyErr_Clear();
517 PyDict_Clear(interp->builtins);
518 if (PyDict_Update(interp->builtins, interp->builtins_copy))
519 PyErr_Clear();
520 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200521 /* Clear module dict copies stored in the interpreter state */
522 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200523 /* Collect references */
524 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200525 /* Dump GC stats before it's too late, since it uses the warnings
526 machinery. */
527 _PyGC_DumpShutdownStats();
528
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200529 /* Now, if there are any modules left alive, clear their globals to
530 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200531 up here, since they are kept alive in the interpreter state.
532
533 The special treatment of "builtins" here is because even
534 when it's not referenced as a module, its dictionary is
535 referenced by almost every module's __builtins__. Since
536 deleting a module clears its dictionary (even if there are
537 references left to it), we need to delete the "builtins"
538 module last. Likewise, we don't delete sys until the very
539 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200540 if (weaklist != NULL) {
541 Py_ssize_t i, n;
542 n = PyList_GET_SIZE(weaklist);
543 for (i = 0; i < n; i++) {
544 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200545 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200546 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
547 if (mod == Py_None)
548 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200549 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200550 dict = PyModule_GetDict(mod);
551 if (dict == interp->builtins || dict == interp->sysdict)
552 continue;
553 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200554 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200555 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200556 _PyModule_Clear(mod);
557 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200558 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200559 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000561
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200562 /* Next, delete sys and builtins (in that order) */
563 if (Py_VerboseFlag)
564 PySys_FormatStderr("# cleanup[3] wiping sys\n");
565 _PyModule_ClearDict(interp->sysdict);
566 if (Py_VerboseFlag)
567 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
568 _PyModule_ClearDict(interp->builtins);
569
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200570 /* Clear and delete the modules directory. Actual modules will
571 still be there only if imported during the execution of some
572 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200574
575 /* Once more */
576 _PyGC_CollectNoFail();
577
578#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000579}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000580
581
Barry Warsaw28a691b2010-04-17 00:19:56 +0000582/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000583
584long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000585PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000586{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200587 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400588 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600589 PyObject *external, *pyc_magic;
590
591 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
592 if (external == NULL)
593 return -1;
594 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
595 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400596 if (pyc_magic == NULL)
597 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200598 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700599 Py_DECREF(pyc_magic);
600 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000601}
602
603
Brett Cannon3adc7b72012-07-09 14:22:12 -0400604extern const char * _PySys_ImplCacheTag;
605
Barry Warsaw28a691b2010-04-17 00:19:56 +0000606const char *
607PyImport_GetMagicTag(void)
608{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400609 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000610}
611
Brett Cannon98979b82012-07-02 15:13:11 -0400612
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613/* Magic for extension modules (built-in as well as dynamically
614 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200615 once, we keep a static dictionary 'extensions' keyed by the tuple
616 (module name, module name) (for built-in modules) or by
617 (filename, module name) (for dynamically loaded modules), containing these
618 modules. A copy of the module's dictionary is stored by calling
619 _PyImport_FixupExtensionObject() immediately after the module initialization
620 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100621 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000622
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000623 Modules which do support multiple initialization set their m_size
624 field to a non-negative number (indicating the size of the
625 module-specific state). They are still recorded in the extensions
626 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000627*/
628
629int
Victor Stinner95872862011-03-07 18:20:56 +0100630_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snow86b7afd2017-09-04 17:54:09 -0600631 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000632{
Eric Snow86b7afd2017-09-04 17:54:09 -0600633 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500635 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (extensions == NULL) {
637 extensions = PyDict_New();
638 if (extensions == NULL)
639 return -1;
640 }
641 if (mod == NULL || !PyModule_Check(mod)) {
642 PyErr_BadInternalCall();
643 return -1;
644 }
645 def = PyModule_GetDef(mod);
646 if (!def) {
647 PyErr_BadInternalCall();
648 return -1;
649 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600650 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return -1;
652 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow86b7afd2017-09-04 17:54:09 -0600653 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return -1;
655 }
656 if (def->m_size == -1) {
657 if (def->m_base.m_copy) {
658 /* Somebody already imported the module,
659 likely under a different name.
660 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200661 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 }
663 dict = PyModule_GetDict(mod);
664 if (dict == NULL)
665 return -1;
666 def->m_base.m_copy = PyDict_Copy(dict);
667 if (def->m_base.m_copy == NULL)
668 return -1;
669 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500670 key = PyTuple_Pack(2, filename, name);
671 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200672 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500673 res = PyDict_SetItem(extensions, key, (PyObject *)def);
674 Py_DECREF(key);
675 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200676 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678}
679
Victor Stinner49d3f252010-10-17 01:24:53 +0000680int
Eric Snow86b7afd2017-09-04 17:54:09 -0600681_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000682{
683 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100684 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100685 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100686 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000687 return -1;
Eric Snow86b7afd2017-09-04 17:54:09 -0600688 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100689 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000690 return res;
691}
692
Guido van Rossum25ce5661997-08-02 03:10:38 +0000693PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100694_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000695{
Eric Snow86b7afd2017-09-04 17:54:09 -0600696 PyObject *modules = PyImport_GetModuleDict();
697 return _PyImport_FindExtensionObjectEx(name, filename, modules);
698}
699
700PyObject *
701_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
702 PyObject *modules)
703{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500704 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyModuleDef* def;
706 if (extensions == NULL)
707 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500708 key = PyTuple_Pack(2, filename, name);
709 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200710 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500711 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
712 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (def == NULL)
714 return NULL;
715 if (def->m_size == -1) {
716 /* Module does not support repeated initialization */
717 if (def->m_base.m_copy == NULL)
718 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600719 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (mod == NULL)
721 return NULL;
722 mdict = PyModule_GetDict(mod);
723 if (mdict == NULL)
724 return NULL;
725 if (PyDict_Update(mdict, def->m_base.m_copy))
726 return NULL;
727 }
728 else {
729 if (def->m_base.m_init == NULL)
730 return NULL;
731 mod = def->m_base.m_init();
732 if (mod == NULL)
733 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600734 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200735 Py_DECREF(mod);
736 return NULL;
737 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 Py_DECREF(mod);
739 }
740 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow86b7afd2017-09-04 17:54:09 -0600741 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 Py_DECREF(mod);
743 return NULL;
744 }
745 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100746 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 name, filename);
748 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000749
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750}
751
Victor Stinner49d3f252010-10-17 01:24:53 +0000752PyObject *
Eric Snow86b7afd2017-09-04 17:54:09 -0600753_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000754{
Victor Stinner95872862011-03-07 18:20:56 +0100755 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100756 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100757 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000758 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600759 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100760 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000761 return res;
762}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763
764/* Get the module object corresponding to a module name.
765 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000766 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000767 Because the former action is most common, THIS DOES NOT RETURN A
768 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769
Guido van Rossum79f25d91997-04-29 20:08:16 +0000770PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000771PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 PyObject *modules = PyImport_GetModuleDict();
Eric Snow86b7afd2017-09-04 17:54:09 -0600774 return _PyImport_AddModuleObject(name, modules);
775}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000776
Eric Snow86b7afd2017-09-04 17:54:09 -0600777PyObject *
778_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
779{
780 PyObject *m;
781 if (PyDict_CheckExact(modules)) {
782 m = PyDict_GetItemWithError(modules, name);
783 }
784 else {
785 m = PyObject_GetItem(modules, name);
786 // For backward-comaptibility we copy the behavior
787 // of PyDict_GetItemWithError().
788 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
789 PyErr_Clear();
790 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200791 }
792 if (PyErr_Occurred()) {
793 return NULL;
794 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600795 if (m != NULL && PyModule_Check(m)) {
796 return m;
797 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000798 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (m == NULL)
800 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600801 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 Py_DECREF(m);
803 return NULL;
804 }
805 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000808}
809
Victor Stinner27ee0892011-03-04 12:57:09 +0000810PyObject *
811PyImport_AddModule(const char *name)
812{
813 PyObject *nameobj, *module;
814 nameobj = PyUnicode_FromString(name);
815 if (nameobj == NULL)
816 return NULL;
817 module = PyImport_AddModuleObject(nameobj);
818 Py_DECREF(nameobj);
819 return module;
820}
821
822
Tim Peters1cd70172004-08-02 03:52:12 +0000823/* Remove name from sys.modules, if it's there. */
824static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000825remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *modules = PyImport_GetModuleDict();
Eric Snow86b7afd2017-09-04 17:54:09 -0600828 if (PyMapping_DelItem(modules, name) < 0) {
829 if (!PyMapping_HasKey(modules, name)) {
830 return;
831 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_FatalError("import: deleting existing key in"
833 "sys.modules failed");
Eric Snow86b7afd2017-09-04 17:54:09 -0600834 }
Tim Peters1cd70172004-08-02 03:52:12 +0000835}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836
Christian Heimes3b06e532008-01-07 20:12:44 +0000837
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000838/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000839 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
840 * removed from sys.modules, to avoid leaving damaged module objects
841 * in sys.modules. The caller may wish to restore the original
842 * module object (if any) in this case; PyImport_ReloadModule is an
843 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000844 *
845 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
846 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000847 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000848PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300849PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 return PyImport_ExecCodeModuleWithPathnames(
852 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000853}
854
855PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300856PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return PyImport_ExecCodeModuleWithPathnames(
859 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000860}
861
862PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300863PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
864 const char *pathname,
865 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000866{
Victor Stinner27ee0892011-03-04 12:57:09 +0000867 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600868 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000869
870 nameobj = PyUnicode_FromString(name);
871 if (nameobj == NULL)
872 return NULL;
873
Victor Stinner27ee0892011-03-04 12:57:09 +0000874 if (cpathname != NULL) {
875 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
876 if (cpathobj == NULL)
877 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400878 }
879 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000880 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400881
882 if (pathname != NULL) {
883 pathobj = PyUnicode_DecodeFSDefault(pathname);
884 if (pathobj == NULL)
885 goto error;
886 }
887 else if (cpathobj != NULL) {
888 PyInterpreterState *interp = PyThreadState_GET()->interp;
889 _Py_IDENTIFIER(_get_sourcefile);
890
891 if (interp == NULL) {
892 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
893 "no interpreter!");
894 }
895
Eric Snow32439d62015-05-02 19:15:18 -0600896 external= PyObject_GetAttrString(interp->importlib,
897 "_bootstrap_external");
898 if (external != NULL) {
899 pathobj = _PyObject_CallMethodIdObjArgs(external,
900 &PyId__get_sourcefile, cpathobj,
901 NULL);
902 Py_DECREF(external);
903 }
Brett Cannona6473f92012-07-13 13:57:03 -0400904 if (pathobj == NULL)
905 PyErr_Clear();
906 }
907 else
908 pathobj = NULL;
909
Victor Stinner27ee0892011-03-04 12:57:09 +0000910 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
911error:
912 Py_DECREF(nameobj);
913 Py_XDECREF(pathobj);
914 Py_XDECREF(cpathobj);
915 return m;
916}
917
Brett Cannon18fc4e72014-04-04 10:01:46 -0400918static PyObject *
919module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000920{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400921 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000922
Victor Stinner27ee0892011-03-04 12:57:09 +0000923 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (m == NULL)
925 return NULL;
926 /* If the module is being reloaded, we get the old module back
927 and re-use its dict to exec the new code. */
928 d = PyModule_GetDict(m);
929 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
930 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400931 PyEval_GetBuiltins()) != 0) {
932 remove_module(name);
933 return NULL;
934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400936
Eric Snow08197a42014-05-12 17:54:55 -0600937 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400938}
939
940static PyObject *
941exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
942{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400943 PyObject *v, *m;
944
945 v = PyEval_EvalCode(code_object, module_dict, module_dict);
946 if (v == NULL) {
947 remove_module(name);
948 return NULL;
949 }
950 Py_DECREF(v);
951
Eric Snow86b7afd2017-09-04 17:54:09 -0600952 m = _PyImport_GetModule(name);
953 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400954 PyErr_Format(PyExc_ImportError,
955 "Loaded module %R not found in sys.modules",
956 name);
957 return NULL;
958 }
959
960 Py_INCREF(m);
961
962 return m;
963}
964
965PyObject*
966PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
967 PyObject *cpathname)
968{
Eric Snow32439d62015-05-02 19:15:18 -0600969 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600970 PyInterpreterState *interp = PyThreadState_GET()->interp;
971 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400972
973 d = module_dict_for_exec(name);
974 if (d == NULL) {
975 return NULL;
976 }
977
Eric Snow08197a42014-05-12 17:54:55 -0600978 if (pathname == NULL) {
979 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 }
Eric Snow32439d62015-05-02 19:15:18 -0600981 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
982 if (external == NULL)
983 return NULL;
984 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600985 &PyId__fix_up_module,
986 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600987 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600988 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600989 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600990 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 }
Eric Snow08197a42014-05-12 17:54:55 -0600992 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000993}
994
995
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000996static void
997update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *constants, *tmp;
1000 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (PyUnicode_Compare(co->co_filename, oldname))
1003 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001004
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001005 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001006 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 constants = co->co_consts;
1009 n = PyTuple_GET_SIZE(constants);
1010 for (i = 0; i < n; i++) {
1011 tmp = PyTuple_GET_ITEM(constants, i);
1012 if (PyCode_Check(tmp))
1013 update_code_filenames((PyCodeObject *)tmp,
1014 oldname, newname);
1015 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001016}
1017
Victor Stinner2f42ae52011-03-20 00:41:24 +01001018static void
1019update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001020{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001021 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001022
Victor Stinner2f42ae52011-03-20 00:41:24 +01001023 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1024 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 oldname = co->co_filename;
1027 Py_INCREF(oldname);
1028 update_code_filenames(co, oldname, newname);
1029 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001030}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001031
Brett Cannon4caa61d2014-01-09 19:03:32 -05001032/*[clinic input]
1033_imp._fix_co_filename
1034
1035 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1036 Code object to change.
1037
1038 path: unicode
1039 File path to use.
1040 /
1041
1042Changes code.co_filename to specify the passed-in file path.
1043[clinic start generated code]*/
1044
Brett Cannon4caa61d2014-01-09 19:03:32 -05001045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001046_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001047 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001048/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001049
Brett Cannon4caa61d2014-01-09 19:03:32 -05001050{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001051 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001052
1053 Py_RETURN_NONE;
1054}
1055
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001056
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001057/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001058static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001059
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001060
1061/* Helper to test for built-in module */
1062
1063static int
Victor Stinner95872862011-03-07 18:20:56 +01001064is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001065{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001066 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001068 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 if (PyImport_Inittab[i].initfunc == NULL)
1070 return -1;
1071 else
1072 return 1;
1073 }
1074 }
1075 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001076}
1077
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001078
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001079/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001080 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001081 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001082 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001083 this tells our caller that the path based finder could not find
1084 a finder for this path item. Cache the result in
1085 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001086 Returns a borrowed reference. */
1087
1088static PyObject *
1089get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *importer;
1093 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* These conditions are the caller's responsibility: */
1096 assert(PyList_Check(path_hooks));
1097 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 nhooks = PyList_Size(path_hooks);
1100 if (nhooks < 0)
1101 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 importer = PyDict_GetItem(path_importer_cache, p);
1104 if (importer != NULL)
1105 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 /* set path_importer_cache[p] to None to avoid recursion */
1108 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1109 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 for (j = 0; j < nhooks; j++) {
1112 PyObject *hook = PyList_GetItem(path_hooks, j);
1113 if (hook == NULL)
1114 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001115 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (importer != NULL)
1117 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1120 return NULL;
1121 }
1122 PyErr_Clear();
1123 }
1124 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001125 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
1127 if (importer != NULL) {
1128 int err = PyDict_SetItem(path_importer_cache, p, importer);
1129 Py_DECREF(importer);
1130 if (err != 0)
1131 return NULL;
1132 }
1133 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001134}
1135
Christian Heimes9cd17752007-11-18 19:35:23 +00001136PyAPI_FUNC(PyObject *)
1137PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001139
Victor Stinner1e53bba2013-07-16 22:26:05 +02001140 path_importer_cache = PySys_GetObject("path_importer_cache");
1141 path_hooks = PySys_GetObject("path_hooks");
1142 if (path_importer_cache != NULL && path_hooks != NULL) {
1143 importer = get_path_importer(path_importer_cache,
1144 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 }
1146 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1147 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001148}
1149
Nick Coghland5cacbb2015-05-23 22:24:10 +10001150/*[clinic input]
1151_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001152
Nick Coghland5cacbb2015-05-23 22:24:10 +10001153 spec: object
1154 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001155
Nick Coghland5cacbb2015-05-23 22:24:10 +10001156Create an extension module.
1157[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001158
Nick Coghland5cacbb2015-05-23 22:24:10 +10001159static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001160_imp_create_builtin(PyObject *module, PyObject *spec)
1161/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001164 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001165 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001166 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001167
Nick Coghland5cacbb2015-05-23 22:24:10 +10001168 name = PyObject_GetAttrString(spec, "name");
1169 if (name == NULL) {
1170 return NULL;
1171 }
1172
Victor Stinner5eb4f592013-11-14 22:38:52 +01001173 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001174 if (mod || PyErr_Occurred()) {
1175 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001176 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001177 return mod;
1178 }
1179
1180 namestr = PyUnicode_AsUTF8(name);
1181 if (namestr == NULL) {
1182 Py_DECREF(name);
1183 return NULL;
1184 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001185
Eric Snow86b7afd2017-09-04 17:54:09 -06001186 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001188 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001189 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001191 /* Cannot re-init internal module ("sys" or "builtins") */
1192 mod = PyImport_AddModule(namestr);
1193 Py_DECREF(name);
1194 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001197 if (mod == NULL) {
1198 Py_DECREF(name);
1199 return NULL;
1200 }
1201 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1202 Py_DECREF(name);
1203 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1204 } else {
1205 /* Remember pointer to module init function. */
1206 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001207 if (def == NULL) {
1208 Py_DECREF(name);
1209 return NULL;
1210 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001211 def->m_base.m_init = p->initfunc;
Eric Snow86b7afd2017-09-04 17:54:09 -06001212 if (modules == NULL) {
1213 modules = PyImport_GetModuleDict();
1214 }
1215 if (_PyImport_FixupExtensionObject(mod, name, name,
1216 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001217 Py_DECREF(name);
1218 return NULL;
1219 }
1220 Py_DECREF(name);
1221 return mod;
1222 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 }
1224 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001225 Py_DECREF(name);
1226 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001227}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001228
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001229
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001230/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001232static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001233find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001234{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001235 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001236
Victor Stinner53dc7352011-03-20 01:50:21 +01001237 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 for (p = PyImport_FrozenModules; ; p++) {
1241 if (p->name == NULL)
1242 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001243 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 break;
1245 }
1246 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001247}
1248
Guido van Rossum79f25d91997-04-29 20:08:16 +00001249static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001250get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001251{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001252 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (p == NULL) {
1256 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001257 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 name);
1259 return NULL;
1260 }
1261 if (p->code == NULL) {
1262 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001263 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 name);
1265 return NULL;
1266 }
1267 size = p->size;
1268 if (size < 0)
1269 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001270 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001271}
1272
Brett Cannon8d110132009-03-15 02:20:16 +00001273static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001274is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001275{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001276 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (p == NULL) {
1280 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001281 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 name);
1283 return NULL;
1284 }
Brett Cannon8d110132009-03-15 02:20:16 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (size < 0)
1289 Py_RETURN_TRUE;
1290 else
1291 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001292}
1293
1294
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001295/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001296 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001297 an exception set if the initialization failed.
1298 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001299
1300int
Victor Stinner53dc7352011-03-20 01:50:21 +01001301PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001302{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001303 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001304 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int ispackage;
1306 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001307
Victor Stinner53dc7352011-03-20 01:50:21 +01001308 p = find_frozen(name);
1309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (p == NULL)
1311 return 0;
1312 if (p->code == NULL) {
1313 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001314 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 name);
1316 return -1;
1317 }
1318 size = p->size;
1319 ispackage = (size < 0);
1320 if (ispackage)
1321 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001322 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (co == NULL)
1324 return -1;
1325 if (!PyCode_Check(co)) {
1326 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001327 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 name);
1329 goto err_return;
1330 }
1331 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001332 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001333 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001335 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (m == NULL)
1337 goto err_return;
1338 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001339 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 goto err_return;
1342 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 err = PyDict_SetItemString(d, "__path__", l);
1344 Py_DECREF(l);
1345 if (err != 0)
1346 goto err_return;
1347 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001348 d = module_dict_for_exec(name);
1349 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001350 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001351 }
1352 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (m == NULL)
1354 goto err_return;
1355 Py_DECREF(co);
1356 Py_DECREF(m);
1357 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001358err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 Py_DECREF(co);
1360 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001361}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001362
Victor Stinner53dc7352011-03-20 01:50:21 +01001363int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001364PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001365{
1366 PyObject *nameobj;
1367 int ret;
1368 nameobj = PyUnicode_InternFromString(name);
1369 if (nameobj == NULL)
1370 return -1;
1371 ret = PyImport_ImportFrozenModuleObject(nameobj);
1372 Py_DECREF(nameobj);
1373 return ret;
1374}
1375
Guido van Rossum74e6a111994-08-29 12:54:38 +00001376
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001377/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001378 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001379
Guido van Rossum79f25d91997-04-29 20:08:16 +00001380PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001381PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyObject *pname;
1384 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 pname = PyUnicode_FromString(name);
1387 if (pname == NULL)
1388 return NULL;
1389 result = PyImport_Import(pname);
1390 Py_DECREF(pname);
1391 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001392}
1393
Christian Heimes072c0f12008-01-03 23:01:04 +00001394/* Import a module without blocking
1395 *
1396 * At first it tries to fetch the module from sys.modules. If the module was
1397 * never loaded before it loads it with PyImport_ImportModule() unless another
1398 * thread holds the import lock. In the latter case the function raises an
1399 * ImportError instead of blocking.
1400 *
1401 * Returns the module object with incremented ref count.
1402 */
1403PyObject *
1404PyImport_ImportModuleNoBlock(const char *name)
1405{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001406 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001407}
1408
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001409
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001410/* Remove importlib frames from the traceback,
1411 * except in Verbose mode. */
1412static void
1413remove_importlib_frames(void)
1414{
1415 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001416 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001417 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001418 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001419 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001420 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001421 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001422
1423 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001424 from the traceback. We always trim chunks
1425 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001426
1427 PyErr_Fetch(&exception, &value, &base_tb);
1428 if (!exception || Py_VerboseFlag)
1429 goto done;
1430 if (PyType_IsSubtype((PyTypeObject *) exception,
1431 (PyTypeObject *) PyExc_ImportError))
1432 always_trim = 1;
1433
1434 prev_link = &base_tb;
1435 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001436 while (tb != NULL) {
1437 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1438 PyObject *next = (PyObject *) traceback->tb_next;
1439 PyFrameObject *frame = traceback->tb_frame;
1440 PyCodeObject *code = frame->f_code;
1441 int now_in_importlib;
1442
1443 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001444 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1445 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001446 if (now_in_importlib && !in_importlib) {
1447 /* This is the link to this chunk of importlib tracebacks */
1448 outer_link = prev_link;
1449 }
1450 in_importlib = now_in_importlib;
1451
1452 if (in_importlib &&
1453 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001454 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001455 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001456 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001457 prev_link = outer_link;
1458 }
1459 else {
1460 prev_link = (PyObject **) &traceback->tb_next;
1461 }
1462 tb = next;
1463 }
1464done:
1465 PyErr_Restore(exception, value, base_tb);
1466}
1467
1468
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001469static PyObject *
1470resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001471{
Eric Snowb523f842013-11-22 09:05:39 -07001472 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001473 _Py_IDENTIFIER(__package__);
1474 _Py_IDENTIFIER(__path__);
1475 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001476 _Py_IDENTIFIER(parent);
1477 PyObject *abs_name;
1478 PyObject *package = NULL;
1479 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001480 Py_ssize_t last_dot;
1481 PyObject *base;
1482 int level_up;
1483
1484 if (globals == NULL) {
1485 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1486 goto error;
1487 }
1488 if (!PyDict_Check(globals)) {
1489 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1490 goto error;
1491 }
1492 package = _PyDict_GetItemId(globals, &PyId___package__);
1493 if (package == Py_None) {
1494 package = NULL;
1495 }
1496 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1497
1498 if (package != NULL) {
1499 Py_INCREF(package);
1500 if (!PyUnicode_Check(package)) {
1501 PyErr_SetString(PyExc_TypeError, "package must be a string");
1502 goto error;
1503 }
1504 else if (spec != NULL && spec != Py_None) {
1505 int equal;
1506 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1507 if (parent == NULL) {
1508 goto error;
1509 }
1510
1511 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1512 Py_DECREF(parent);
1513 if (equal < 0) {
1514 goto error;
1515 }
1516 else if (equal == 0) {
1517 if (PyErr_WarnEx(PyExc_ImportWarning,
1518 "__package__ != __spec__.parent", 1) < 0) {
1519 goto error;
1520 }
1521 }
1522 }
1523 }
1524 else if (spec != NULL && spec != Py_None) {
1525 package = _PyObject_GetAttrId(spec, &PyId_parent);
1526 if (package == NULL) {
1527 goto error;
1528 }
1529 else if (!PyUnicode_Check(package)) {
1530 PyErr_SetString(PyExc_TypeError,
1531 "__spec__.parent must be a string");
1532 goto error;
1533 }
1534 }
1535 else {
1536 if (PyErr_WarnEx(PyExc_ImportWarning,
1537 "can't resolve package from __spec__ or __package__, "
1538 "falling back on __name__ and __path__", 1) < 0) {
1539 goto error;
1540 }
1541
1542 package = _PyDict_GetItemId(globals, &PyId___name__);
1543 if (package == NULL) {
1544 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1545 goto error;
1546 }
1547
1548 Py_INCREF(package);
1549 if (!PyUnicode_Check(package)) {
1550 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1551 goto error;
1552 }
1553
1554 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1555 Py_ssize_t dot;
1556
1557 if (PyUnicode_READY(package) < 0) {
1558 goto error;
1559 }
1560
1561 dot = PyUnicode_FindChar(package, '.',
1562 0, PyUnicode_GET_LENGTH(package), -1);
1563 if (dot == -2) {
1564 goto error;
1565 }
1566
1567 if (dot >= 0) {
1568 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1569 if (substr == NULL) {
1570 goto error;
1571 }
1572 Py_SETREF(package, substr);
1573 }
1574 }
1575 }
1576
1577 last_dot = PyUnicode_GET_LENGTH(package);
1578 if (last_dot == 0) {
1579 PyErr_SetString(PyExc_ImportError,
1580 "attempted relative import with no known parent package");
1581 goto error;
1582 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001583
1584 for (level_up = 1; level_up < level; level_up += 1) {
1585 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1586 if (last_dot == -2) {
1587 goto error;
1588 }
1589 else if (last_dot == -1) {
1590 PyErr_SetString(PyExc_ValueError,
1591 "attempted relative import beyond top-level "
1592 "package");
1593 goto error;
1594 }
1595 }
1596
1597 base = PyUnicode_Substring(package, 0, last_dot);
1598 Py_DECREF(package);
1599 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1600 return base;
1601 }
1602
1603 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1604 Py_DECREF(base);
1605 return abs_name;
1606
1607 error:
1608 Py_XDECREF(package);
1609 return NULL;
1610}
1611
1612PyObject *
1613PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1614 PyObject *locals, PyObject *fromlist,
1615 int level)
1616{
Brett Cannonfd074152012-04-14 14:10:13 -04001617 _Py_IDENTIFIER(_find_and_load);
1618 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001619 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001620 PyObject *final_mod = NULL;
1621 PyObject *mod = NULL;
1622 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001623 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001624 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001625
Brett Cannonfd074152012-04-14 14:10:13 -04001626 if (name == NULL) {
1627 PyErr_SetString(PyExc_ValueError, "Empty module name");
1628 goto error;
1629 }
1630
1631 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1632 for added performance. */
1633
1634 if (!PyUnicode_Check(name)) {
1635 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1636 goto error;
1637 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001638 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001639 goto error;
1640 }
1641 if (level < 0) {
1642 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1643 goto error;
1644 }
Brett Cannon849113a2016-01-22 15:25:50 -08001645
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001646 if (level > 0) {
1647 abs_name = resolve_name(name, globals, level);
1648 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001649 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001650 }
1651 else { /* level == 0 */
1652 if (PyUnicode_GET_LENGTH(name) == 0) {
1653 PyErr_SetString(PyExc_ValueError, "Empty module name");
1654 goto error;
1655 }
Brett Cannonfd074152012-04-14 14:10:13 -04001656 abs_name = name;
1657 Py_INCREF(abs_name);
1658 }
1659
Eric Snow86b7afd2017-09-04 17:54:09 -06001660 mod = _PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001661 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001662 _Py_IDENTIFIER(__spec__);
1663 _Py_IDENTIFIER(_initializing);
1664 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001665 PyObject *value = NULL;
1666 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001667 int initializing = 0;
1668
Brett Cannonfd074152012-04-14 14:10:13 -04001669 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001670 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001671 __spec__._initializing is true.
1672 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001673 stuffing the new module in sys.modules.
1674 */
Eric Snowb523f842013-11-22 09:05:39 -07001675 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1676 if (spec != NULL) {
1677 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1678 Py_DECREF(spec);
1679 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001680 if (value == NULL)
1681 PyErr_Clear();
1682 else {
1683 initializing = PyObject_IsTrue(value);
1684 Py_DECREF(value);
1685 if (initializing == -1)
1686 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001687 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001688 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1689 &PyId__lock_unlock_module, abs_name,
1690 NULL);
1691 if (value == NULL)
1692 goto error;
1693 Py_DECREF(value);
1694 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001695 }
Brett Cannonfd074152012-04-14 14:10:13 -04001696 }
1697 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001698 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001699 &PyId__find_and_load, abs_name,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001700 interp->import_func, NULL);
Brett Cannonfd074152012-04-14 14:10:13 -04001701 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001702 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001703 }
1704 }
1705
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001706 has_from = 0;
1707 if (fromlist != NULL && fromlist != Py_None) {
1708 has_from = PyObject_IsTrue(fromlist);
1709 if (has_from < 0)
1710 goto error;
1711 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001712 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001713 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1714 if (level == 0 || len > 0) {
1715 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001716
Victor Stinner744c34e2016-05-20 11:36:13 +02001717 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1718 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001719 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001720 }
1721
Victor Stinner744c34e2016-05-20 11:36:13 +02001722 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001723 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001724 final_mod = mod;
1725 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001726 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001727 }
1728
Brett Cannonfd074152012-04-14 14:10:13 -04001729 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001730 PyObject *front = PyUnicode_Substring(name, 0, dot);
1731 if (front == NULL) {
1732 goto error;
1733 }
1734
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001735 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001736 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001737 }
1738 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001739 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001740 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001741 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001742 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001743 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001744 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001745 }
Brett Cannonfd074152012-04-14 14:10:13 -04001746
Eric Snow86b7afd2017-09-04 17:54:09 -06001747 final_mod = _PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001748 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001749 if (final_mod == NULL) {
1750 PyErr_Format(PyExc_KeyError,
1751 "%R not in sys.modules as expected",
1752 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001753 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001754 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001755 Py_INCREF(final_mod);
Brett Cannonfd074152012-04-14 14:10:13 -04001756 }
1757 }
1758 else {
1759 final_mod = mod;
1760 Py_INCREF(mod);
1761 }
1762 }
1763 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001764 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001765 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001766 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001767 NULL);
1768 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001769
Brett Cannonfd074152012-04-14 14:10:13 -04001770 error:
1771 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001772 Py_XDECREF(mod);
1773 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001774 if (final_mod == NULL)
1775 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001776 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001777}
1778
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001779PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001780PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001781 PyObject *fromlist, int level)
1782{
1783 PyObject *nameobj, *mod;
1784 nameobj = PyUnicode_FromString(name);
1785 if (nameobj == NULL)
1786 return NULL;
1787 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1788 fromlist, level);
1789 Py_DECREF(nameobj);
1790 return mod;
1791}
1792
1793
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001794/* Re-import a module of any kind and return its module object, WITH
1795 INCREMENTED REFERENCE COUNT */
1796
Guido van Rossum79f25d91997-04-29 20:08:16 +00001797PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001798PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001799{
Eric Snow86b7afd2017-09-04 17:54:09 -06001800 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001801 _Py_IDENTIFIER(reload);
1802 PyObject *reloaded_module = NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -06001803 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001804 if (imp == NULL) {
1805 imp = PyImport_ImportModule("imp");
1806 if (imp == NULL) {
1807 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
Brett Cannon62228db2012-04-29 14:38:11 -04001810 else {
1811 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001813
Victor Stinner55ba38a2016-12-09 16:09:30 +01001814 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001815 Py_DECREF(imp);
1816 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001817}
1818
1819
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001820/* Higher-level import emulator which emulates the "import" statement
1821 more accurately -- it invokes the __import__() function from the
1822 builtins of the current globals. This means that the import is
1823 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001824 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001825 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001826 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001827 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001828
1829PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001830PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 static PyObject *silly_list = NULL;
1833 static PyObject *builtins_str = NULL;
1834 static PyObject *import_str = NULL;
1835 PyObject *globals = NULL;
1836 PyObject *import = NULL;
1837 PyObject *builtins = NULL;
1838 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 /* Initialize constant string objects */
1841 if (silly_list == NULL) {
1842 import_str = PyUnicode_InternFromString("__import__");
1843 if (import_str == NULL)
1844 return NULL;
1845 builtins_str = PyUnicode_InternFromString("__builtins__");
1846 if (builtins_str == NULL)
1847 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001848 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (silly_list == NULL)
1850 return NULL;
1851 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* Get the builtins from current globals */
1854 globals = PyEval_GetGlobals();
1855 if (globals != NULL) {
1856 Py_INCREF(globals);
1857 builtins = PyObject_GetItem(globals, builtins_str);
1858 if (builtins == NULL)
1859 goto err;
1860 }
1861 else {
1862 /* No globals -- use standard builtins, and fake globals */
1863 builtins = PyImport_ImportModuleLevel("builtins",
1864 NULL, NULL, NULL, 0);
1865 if (builtins == NULL)
1866 return NULL;
1867 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1868 if (globals == NULL)
1869 goto err;
1870 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 /* Get the __import__ function from the builtins */
1873 if (PyDict_Check(builtins)) {
1874 import = PyObject_GetItem(builtins, import_str);
1875 if (import == NULL)
1876 PyErr_SetObject(PyExc_KeyError, import_str);
1877 }
1878 else
1879 import = PyObject_GetAttr(builtins, import_str);
1880 if (import == NULL)
1881 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001884 Always use absolute import here.
1885 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1887 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001888 if (r == NULL)
1889 goto err;
1890 Py_DECREF(r);
1891
Eric Snow86b7afd2017-09-04 17:54:09 -06001892 r = _PyImport_GetModule(module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001893 if (r != NULL) {
Brett Cannonbc2eff32010-09-19 21:39:02 +00001894 Py_INCREF(r);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001895 }
1896 else if (!PyErr_Occurred()) {
1897 PyErr_SetObject(PyExc_KeyError, module_name);
1898 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001899
1900 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 Py_XDECREF(globals);
1902 Py_XDECREF(builtins);
1903 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001906}
1907
Brett Cannon4caa61d2014-01-09 19:03:32 -05001908/*[clinic input]
1909_imp.extension_suffixes
1910
1911Returns the list of file suffixes used to identify extension modules.
1912[clinic start generated code]*/
1913
Brett Cannon4caa61d2014-01-09 19:03:32 -05001914static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001915_imp_extension_suffixes_impl(PyObject *module)
1916/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001919 const char *suffix;
1920 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 list = PyList_New(0);
1923 if (list == NULL)
1924 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001925#ifdef HAVE_DYNAMIC_LOADING
1926 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1927 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 if (item == NULL) {
1929 Py_DECREF(list);
1930 return NULL;
1931 }
1932 if (PyList_Append(list, item) < 0) {
1933 Py_DECREF(list);
1934 Py_DECREF(item);
1935 return NULL;
1936 }
1937 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001938 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
Brett Cannon2657df42012-05-04 15:20:40 -04001940#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001942}
1943
Brett Cannon4caa61d2014-01-09 19:03:32 -05001944/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001945_imp.init_frozen
1946
1947 name: unicode
1948 /
1949
1950Initializes a frozen module.
1951[clinic start generated code]*/
1952
Brett Cannon4caa61d2014-01-09 19:03:32 -05001953static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001954_imp_init_frozen_impl(PyObject *module, PyObject *name)
1955/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 int ret;
1958 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001959
Victor Stinner53dc7352011-03-20 01:50:21 +01001960 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 if (ret < 0)
1962 return NULL;
1963 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001964 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001966 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 Py_XINCREF(m);
1968 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001969}
1970
Brett Cannon4caa61d2014-01-09 19:03:32 -05001971/*[clinic input]
1972_imp.get_frozen_object
1973
1974 name: unicode
1975 /
1976
1977Create a code object for a frozen module.
1978[clinic start generated code]*/
1979
Brett Cannon4caa61d2014-01-09 19:03:32 -05001980static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001981_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1982/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001985}
1986
Brett Cannon4caa61d2014-01-09 19:03:32 -05001987/*[clinic input]
1988_imp.is_frozen_package
1989
1990 name: unicode
1991 /
1992
1993Returns True if the module name is of a frozen package.
1994[clinic start generated code]*/
1995
Brett Cannon4caa61d2014-01-09 19:03:32 -05001996static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001997_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1998/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002001}
2002
Brett Cannon4caa61d2014-01-09 19:03:32 -05002003/*[clinic input]
2004_imp.is_builtin
2005
2006 name: unicode
2007 /
2008
2009Returns True if the module name corresponds to a built-in module.
2010[clinic start generated code]*/
2011
Guido van Rossum79f25d91997-04-29 20:08:16 +00002012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002013_imp_is_builtin_impl(PyObject *module, PyObject *name)
2014/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002015{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002016 return PyLong_FromLong(is_builtin(name));
2017}
2018
2019/*[clinic input]
2020_imp.is_frozen
2021
2022 name: unicode
2023 /
2024
2025Returns True if the module name corresponds to a frozen module.
2026[clinic start generated code]*/
2027
Brett Cannon4caa61d2014-01-09 19:03:32 -05002028static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002029_imp_is_frozen_impl(PyObject *module, PyObject *name)
2030/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002031{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002032 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 p = find_frozen(name);
2035 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002036}
2037
Larry Hastings1df0b352015-08-24 19:53:56 -07002038/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2039static int
2040exec_builtin_or_dynamic(PyObject *mod) {
2041 PyModuleDef *def;
2042 void *state;
2043
2044 if (!PyModule_Check(mod)) {
2045 return 0;
2046 }
2047
2048 def = PyModule_GetDef(mod);
2049 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002050 return 0;
2051 }
Brett Cannon52794db2016-09-07 17:00:43 -07002052
Larry Hastings1df0b352015-08-24 19:53:56 -07002053 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002054 if (state) {
2055 /* Already initialized; skip reload */
2056 return 0;
2057 }
Brett Cannon52794db2016-09-07 17:00:43 -07002058
Larry Hastings1df0b352015-08-24 19:53:56 -07002059 return PyModule_ExecDef(mod, def);
2060}
2061
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002062#ifdef HAVE_DYNAMIC_LOADING
2063
Brett Cannon4caa61d2014-01-09 19:03:32 -05002064/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002065_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002066
Nick Coghland5cacbb2015-05-23 22:24:10 +10002067 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002068 file: object = NULL
2069 /
2070
Nick Coghland5cacbb2015-05-23 22:24:10 +10002071Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002072[clinic start generated code]*/
2073
Brett Cannon4caa61d2014-01-09 19:03:32 -05002074static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002075_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2076/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002077{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002078 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002079 FILE *fp;
2080
Nick Coghland5cacbb2015-05-23 22:24:10 +10002081 name = PyObject_GetAttrString(spec, "name");
2082 if (name == NULL) {
2083 return NULL;
2084 }
2085
2086 path = PyObject_GetAttrString(spec, "origin");
2087 if (path == NULL) {
2088 Py_DECREF(name);
2089 return NULL;
2090 }
2091
2092 mod = _PyImport_FindExtensionObject(name, path);
2093 if (mod != NULL) {
2094 Py_DECREF(name);
2095 Py_DECREF(path);
2096 Py_INCREF(mod);
2097 return mod;
2098 }
2099
Brett Cannon4caa61d2014-01-09 19:03:32 -05002100 if (file != NULL) {
2101 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002102 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002103 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002104 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002108 else
2109 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002110
2111 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2112
2113 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002114 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (fp)
2116 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002117 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002118}
2119
Nick Coghland5cacbb2015-05-23 22:24:10 +10002120/*[clinic input]
2121_imp.exec_dynamic -> int
2122
2123 mod: object
2124 /
2125
2126Initialize an extension module.
2127[clinic start generated code]*/
2128
2129static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002130_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2131/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002132{
Larry Hastings1df0b352015-08-24 19:53:56 -07002133 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002134}
2135
2136
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002137#endif /* HAVE_DYNAMIC_LOADING */
2138
Larry Hastings7726ac92014-01-31 22:03:12 -08002139/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002140_imp.exec_builtin -> int
2141
2142 mod: object
2143 /
2144
2145Initialize a built-in module.
2146[clinic start generated code]*/
2147
2148static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002149_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2150/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002151{
2152 return exec_builtin_or_dynamic(mod);
2153}
2154
Barry Warsaw28a691b2010-04-17 00:19:56 +00002155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002156PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002157"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002158
Guido van Rossum79f25d91997-04-29 20:08:16 +00002159static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002160 _IMP_EXTENSION_SUFFIXES_METHODDEF
2161 _IMP_LOCK_HELD_METHODDEF
2162 _IMP_ACQUIRE_LOCK_METHODDEF
2163 _IMP_RELEASE_LOCK_METHODDEF
2164 _IMP_GET_FROZEN_OBJECT_METHODDEF
2165 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002166 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002167 _IMP_INIT_FROZEN_METHODDEF
2168 _IMP_IS_BUILTIN_METHODDEF
2169 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002170 _IMP_CREATE_DYNAMIC_METHODDEF
2171 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002172 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002173 _IMP__FIX_CO_FILENAME_METHODDEF
2174 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002175};
2176
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002177
Martin v. Löwis1a214512008-06-11 05:26:20 +00002178static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002180 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 doc_imp,
2182 0,
2183 imp_methods,
2184 NULL,
2185 NULL,
2186 NULL,
2187 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002188};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002189
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002190PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002191PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 m = PyModule_Create(&impmodule);
2196 if (m == NULL)
2197 goto failure;
2198 d = PyModule_GetDict(m);
2199 if (d == NULL)
2200 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002203 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 Py_XDECREF(m);
2205 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002206}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002207
2208
Guido van Rossumb18618d2000-05-03 23:44:39 +00002209/* API for embedding applications that want to add their own entries
2210 to the table of built-in modules. This should normally be called
2211 *before* Py_Initialize(). When the table resize fails, -1 is
2212 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002213
2214 After a similar function by Just van Rossum. */
2215
2216int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002217PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 static struct _inittab *our_copy = NULL;
2220 struct _inittab *p;
2221 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Count the number of entries in both tables */
2224 for (n = 0; newtab[n].name != NULL; n++)
2225 ;
2226 if (n == 0)
2227 return 0; /* Nothing to do */
2228 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2229 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Allocate new memory for the combined table */
2232 p = our_copy;
2233 PyMem_RESIZE(p, struct _inittab, i+n+1);
2234 if (p == NULL)
2235 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* Copy the tables into the new memory */
2238 if (our_copy != PyImport_Inittab)
2239 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2240 PyImport_Inittab = our_copy = p;
2241 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002244}
2245
2246/* Shorthand to add a single entry given a name and a function */
2247
2248int
Brett Cannona826f322009-04-02 03:41:46 +00002249PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002254
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002255 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002259}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002260
2261#ifdef __cplusplus
2262}
2263#endif