blob: fef639825c47c33af439dfd260bbceb8fac4f361 [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 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06008#include "internal/pystate.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000010#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#include "code.h"
Antoine Pitroubc07a5c2012-07-08 12:01:27 +020012#include "frameobject.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000013#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000014#include "importdl.h"
Christian Heimes3d2b4072017-09-30 00:53:19 +020015#include "pydtrace.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016
Guido van Rossum55a83382000-09-20 20:31:38 +000017#ifdef HAVE_FCNTL_H
18#include <fcntl.h>
19#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000020#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000021extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000022#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000023
Barry Warsaw28a691b2010-04-17 00:19:56 +000024#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000025
Victor Stinner95872862011-03-07 18:20:56 +010026/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000027static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000028
Guido van Rossum771c6c81997-10-31 18:37:24 +000029/* This table is defined in config.c: */
30extern struct _inittab _PyImport_Inittab[];
31
32struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000033
Victor Stinnerd0296212011-03-14 14:04:10 -040034static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000035
Brett Cannon4caa61d2014-01-09 19:03:32 -050036/*[clinic input]
37module _imp
38[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030039/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040040
41#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050042
Guido van Rossum1ae940a1995-01-02 19:04:15 +000043/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Victor Stinnerf7e5b562017-11-15 15:48:08 -080045_PyInitError
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000046_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000047{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020048 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040049 initstr = PyUnicode_InternFromString("__init__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 if (initstr == NULL) {
51 return _Py_INIT_ERR("Can't initialize import variables");
52 }
53
Serhiy Storchaka013bb912014-02-10 18:21:34 +020054 interp->builtins_copy = PyDict_Copy(interp->builtins);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080055 if (interp->builtins_copy == NULL) {
56 return _Py_INIT_ERR("Can't backup builtins dict");
57 }
58 return _Py_INIT_OK();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059}
60
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061_PyInitError
Just van Rossum52e14d62002-12-30 22:08:05 +000062_PyImportHooks_Init(void)
63{
Brett Cannonfd074152012-04-14 14:10:13 -040064 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000066
Brett Cannonfd074152012-04-14 14:10:13 -040067 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 v = PyList_New(0);
69 if (v == NULL)
70 goto error;
71 err = PySys_SetObject("meta_path", v);
72 Py_DECREF(v);
73 if (err)
74 goto error;
75 v = PyDict_New();
76 if (v == NULL)
77 goto error;
78 err = PySys_SetObject("path_importer_cache", v);
79 Py_DECREF(v);
80 if (err)
81 goto error;
82 path_hooks = PyList_New(0);
83 if (path_hooks == NULL)
84 goto error;
85 err = PySys_SetObject("path_hooks", path_hooks);
86 if (err) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 }
Brett Cannonfd074152012-04-14 14:10:13 -040089 Py_DECREF(path_hooks);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080090 return _Py_INIT_OK();
91
92 error:
93 PyErr_Print();
94 return _Py_INIT_ERR("initializing sys.meta_path, sys.path_hooks, "
95 "or path_importer_cache failed");
Brett Cannonfd074152012-04-14 14:10:13 -040096}
97
Victor Stinnerf7e5b562017-11-15 15:48:08 -080098_PyInitError
Brett Cannonfd074152012-04-14 14:10:13 -040099_PyImportZip_Init(void)
100{
101 PyObject *path_hooks, *zimpimport;
102 int err = 0;
103
104 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +0200105 if (path_hooks == NULL) {
106 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -0400107 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200108 }
Brett Cannonfd074152012-04-14 14:10:13 -0400109
110 if (Py_VerboseFlag)
111 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 zimpimport = PyImport_ImportModule("zipimport");
114 if (zimpimport == NULL) {
115 PyErr_Clear(); /* No zip import module -- okay */
116 if (Py_VerboseFlag)
117 PySys_WriteStderr("# can't import zipimport\n");
118 }
119 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200120 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200121 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
122 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 Py_DECREF(zimpimport);
124 if (zipimporter == NULL) {
125 PyErr_Clear(); /* No zipimporter object -- okay */
126 if (Py_VerboseFlag)
127 PySys_WriteStderr(
128 "# can't import zipimport.zipimporter\n");
129 }
130 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400131 /* sys.path_hooks.insert(0, zipimporter) */
132 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400134 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (Py_VerboseFlag)
138 PySys_WriteStderr(
139 "# installed zipimport hook\n");
140 }
141 }
Brett Cannonfd074152012-04-14 14:10:13 -0400142
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800143 return _Py_INIT_OK();
Brett Cannonfd074152012-04-14 14:10:13 -0400144
145 error:
146 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800147 return _Py_INIT_ERR("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000148}
149
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000150/* Locking primitives to prevent parallel imports of the same module
151 in different threads to return with a partially loaded module.
152 These calls are serialized by the global interpreter lock. */
153
Guido van Rossum49b56061998-10-01 20:42:43 +0000154#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000155
Guido van Rossum65d5b571998-12-21 19:32:43 +0000156static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200157static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000158static int import_lock_level = 0;
159
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000160void
161_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000162{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200163 unsigned long me = PyThread_get_thread_ident();
164 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 return; /* Too bad */
166 if (import_lock == NULL) {
167 import_lock = PyThread_allocate_lock();
168 if (import_lock == NULL)
169 return; /* Nothing much we can do. */
170 }
171 if (import_lock_thread == me) {
172 import_lock_level++;
173 return;
174 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200175 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
176 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 {
178 PyThreadState *tstate = PyEval_SaveThread();
179 PyThread_acquire_lock(import_lock, 1);
180 PyEval_RestoreThread(tstate);
181 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100182 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 import_lock_thread = me;
184 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000185}
186
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000187int
188_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000189{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200190 unsigned long me = PyThread_get_thread_ident();
191 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 return 0; /* Too bad */
193 if (import_lock_thread != me)
194 return -1;
195 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100196 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200198 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 PyThread_release_lock(import_lock);
200 }
201 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000202}
203
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200204/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000205 created child processes do not share locks with the parent.
206 We now acquire the import lock around fork() calls but on some platforms
207 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000208
209void
210_PyImport_ReInitLock(void)
211{
Christian Heimes418fd742015-04-19 21:08:42 +0200212 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200214 if (import_lock == NULL) {
215 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
216 }
217 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000218 if (import_lock_level > 1) {
219 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200220 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500221 /* The following could fail if the lock is already held, but forking as
222 a side-effect of an import is a) rare, b) nuts, and c) difficult to
223 do thanks to the lock only being held when doing individual module
224 locks per import. */
225 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000226 import_lock_thread = me;
227 import_lock_level--;
228 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200229 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000230 import_lock_level = 0;
231 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000232}
233
Brett Cannon4caa61d2014-01-09 19:03:32 -0500234/*[clinic input]
235_imp.lock_held
236
237Return True if the import lock is currently held, else False.
238
239On platforms without threads, return False.
240[clinic start generated code]*/
241
Brett Cannon4caa61d2014-01-09 19:03:32 -0500242static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300243_imp_lock_held_impl(PyObject *module)
244/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000245{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200246 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000247}
248
Brett Cannon4caa61d2014-01-09 19:03:32 -0500249/*[clinic input]
250_imp.acquire_lock
251
252Acquires the interpreter's import lock for the current thread.
253
254This lock should be used by import hooks to ensure thread-safety when importing
255modules. On platforms without threads, this function does nothing.
256[clinic start generated code]*/
257
Brett Cannon4caa61d2014-01-09 19:03:32 -0500258static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300259_imp_acquire_lock_impl(PyObject *module)
260/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200263 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000264}
265
Brett Cannon4caa61d2014-01-09 19:03:32 -0500266/*[clinic input]
267_imp.release_lock
268
269Release the interpreter's import lock.
270
271On platforms without threads, this function does nothing.
272[clinic start generated code]*/
273
Brett Cannon4caa61d2014-01-09 19:03:32 -0500274static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300275_imp_release_lock_impl(PyObject *module)
276/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (_PyImport_ReleaseLock() < 0) {
279 PyErr_SetString(PyExc_RuntimeError,
280 "not holding the import lock");
281 return NULL;
282 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200283 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000284}
285
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100286void
287_PyImport_Fini(void)
288{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200289 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100290 if (import_lock != NULL) {
291 PyThread_free_lock(import_lock);
292 import_lock = NULL;
293 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100294}
295
Guido van Rossum25ce5661997-08-02 03:10:38 +0000296/* Helper for sys */
297
298PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000299PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300{
Eric Snow93c92f72017-09-13 23:46:04 -0700301 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow3f9eee62017-09-15 16:35:20 -0600302 if (interp->modules == NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700303 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
Eric Snow3f9eee62017-09-15 16:35:20 -0600304 }
Eric Snow93c92f72017-09-13 23:46:04 -0700305 return interp->modules;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306}
307
Eric Snowd393c1b2017-09-14 12:18:12 -0600308/* In some corner cases it is important to be sure that the import
309 machinery has been initialized (or not cleaned up yet). For
310 example, see issue #4236 and PyModule_Create2(). */
311
312int
313_PyImport_IsInitialized(PyInterpreterState *interp)
314{
315 if (interp->modules == NULL)
316 return 0;
317 return 1;
318}
Guido van Rossum3f5da241990-12-20 15:06:42 +0000319
Eric Snow3f9eee62017-09-15 16:35:20 -0600320PyObject *
321_PyImport_GetModuleId(struct _Py_Identifier *nameid)
322{
323 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
324 if (name == NULL) {
325 return NULL;
326 }
327 return PyImport_GetModule(name);
328}
329
330int
331_PyImport_SetModule(PyObject *name, PyObject *m)
332{
333 PyObject *modules = PyImport_GetModuleDict();
334 return PyObject_SetItem(modules, name, m);
335}
336
337int
338_PyImport_SetModuleString(const char *name, PyObject *m)
339{
340 PyObject *modules = PyImport_GetModuleDict();
341 return PyMapping_SetItemString(modules, name, m);
342}
343
344PyObject *
345PyImport_GetModule(PyObject *name)
346{
347 PyObject *m;
348 PyObject *modules = PyImport_GetModuleDict();
349 if (modules == NULL) {
350 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
351 return NULL;
352 }
353 Py_INCREF(modules);
354 if (PyDict_CheckExact(modules)) {
355 m = PyDict_GetItemWithError(modules, name); /* borrowed */
356 Py_XINCREF(m);
357 }
358 else {
359 m = PyObject_GetItem(modules, name);
360 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
361 PyErr_Clear();
362 }
363 }
364 Py_DECREF(modules);
365 return m;
366}
367
368
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000369/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200370static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 "path", "argv", "ps1", "ps2",
372 "last_type", "last_value", "last_traceback",
373 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200374 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* misc stuff */
376 "flags", "float_info",
377 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000378};
379
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200380static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 "stdin", "__stdin__",
382 "stdout", "__stdout__",
383 "stderr", "__stderr__",
384 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000385};
386
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000387/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000388
Guido van Rossum3f5da241990-12-20 15:06:42 +0000389void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000390PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000391{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200392 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 PyObject *key, *value, *dict;
394 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snowd393c1b2017-09-14 12:18:12 -0600395 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200396 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200397 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (modules == NULL)
400 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Delete some special variables first. These are common
403 places where user values hide and people complain when their
404 destructors fail. Since the modules containing them are
405 deleted *last* of all, they would come too late in the normal
406 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000407
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200408 /* XXX Perhaps these precautions are obsolete. Who knows? */
409
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200410 if (Py_VerboseFlag)
411 PySys_WriteStderr("# clear builtins._\n");
412 PyDict_SetItemString(interp->builtins, "_", Py_None);
413
414 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200416 PySys_WriteStderr("# clear sys.%s\n", *p);
417 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200419 for (p = sys_files; *p != NULL; p+=2) {
420 if (Py_VerboseFlag)
421 PySys_WriteStderr("# restore sys.%s\n", *p);
422 value = PyDict_GetItemString(interp->sysdict, *(p+1));
423 if (value == NULL)
424 value = Py_None;
425 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000427
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200428 /* We prepare a list which will receive (name, weakref) tuples of
429 modules when they are removed from sys.modules. The name is used
430 for diagnosis messages (in verbose mode), while the weakref helps
431 detect those modules which have been held alive. */
432 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200433 if (weaklist == NULL)
434 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200435
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200436#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200437 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200438 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
439 if (name && wr) { \
440 PyObject *tup = PyTuple_Pack(2, name, wr); \
441 PyList_Append(weaklist, tup); \
442 Py_XDECREF(tup); \
443 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200444 Py_XDECREF(wr); \
445 if (PyErr_Occurred()) \
446 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600448#define CLEAR_MODULE(name, mod) \
449 if (PyModule_Check(mod)) { \
450 if (Py_VerboseFlag && PyUnicode_Check(name)) \
451 PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
452 STORE_MODULE_WEAKREF(name, mod); \
453 PyObject_SetItem(modules, name, Py_None); \
454 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000455
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200456 /* Remove all modules from sys.modules, hoping that garbage collection
457 can reclaim most of them. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600458 if (PyDict_CheckExact(modules)) {
459 pos = 0;
460 while (PyDict_Next(modules, &pos, &key, &value)) {
461 CLEAR_MODULE(key, value);
462 }
463 }
464 else {
465 PyObject *iterator = PyObject_GetIter(modules);
466 if (iterator == NULL) {
467 PyErr_Clear();
468 }
469 else {
470 while ((key = PyIter_Next(iterator))) {
471 value = PyObject_GetItem(modules, key);
472 if (value == NULL) {
473 PyErr_Clear();
474 continue;
475 }
476 CLEAR_MODULE(key, value);
477 Py_DECREF(value);
478 Py_DECREF(key);
479 }
480 Py_DECREF(iterator);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 }
482 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000483
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200484 /* Clear the modules dict. */
Eric Snow3f9eee62017-09-15 16:35:20 -0600485 if (PyDict_CheckExact(modules)) {
486 PyDict_Clear(modules);
487 }
488 else {
489 _Py_IDENTIFIER(clear);
490 if (_PyObject_CallMethodId(modules, &PyId_clear, "") == NULL)
491 PyErr_Clear();
492 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200493 /* Restore the original builtins dict, to ensure that any
494 user data gets cleared. */
495 dict = PyDict_Copy(interp->builtins);
496 if (dict == NULL)
497 PyErr_Clear();
498 PyDict_Clear(interp->builtins);
499 if (PyDict_Update(interp->builtins, interp->builtins_copy))
500 PyErr_Clear();
501 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200502 /* Clear module dict copies stored in the interpreter state */
503 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200504 /* Collect references */
505 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200506 /* Dump GC stats before it's too late, since it uses the warnings
507 machinery. */
508 _PyGC_DumpShutdownStats();
509
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200510 /* Now, if there are any modules left alive, clear their globals to
511 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200512 up here, since they are kept alive in the interpreter state.
513
514 The special treatment of "builtins" here is because even
515 when it's not referenced as a module, its dictionary is
516 referenced by almost every module's __builtins__. Since
517 deleting a module clears its dictionary (even if there are
518 references left to it), we need to delete the "builtins"
519 module last. Likewise, we don't delete sys until the very
520 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200521 if (weaklist != NULL) {
522 Py_ssize_t i, n;
523 n = PyList_GET_SIZE(weaklist);
524 for (i = 0; i < n; i++) {
525 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200526 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200527 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
528 if (mod == Py_None)
529 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200530 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200531 dict = PyModule_GetDict(mod);
532 if (dict == interp->builtins || dict == interp->sysdict)
533 continue;
534 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200535 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200536 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200537 _PyModule_Clear(mod);
538 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200539 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200540 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000542
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200543 /* Next, delete sys and builtins (in that order) */
544 if (Py_VerboseFlag)
545 PySys_FormatStderr("# cleanup[3] wiping sys\n");
546 _PyModule_ClearDict(interp->sysdict);
547 if (Py_VerboseFlag)
548 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
549 _PyModule_ClearDict(interp->builtins);
550
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200551 /* Clear and delete the modules directory. Actual modules will
552 still be there only if imported during the execution of some
553 destructor. */
Eric Snow93c92f72017-09-13 23:46:04 -0700554 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200556
557 /* Once more */
558 _PyGC_CollectNoFail();
559
560#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000561}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000562
563
Barry Warsaw28a691b2010-04-17 00:19:56 +0000564/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565
566long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000567PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000568{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200569 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400570 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600571 PyObject *external, *pyc_magic;
572
573 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
574 if (external == NULL)
575 return -1;
576 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
577 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400578 if (pyc_magic == NULL)
579 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200580 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700581 Py_DECREF(pyc_magic);
582 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000583}
584
585
Brett Cannon3adc7b72012-07-09 14:22:12 -0400586extern const char * _PySys_ImplCacheTag;
587
Barry Warsaw28a691b2010-04-17 00:19:56 +0000588const char *
589PyImport_GetMagicTag(void)
590{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400591 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000592}
593
Brett Cannon98979b82012-07-02 15:13:11 -0400594
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595/* Magic for extension modules (built-in as well as dynamically
596 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200597 once, we keep a static dictionary 'extensions' keyed by the tuple
598 (module name, module name) (for built-in modules) or by
599 (filename, module name) (for dynamically loaded modules), containing these
600 modules. A copy of the module's dictionary is stored by calling
601 _PyImport_FixupExtensionObject() immediately after the module initialization
602 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100603 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000604
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000605 Modules which do support multiple initialization set their m_size
606 field to a non-negative number (indicating the size of the
607 module-specific state). They are still recorded in the extensions
608 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000609*/
610
611int
Victor Stinner95872862011-03-07 18:20:56 +0100612_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snowd393c1b2017-09-14 12:18:12 -0600613 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000614{
Eric Snowd393c1b2017-09-14 12:18:12 -0600615 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500617 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (extensions == NULL) {
619 extensions = PyDict_New();
620 if (extensions == NULL)
621 return -1;
622 }
623 if (mod == NULL || !PyModule_Check(mod)) {
624 PyErr_BadInternalCall();
625 return -1;
626 }
627 def = PyModule_GetDef(mod);
628 if (!def) {
629 PyErr_BadInternalCall();
630 return -1;
631 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600632 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return -1;
634 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600635 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return -1;
637 }
638 if (def->m_size == -1) {
639 if (def->m_base.m_copy) {
640 /* Somebody already imported the module,
641 likely under a different name.
642 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200643 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 }
645 dict = PyModule_GetDict(mod);
646 if (dict == NULL)
647 return -1;
648 def->m_base.m_copy = PyDict_Copy(dict);
649 if (def->m_base.m_copy == NULL)
650 return -1;
651 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500652 key = PyTuple_Pack(2, filename, name);
653 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200654 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500655 res = PyDict_SetItem(extensions, key, (PyObject *)def);
656 Py_DECREF(key);
657 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200658 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660}
661
Victor Stinner49d3f252010-10-17 01:24:53 +0000662int
Eric Snowd393c1b2017-09-14 12:18:12 -0600663_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000664{
665 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100666 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100667 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100668 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000669 return -1;
Eric Snowd393c1b2017-09-14 12:18:12 -0600670 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100671 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000672 return res;
673}
674
Guido van Rossum25ce5661997-08-02 03:10:38 +0000675PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100676_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677{
Eric Snowd393c1b2017-09-14 12:18:12 -0600678 PyObject *modules = PyImport_GetModuleDict();
679 return _PyImport_FindExtensionObjectEx(name, filename, modules);
680}
681
682PyObject *
683_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
684 PyObject *modules)
685{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500686 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyModuleDef* def;
688 if (extensions == NULL)
689 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500690 key = PyTuple_Pack(2, filename, name);
691 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200692 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500693 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
694 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (def == NULL)
696 return NULL;
697 if (def->m_size == -1) {
698 /* Module does not support repeated initialization */
699 if (def->m_base.m_copy == NULL)
700 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600701 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (mod == NULL)
703 return NULL;
704 mdict = PyModule_GetDict(mod);
705 if (mdict == NULL)
706 return NULL;
707 if (PyDict_Update(mdict, def->m_base.m_copy))
708 return NULL;
709 }
710 else {
711 if (def->m_base.m_init == NULL)
712 return NULL;
713 mod = def->m_base.m_init();
714 if (mod == NULL)
715 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600716 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200717 Py_DECREF(mod);
718 return NULL;
719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 Py_DECREF(mod);
721 }
722 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow3f9eee62017-09-15 16:35:20 -0600723 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 Py_DECREF(mod);
725 return NULL;
726 }
727 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100728 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 name, filename);
730 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000731
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000732}
733
Victor Stinner49d3f252010-10-17 01:24:53 +0000734PyObject *
Eric Snowd393c1b2017-09-14 12:18:12 -0600735_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000736{
Victor Stinner95872862011-03-07 18:20:56 +0100737 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100738 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100739 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000740 return NULL;
Eric Snowd393c1b2017-09-14 12:18:12 -0600741 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100742 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000743 return res;
744}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000745
746/* Get the module object corresponding to a module name.
747 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000748 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000749 Because the former action is most common, THIS DOES NOT RETURN A
750 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000751
Guido van Rossum79f25d91997-04-29 20:08:16 +0000752PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000753PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyObject *modules = PyImport_GetModuleDict();
Eric Snowd393c1b2017-09-14 12:18:12 -0600756 return _PyImport_AddModuleObject(name, modules);
757}
758
759PyObject *
760_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
761{
Eric Snow86b7afd2017-09-04 17:54:09 -0600762 PyObject *m;
Eric Snow3f9eee62017-09-15 16:35:20 -0600763 if (PyDict_CheckExact(modules)) {
764 m = PyDict_GetItemWithError(modules, name);
765 }
766 else {
767 m = PyObject_GetItem(modules, name);
768 // For backward-comaptibility we copy the behavior
769 // of PyDict_GetItemWithError().
770 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
771 PyErr_Clear();
772 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200773 }
774 if (PyErr_Occurred()) {
775 return NULL;
776 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600777 if (m != NULL && PyModule_Check(m)) {
778 return m;
779 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000780 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (m == NULL)
782 return NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -0600783 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 Py_DECREF(m);
785 return NULL;
786 }
787 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000790}
791
Victor Stinner27ee0892011-03-04 12:57:09 +0000792PyObject *
793PyImport_AddModule(const char *name)
794{
795 PyObject *nameobj, *module;
796 nameobj = PyUnicode_FromString(name);
797 if (nameobj == NULL)
798 return NULL;
799 module = PyImport_AddModuleObject(nameobj);
800 Py_DECREF(nameobj);
801 return module;
802}
803
804
Tim Peters1cd70172004-08-02 03:52:12 +0000805/* Remove name from sys.modules, if it's there. */
806static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000807remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyObject *modules = PyImport_GetModuleDict();
Eric Snow3f9eee62017-09-15 16:35:20 -0600810 if (PyMapping_DelItem(modules, name) < 0) {
811 if (!PyMapping_HasKey(modules, name)) {
812 return;
813 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_FatalError("import: deleting existing key in"
815 "sys.modules failed");
Eric Snow3f9eee62017-09-15 16:35:20 -0600816 }
Tim Peters1cd70172004-08-02 03:52:12 +0000817}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000818
Christian Heimes3b06e532008-01-07 20:12:44 +0000819
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000820/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000821 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
822 * removed from sys.modules, to avoid leaving damaged module objects
823 * in sys.modules. The caller may wish to restore the original
824 * module object (if any) in this case; PyImport_ReloadModule is an
825 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000826 *
827 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
828 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000829 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000830PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300831PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 return PyImport_ExecCodeModuleWithPathnames(
834 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000835}
836
837PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300838PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return PyImport_ExecCodeModuleWithPathnames(
841 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000842}
843
844PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300845PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
846 const char *pathname,
847 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000848{
Victor Stinner27ee0892011-03-04 12:57:09 +0000849 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600850 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000851
852 nameobj = PyUnicode_FromString(name);
853 if (nameobj == NULL)
854 return NULL;
855
Victor Stinner27ee0892011-03-04 12:57:09 +0000856 if (cpathname != NULL) {
857 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
858 if (cpathobj == NULL)
859 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400860 }
861 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000862 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400863
864 if (pathname != NULL) {
865 pathobj = PyUnicode_DecodeFSDefault(pathname);
866 if (pathobj == NULL)
867 goto error;
868 }
869 else if (cpathobj != NULL) {
870 PyInterpreterState *interp = PyThreadState_GET()->interp;
871 _Py_IDENTIFIER(_get_sourcefile);
872
873 if (interp == NULL) {
874 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
875 "no interpreter!");
876 }
877
Eric Snow32439d62015-05-02 19:15:18 -0600878 external= PyObject_GetAttrString(interp->importlib,
879 "_bootstrap_external");
880 if (external != NULL) {
881 pathobj = _PyObject_CallMethodIdObjArgs(external,
882 &PyId__get_sourcefile, cpathobj,
883 NULL);
884 Py_DECREF(external);
885 }
Brett Cannona6473f92012-07-13 13:57:03 -0400886 if (pathobj == NULL)
887 PyErr_Clear();
888 }
889 else
890 pathobj = NULL;
891
Victor Stinner27ee0892011-03-04 12:57:09 +0000892 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
893error:
894 Py_DECREF(nameobj);
895 Py_XDECREF(pathobj);
896 Py_XDECREF(cpathobj);
897 return m;
898}
899
Brett Cannon18fc4e72014-04-04 10:01:46 -0400900static PyObject *
901module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000902{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400903 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904
Victor Stinner27ee0892011-03-04 12:57:09 +0000905 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (m == NULL)
907 return NULL;
908 /* If the module is being reloaded, we get the old module back
909 and re-use its dict to exec the new code. */
910 d = PyModule_GetDict(m);
911 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
912 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400913 PyEval_GetBuiltins()) != 0) {
914 remove_module(name);
915 return NULL;
916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400918
Eric Snow08197a42014-05-12 17:54:55 -0600919 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400920}
921
922static PyObject *
923exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
924{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400925 PyObject *v, *m;
926
927 v = PyEval_EvalCode(code_object, module_dict, module_dict);
928 if (v == NULL) {
929 remove_module(name);
930 return NULL;
931 }
932 Py_DECREF(v);
933
Eric Snow3f9eee62017-09-15 16:35:20 -0600934 m = PyImport_GetModule(name);
935 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400936 PyErr_Format(PyExc_ImportError,
937 "Loaded module %R not found in sys.modules",
938 name);
939 return NULL;
940 }
941
Brett Cannon18fc4e72014-04-04 10:01:46 -0400942 return m;
943}
944
945PyObject*
946PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
947 PyObject *cpathname)
948{
Eric Snow32439d62015-05-02 19:15:18 -0600949 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600950 PyInterpreterState *interp = PyThreadState_GET()->interp;
951 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400952
953 d = module_dict_for_exec(name);
954 if (d == NULL) {
955 return NULL;
956 }
957
Eric Snow08197a42014-05-12 17:54:55 -0600958 if (pathname == NULL) {
959 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
Eric Snow32439d62015-05-02 19:15:18 -0600961 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
962 if (external == NULL)
963 return NULL;
964 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600965 &PyId__fix_up_module,
966 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600967 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600968 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600969 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600970 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 }
Eric Snow08197a42014-05-12 17:54:55 -0600972 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000973}
974
975
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000976static void
977update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyObject *constants, *tmp;
980 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (PyUnicode_Compare(co->co_filename, oldname))
983 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000984
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200985 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300986 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 constants = co->co_consts;
989 n = PyTuple_GET_SIZE(constants);
990 for (i = 0; i < n; i++) {
991 tmp = PyTuple_GET_ITEM(constants, i);
992 if (PyCode_Check(tmp))
993 update_code_filenames((PyCodeObject *)tmp,
994 oldname, newname);
995 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000996}
997
Victor Stinner2f42ae52011-03-20 00:41:24 +0100998static void
999update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001000{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001001 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001002
Victor Stinner2f42ae52011-03-20 00:41:24 +01001003 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1004 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 oldname = co->co_filename;
1007 Py_INCREF(oldname);
1008 update_code_filenames(co, oldname, newname);
1009 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001010}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001011
Brett Cannon4caa61d2014-01-09 19:03:32 -05001012/*[clinic input]
1013_imp._fix_co_filename
1014
1015 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1016 Code object to change.
1017
1018 path: unicode
1019 File path to use.
1020 /
1021
1022Changes code.co_filename to specify the passed-in file path.
1023[clinic start generated code]*/
1024
Brett Cannon4caa61d2014-01-09 19:03:32 -05001025static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001026_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001027 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001028/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001029
Brett Cannon4caa61d2014-01-09 19:03:32 -05001030{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001031 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001032
1033 Py_RETURN_NONE;
1034}
1035
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001036
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001037/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001038static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001039
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001040
1041/* Helper to test for built-in module */
1042
1043static int
Victor Stinner95872862011-03-07 18:20:56 +01001044is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001045{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001046 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001048 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (PyImport_Inittab[i].initfunc == NULL)
1050 return -1;
1051 else
1052 return 1;
1053 }
1054 }
1055 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001056}
1057
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001058
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001059/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001060 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001061 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001062 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001063 this tells our caller that the path based finder could not find
1064 a finder for this path item. Cache the result in
1065 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001066 Returns a borrowed reference. */
1067
1068static PyObject *
1069get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyObject *importer;
1073 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 /* These conditions are the caller's responsibility: */
1076 assert(PyList_Check(path_hooks));
1077 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 nhooks = PyList_Size(path_hooks);
1080 if (nhooks < 0)
1081 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 importer = PyDict_GetItem(path_importer_cache, p);
1084 if (importer != NULL)
1085 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 /* set path_importer_cache[p] to None to avoid recursion */
1088 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1089 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 for (j = 0; j < nhooks; j++) {
1092 PyObject *hook = PyList_GetItem(path_hooks, j);
1093 if (hook == NULL)
1094 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001095 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (importer != NULL)
1097 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1100 return NULL;
1101 }
1102 PyErr_Clear();
1103 }
1104 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001105 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
1107 if (importer != NULL) {
1108 int err = PyDict_SetItem(path_importer_cache, p, importer);
1109 Py_DECREF(importer);
1110 if (err != 0)
1111 return NULL;
1112 }
1113 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001114}
1115
Christian Heimes9cd17752007-11-18 19:35:23 +00001116PyAPI_FUNC(PyObject *)
1117PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001119
Victor Stinner1e53bba2013-07-16 22:26:05 +02001120 path_importer_cache = PySys_GetObject("path_importer_cache");
1121 path_hooks = PySys_GetObject("path_hooks");
1122 if (path_importer_cache != NULL && path_hooks != NULL) {
1123 importer = get_path_importer(path_importer_cache,
1124 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
1126 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1127 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001128}
1129
Nick Coghland5cacbb2015-05-23 22:24:10 +10001130/*[clinic input]
1131_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001132
Nick Coghland5cacbb2015-05-23 22:24:10 +10001133 spec: object
1134 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001135
Nick Coghland5cacbb2015-05-23 22:24:10 +10001136Create an extension module.
1137[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001138
Nick Coghland5cacbb2015-05-23 22:24:10 +10001139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001140_imp_create_builtin(PyObject *module, PyObject *spec)
1141/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001144 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001145 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001146 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001147
Nick Coghland5cacbb2015-05-23 22:24:10 +10001148 name = PyObject_GetAttrString(spec, "name");
1149 if (name == NULL) {
1150 return NULL;
1151 }
1152
Victor Stinner5eb4f592013-11-14 22:38:52 +01001153 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001154 if (mod || PyErr_Occurred()) {
1155 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001156 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001157 return mod;
1158 }
1159
1160 namestr = PyUnicode_AsUTF8(name);
1161 if (namestr == NULL) {
1162 Py_DECREF(name);
1163 return NULL;
1164 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001165
Eric Snowd393c1b2017-09-14 12:18:12 -06001166 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001168 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001169 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001171 /* Cannot re-init internal module ("sys" or "builtins") */
1172 mod = PyImport_AddModule(namestr);
1173 Py_DECREF(name);
1174 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001177 if (mod == NULL) {
1178 Py_DECREF(name);
1179 return NULL;
1180 }
1181 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1182 Py_DECREF(name);
1183 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1184 } else {
1185 /* Remember pointer to module init function. */
1186 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001187 if (def == NULL) {
1188 Py_DECREF(name);
1189 return NULL;
1190 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001191 def->m_base.m_init = p->initfunc;
Eric Snowd393c1b2017-09-14 12:18:12 -06001192 if (modules == NULL) {
1193 modules = PyImport_GetModuleDict();
1194 }
1195 if (_PyImport_FixupExtensionObject(mod, name, name,
1196 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001197 Py_DECREF(name);
1198 return NULL;
1199 }
1200 Py_DECREF(name);
1201 return mod;
1202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
1204 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001205 Py_DECREF(name);
1206 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001207}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001208
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001209
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001210/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001211
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001212static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001213find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001214{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001215 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001216
Victor Stinner53dc7352011-03-20 01:50:21 +01001217 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 for (p = PyImport_FrozenModules; ; p++) {
1221 if (p->name == NULL)
1222 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001223 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 break;
1225 }
1226 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001227}
1228
Guido van Rossum79f25d91997-04-29 20:08:16 +00001229static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001230get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001231{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001232 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (p == NULL) {
1236 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001237 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 name);
1239 return NULL;
1240 }
1241 if (p->code == NULL) {
1242 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001243 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 name);
1245 return NULL;
1246 }
1247 size = p->size;
1248 if (size < 0)
1249 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001250 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001251}
1252
Brett Cannon8d110132009-03-15 02:20:16 +00001253static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001254is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001255{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001256 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (p == NULL) {
1260 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001261 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 name);
1263 return NULL;
1264 }
Brett Cannon8d110132009-03-15 02:20:16 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (size < 0)
1269 Py_RETURN_TRUE;
1270 else
1271 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001272}
1273
1274
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001275/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001276 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001277 an exception set if the initialization failed.
1278 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001279
1280int
Victor Stinner53dc7352011-03-20 01:50:21 +01001281PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001282{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001283 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001284 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 int ispackage;
1286 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001287
Victor Stinner53dc7352011-03-20 01:50:21 +01001288 p = find_frozen(name);
1289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (p == NULL)
1291 return 0;
1292 if (p->code == NULL) {
1293 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001294 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 name);
1296 return -1;
1297 }
1298 size = p->size;
1299 ispackage = (size < 0);
1300 if (ispackage)
1301 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001302 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (co == NULL)
1304 return -1;
1305 if (!PyCode_Check(co)) {
1306 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001307 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 name);
1309 goto err_return;
1310 }
1311 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001312 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001313 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001315 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (m == NULL)
1317 goto err_return;
1318 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001319 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 goto err_return;
1322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 err = PyDict_SetItemString(d, "__path__", l);
1324 Py_DECREF(l);
1325 if (err != 0)
1326 goto err_return;
1327 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001328 d = module_dict_for_exec(name);
1329 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001330 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001331 }
1332 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (m == NULL)
1334 goto err_return;
1335 Py_DECREF(co);
1336 Py_DECREF(m);
1337 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001338err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_DECREF(co);
1340 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001341}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001342
Victor Stinner53dc7352011-03-20 01:50:21 +01001343int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001344PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001345{
1346 PyObject *nameobj;
1347 int ret;
1348 nameobj = PyUnicode_InternFromString(name);
1349 if (nameobj == NULL)
1350 return -1;
1351 ret = PyImport_ImportFrozenModuleObject(nameobj);
1352 Py_DECREF(nameobj);
1353 return ret;
1354}
1355
Guido van Rossum74e6a111994-08-29 12:54:38 +00001356
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001357/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001358 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001359
Guido van Rossum79f25d91997-04-29 20:08:16 +00001360PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001361PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 PyObject *pname;
1364 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 pname = PyUnicode_FromString(name);
1367 if (pname == NULL)
1368 return NULL;
1369 result = PyImport_Import(pname);
1370 Py_DECREF(pname);
1371 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001372}
1373
Christian Heimes072c0f12008-01-03 23:01:04 +00001374/* Import a module without blocking
1375 *
1376 * At first it tries to fetch the module from sys.modules. If the module was
1377 * never loaded before it loads it with PyImport_ImportModule() unless another
1378 * thread holds the import lock. In the latter case the function raises an
1379 * ImportError instead of blocking.
1380 *
1381 * Returns the module object with incremented ref count.
1382 */
1383PyObject *
1384PyImport_ImportModuleNoBlock(const char *name)
1385{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001386 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001387}
1388
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001389
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001390/* Remove importlib frames from the traceback,
1391 * except in Verbose mode. */
1392static void
1393remove_importlib_frames(void)
1394{
1395 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001396 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001397 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001398 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001399 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001400 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001401 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001402
1403 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001404 from the traceback. We always trim chunks
1405 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001406
1407 PyErr_Fetch(&exception, &value, &base_tb);
1408 if (!exception || Py_VerboseFlag)
1409 goto done;
1410 if (PyType_IsSubtype((PyTypeObject *) exception,
1411 (PyTypeObject *) PyExc_ImportError))
1412 always_trim = 1;
1413
1414 prev_link = &base_tb;
1415 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001416 while (tb != NULL) {
1417 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1418 PyObject *next = (PyObject *) traceback->tb_next;
1419 PyFrameObject *frame = traceback->tb_frame;
1420 PyCodeObject *code = frame->f_code;
1421 int now_in_importlib;
1422
1423 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001424 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1425 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001426 if (now_in_importlib && !in_importlib) {
1427 /* This is the link to this chunk of importlib tracebacks */
1428 outer_link = prev_link;
1429 }
1430 in_importlib = now_in_importlib;
1431
1432 if (in_importlib &&
1433 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001434 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001435 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001436 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001437 prev_link = outer_link;
1438 }
1439 else {
1440 prev_link = (PyObject **) &traceback->tb_next;
1441 }
1442 tb = next;
1443 }
1444done:
1445 PyErr_Restore(exception, value, base_tb);
1446}
1447
1448
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001449static PyObject *
1450resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001451{
Eric Snowb523f842013-11-22 09:05:39 -07001452 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001453 _Py_IDENTIFIER(__package__);
1454 _Py_IDENTIFIER(__path__);
1455 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001456 _Py_IDENTIFIER(parent);
1457 PyObject *abs_name;
1458 PyObject *package = NULL;
1459 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001460 Py_ssize_t last_dot;
1461 PyObject *base;
1462 int level_up;
1463
1464 if (globals == NULL) {
1465 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1466 goto error;
1467 }
1468 if (!PyDict_Check(globals)) {
1469 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1470 goto error;
1471 }
1472 package = _PyDict_GetItemId(globals, &PyId___package__);
1473 if (package == Py_None) {
1474 package = NULL;
1475 }
1476 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1477
1478 if (package != NULL) {
1479 Py_INCREF(package);
1480 if (!PyUnicode_Check(package)) {
1481 PyErr_SetString(PyExc_TypeError, "package must be a string");
1482 goto error;
1483 }
1484 else if (spec != NULL && spec != Py_None) {
1485 int equal;
1486 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1487 if (parent == NULL) {
1488 goto error;
1489 }
1490
1491 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1492 Py_DECREF(parent);
1493 if (equal < 0) {
1494 goto error;
1495 }
1496 else if (equal == 0) {
1497 if (PyErr_WarnEx(PyExc_ImportWarning,
1498 "__package__ != __spec__.parent", 1) < 0) {
1499 goto error;
1500 }
1501 }
1502 }
1503 }
1504 else if (spec != NULL && spec != Py_None) {
1505 package = _PyObject_GetAttrId(spec, &PyId_parent);
1506 if (package == NULL) {
1507 goto error;
1508 }
1509 else if (!PyUnicode_Check(package)) {
1510 PyErr_SetString(PyExc_TypeError,
1511 "__spec__.parent must be a string");
1512 goto error;
1513 }
1514 }
1515 else {
1516 if (PyErr_WarnEx(PyExc_ImportWarning,
1517 "can't resolve package from __spec__ or __package__, "
1518 "falling back on __name__ and __path__", 1) < 0) {
1519 goto error;
1520 }
1521
1522 package = _PyDict_GetItemId(globals, &PyId___name__);
1523 if (package == NULL) {
1524 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1525 goto error;
1526 }
1527
1528 Py_INCREF(package);
1529 if (!PyUnicode_Check(package)) {
1530 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1531 goto error;
1532 }
1533
1534 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1535 Py_ssize_t dot;
1536
1537 if (PyUnicode_READY(package) < 0) {
1538 goto error;
1539 }
1540
1541 dot = PyUnicode_FindChar(package, '.',
1542 0, PyUnicode_GET_LENGTH(package), -1);
1543 if (dot == -2) {
1544 goto error;
1545 }
1546
1547 if (dot >= 0) {
1548 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1549 if (substr == NULL) {
1550 goto error;
1551 }
1552 Py_SETREF(package, substr);
1553 }
1554 }
1555 }
1556
1557 last_dot = PyUnicode_GET_LENGTH(package);
1558 if (last_dot == 0) {
1559 PyErr_SetString(PyExc_ImportError,
1560 "attempted relative import with no known parent package");
1561 goto error;
1562 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001563
1564 for (level_up = 1; level_up < level; level_up += 1) {
1565 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1566 if (last_dot == -2) {
1567 goto error;
1568 }
1569 else if (last_dot == -1) {
1570 PyErr_SetString(PyExc_ValueError,
1571 "attempted relative import beyond top-level "
1572 "package");
1573 goto error;
1574 }
1575 }
1576
1577 base = PyUnicode_Substring(package, 0, last_dot);
1578 Py_DECREF(package);
1579 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1580 return base;
1581 }
1582
1583 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1584 Py_DECREF(base);
1585 return abs_name;
1586
1587 error:
1588 Py_XDECREF(package);
1589 return NULL;
1590}
1591
1592PyObject *
1593PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1594 PyObject *locals, PyObject *fromlist,
1595 int level)
1596{
Brett Cannonfd074152012-04-14 14:10:13 -04001597 _Py_IDENTIFIER(_find_and_load);
1598 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001599 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001600 PyObject *final_mod = NULL;
1601 PyObject *mod = NULL;
1602 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001603 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001604 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001605
Brett Cannonfd074152012-04-14 14:10:13 -04001606 if (name == NULL) {
1607 PyErr_SetString(PyExc_ValueError, "Empty module name");
1608 goto error;
1609 }
1610
1611 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1612 for added performance. */
1613
1614 if (!PyUnicode_Check(name)) {
1615 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1616 goto error;
1617 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001618 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001619 goto error;
1620 }
1621 if (level < 0) {
1622 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1623 goto error;
1624 }
Brett Cannon849113a2016-01-22 15:25:50 -08001625
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001626 if (level > 0) {
1627 abs_name = resolve_name(name, globals, level);
1628 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001629 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001630 }
1631 else { /* level == 0 */
1632 if (PyUnicode_GET_LENGTH(name) == 0) {
1633 PyErr_SetString(PyExc_ValueError, "Empty module name");
1634 goto error;
1635 }
Brett Cannonfd074152012-04-14 14:10:13 -04001636 abs_name = name;
1637 Py_INCREF(abs_name);
1638 }
1639
Eric Snow3f9eee62017-09-15 16:35:20 -06001640 mod = PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001641 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001642 _Py_IDENTIFIER(__spec__);
1643 _Py_IDENTIFIER(_initializing);
1644 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001645 PyObject *value = NULL;
1646 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001647 int initializing = 0;
1648
Antoine Pitrou03989852012-08-28 00:24:52 +02001649 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001650 __spec__._initializing is true.
1651 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001652 stuffing the new module in sys.modules.
1653 */
Eric Snowb523f842013-11-22 09:05:39 -07001654 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1655 if (spec != NULL) {
1656 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1657 Py_DECREF(spec);
1658 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001659 if (value == NULL)
1660 PyErr_Clear();
1661 else {
1662 initializing = PyObject_IsTrue(value);
1663 Py_DECREF(value);
1664 if (initializing == -1)
1665 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001666 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001667 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1668 &PyId__lock_unlock_module, abs_name,
1669 NULL);
1670 if (value == NULL)
1671 goto error;
1672 Py_DECREF(value);
1673 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001674 }
Brett Cannonfd074152012-04-14 14:10:13 -04001675 }
1676 else {
Serhiy Storchaka088929c2017-11-07 08:55:38 +02001677 /* 1 -- true, 0 -- false, -1 -- not initialized */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001678 int importtime = interp->core_config.importtime;
INADA Naoki1a87de72017-10-03 19:46:34 +09001679 static int import_level;
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -07001680 static _PyTime_t accumulated;
INADA Naoki1a87de72017-10-03 19:46:34 +09001681
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -07001682 _PyTime_t t1 = 0, accumulated_copy = accumulated;
INADA Naoki1a87de72017-10-03 19:46:34 +09001683
INADA Naoki1a87de72017-10-03 19:46:34 +09001684 /* XOptions is initialized after first some imports.
Serhiy Storchaka088929c2017-11-07 08:55:38 +02001685 * So we can't have negative cache before completed initialization.
1686 * Anyway, importlib._find_and_load is much slower than
1687 * _PyDict_GetItemIdWithError().
INADA Naoki1a87de72017-10-03 19:46:34 +09001688 */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001689 if (importtime) {
1690 static int header = 1;
1691 if (header) {
INADA Naoki1a87de72017-10-03 19:46:34 +09001692 fputs("import time: self [us] | cumulative | imported package\n",
1693 stderr);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001694 header = 0;
INADA Naoki1a87de72017-10-03 19:46:34 +09001695 }
INADA Naoki1a87de72017-10-03 19:46:34 +09001696
INADA Naoki1a87de72017-10-03 19:46:34 +09001697 import_level++;
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -07001698 t1 = _PyTime_GetPerfCounter();
INADA Naoki1a87de72017-10-03 19:46:34 +09001699 accumulated = 0;
1700 }
1701
Serhiy Storchaka088929c2017-11-07 08:55:38 +02001702 Py_XDECREF(mod);
1703
Christian Heimes3d2b4072017-09-30 00:53:19 +02001704 if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1705 PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1706
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001707 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001708 &PyId__find_and_load, abs_name,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001709 interp->import_func, NULL);
Christian Heimes3d2b4072017-09-30 00:53:19 +02001710
1711 if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1712 PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1713 mod != NULL);
1714
Victor Stinnera7368ac2017-11-15 18:11:45 -08001715 if (importtime) {
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -07001716 _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
INADA Naoki1a87de72017-10-03 19:46:34 +09001717
1718 import_level--;
1719 fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -07001720 (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1721 (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
INADA Naoki1a87de72017-10-03 19:46:34 +09001722 import_level*2, "", PyUnicode_AsUTF8(abs_name));
1723
1724 accumulated = accumulated_copy + cum;
1725 }
1726
Brett Cannonfd074152012-04-14 14:10:13 -04001727 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001728 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001729 }
1730 }
1731
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001732 has_from = 0;
1733 if (fromlist != NULL && fromlist != Py_None) {
1734 has_from = PyObject_IsTrue(fromlist);
1735 if (has_from < 0)
1736 goto error;
1737 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001738 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001739 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1740 if (level == 0 || len > 0) {
1741 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001742
Victor Stinner744c34e2016-05-20 11:36:13 +02001743 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1744 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001745 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001746 }
1747
Victor Stinner744c34e2016-05-20 11:36:13 +02001748 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001749 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001750 final_mod = mod;
1751 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001752 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001753 }
1754
Brett Cannonfd074152012-04-14 14:10:13 -04001755 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001756 PyObject *front = PyUnicode_Substring(name, 0, dot);
1757 if (front == NULL) {
1758 goto error;
1759 }
1760
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001761 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001762 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001763 }
1764 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001765 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001766 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001767 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001768 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001769 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001770 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001771 }
Brett Cannonfd074152012-04-14 14:10:13 -04001772
Eric Snow3f9eee62017-09-15 16:35:20 -06001773 final_mod = PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001774 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001775 if (final_mod == NULL) {
1776 PyErr_Format(PyExc_KeyError,
1777 "%R not in sys.modules as expected",
1778 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001779 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001780 }
Brett Cannonfd074152012-04-14 14:10:13 -04001781 }
1782 }
1783 else {
1784 final_mod = mod;
1785 Py_INCREF(mod);
1786 }
1787 }
1788 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001789 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001790 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001791 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001792 NULL);
1793 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001794
Brett Cannonfd074152012-04-14 14:10:13 -04001795 error:
1796 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001797 Py_XDECREF(mod);
1798 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001799 if (final_mod == NULL)
1800 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001801 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001802}
1803
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001804PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001805PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001806 PyObject *fromlist, int level)
1807{
1808 PyObject *nameobj, *mod;
1809 nameobj = PyUnicode_FromString(name);
1810 if (nameobj == NULL)
1811 return NULL;
1812 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1813 fromlist, level);
1814 Py_DECREF(nameobj);
1815 return mod;
1816}
1817
1818
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001819/* Re-import a module of any kind and return its module object, WITH
1820 INCREMENTED REFERENCE COUNT */
1821
Guido van Rossum79f25d91997-04-29 20:08:16 +00001822PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001823PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001824{
Eric Snow3f9eee62017-09-15 16:35:20 -06001825 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001826 _Py_IDENTIFIER(reload);
1827 PyObject *reloaded_module = NULL;
Eric Snow3f9eee62017-09-15 16:35:20 -06001828 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001829 if (imp == NULL) {
1830 imp = PyImport_ImportModule("imp");
1831 if (imp == NULL) {
1832 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001835
Victor Stinner55ba38a2016-12-09 16:09:30 +01001836 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001837 Py_DECREF(imp);
1838 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001839}
1840
1841
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001842/* Higher-level import emulator which emulates the "import" statement
1843 more accurately -- it invokes the __import__() function from the
1844 builtins of the current globals. This means that the import is
1845 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001846 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001847 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001848 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001849 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001850
1851PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001852PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 static PyObject *silly_list = NULL;
1855 static PyObject *builtins_str = NULL;
1856 static PyObject *import_str = NULL;
1857 PyObject *globals = NULL;
1858 PyObject *import = NULL;
1859 PyObject *builtins = NULL;
1860 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 /* Initialize constant string objects */
1863 if (silly_list == NULL) {
1864 import_str = PyUnicode_InternFromString("__import__");
1865 if (import_str == NULL)
1866 return NULL;
1867 builtins_str = PyUnicode_InternFromString("__builtins__");
1868 if (builtins_str == NULL)
1869 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001870 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (silly_list == NULL)
1872 return NULL;
1873 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 /* Get the builtins from current globals */
1876 globals = PyEval_GetGlobals();
1877 if (globals != NULL) {
1878 Py_INCREF(globals);
1879 builtins = PyObject_GetItem(globals, builtins_str);
1880 if (builtins == NULL)
1881 goto err;
1882 }
1883 else {
1884 /* No globals -- use standard builtins, and fake globals */
1885 builtins = PyImport_ImportModuleLevel("builtins",
1886 NULL, NULL, NULL, 0);
1887 if (builtins == NULL)
1888 return NULL;
1889 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1890 if (globals == NULL)
1891 goto err;
1892 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* Get the __import__ function from the builtins */
1895 if (PyDict_Check(builtins)) {
1896 import = PyObject_GetItem(builtins, import_str);
1897 if (import == NULL)
1898 PyErr_SetObject(PyExc_KeyError, import_str);
1899 }
1900 else
1901 import = PyObject_GetAttr(builtins, import_str);
1902 if (import == NULL)
1903 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001906 Always use absolute import here.
1907 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1909 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001910 if (r == NULL)
1911 goto err;
1912 Py_DECREF(r);
1913
Eric Snow3f9eee62017-09-15 16:35:20 -06001914 r = PyImport_GetModule(module_name);
1915 if (r == NULL && !PyErr_Occurred()) {
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001916 PyErr_SetObject(PyExc_KeyError, module_name);
1917 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001918
1919 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 Py_XDECREF(globals);
1921 Py_XDECREF(builtins);
1922 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001925}
1926
Brett Cannon4caa61d2014-01-09 19:03:32 -05001927/*[clinic input]
1928_imp.extension_suffixes
1929
1930Returns the list of file suffixes used to identify extension modules.
1931[clinic start generated code]*/
1932
Brett Cannon4caa61d2014-01-09 19:03:32 -05001933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001934_imp_extension_suffixes_impl(PyObject *module)
1935/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001938 const char *suffix;
1939 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 list = PyList_New(0);
1942 if (list == NULL)
1943 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001944#ifdef HAVE_DYNAMIC_LOADING
1945 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1946 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (item == NULL) {
1948 Py_DECREF(list);
1949 return NULL;
1950 }
1951 if (PyList_Append(list, item) < 0) {
1952 Py_DECREF(list);
1953 Py_DECREF(item);
1954 return NULL;
1955 }
1956 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001957 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 }
Brett Cannon2657df42012-05-04 15:20:40 -04001959#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001961}
1962
Brett Cannon4caa61d2014-01-09 19:03:32 -05001963/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001964_imp.init_frozen
1965
1966 name: unicode
1967 /
1968
1969Initializes a frozen module.
1970[clinic start generated code]*/
1971
Brett Cannon4caa61d2014-01-09 19:03:32 -05001972static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001973_imp_init_frozen_impl(PyObject *module, PyObject *name)
1974/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 int ret;
1977 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001978
Victor Stinner53dc7352011-03-20 01:50:21 +01001979 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (ret < 0)
1981 return NULL;
1982 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001983 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001985 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 Py_XINCREF(m);
1987 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001988}
1989
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990/*[clinic input]
1991_imp.get_frozen_object
1992
1993 name: unicode
1994 /
1995
1996Create a code object for a frozen module.
1997[clinic start generated code]*/
1998
Brett Cannon4caa61d2014-01-09 19:03:32 -05001999static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002000_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
2001/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002004}
2005
Brett Cannon4caa61d2014-01-09 19:03:32 -05002006/*[clinic input]
2007_imp.is_frozen_package
2008
2009 name: unicode
2010 /
2011
2012Returns True if the module name is of a frozen package.
2013[clinic start generated code]*/
2014
Brett Cannon4caa61d2014-01-09 19:03:32 -05002015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002016_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2017/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00002020}
2021
Brett Cannon4caa61d2014-01-09 19:03:32 -05002022/*[clinic input]
2023_imp.is_builtin
2024
2025 name: unicode
2026 /
2027
2028Returns True if the module name corresponds to a built-in module.
2029[clinic start generated code]*/
2030
Guido van Rossum79f25d91997-04-29 20:08:16 +00002031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002032_imp_is_builtin_impl(PyObject *module, PyObject *name)
2033/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002034{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002035 return PyLong_FromLong(is_builtin(name));
2036}
2037
2038/*[clinic input]
2039_imp.is_frozen
2040
2041 name: unicode
2042 /
2043
2044Returns True if the module name corresponds to a frozen module.
2045[clinic start generated code]*/
2046
Brett Cannon4caa61d2014-01-09 19:03:32 -05002047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002048_imp_is_frozen_impl(PyObject *module, PyObject *name)
2049/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002050{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002051 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 p = find_frozen(name);
2054 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002055}
2056
Larry Hastings1df0b352015-08-24 19:53:56 -07002057/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2058static int
2059exec_builtin_or_dynamic(PyObject *mod) {
2060 PyModuleDef *def;
2061 void *state;
2062
2063 if (!PyModule_Check(mod)) {
2064 return 0;
2065 }
2066
2067 def = PyModule_GetDef(mod);
2068 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002069 return 0;
2070 }
Brett Cannon52794db2016-09-07 17:00:43 -07002071
Larry Hastings1df0b352015-08-24 19:53:56 -07002072 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002073 if (state) {
2074 /* Already initialized; skip reload */
2075 return 0;
2076 }
Brett Cannon52794db2016-09-07 17:00:43 -07002077
Larry Hastings1df0b352015-08-24 19:53:56 -07002078 return PyModule_ExecDef(mod, def);
2079}
2080
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002081#ifdef HAVE_DYNAMIC_LOADING
2082
Brett Cannon4caa61d2014-01-09 19:03:32 -05002083/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002084_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002085
Nick Coghland5cacbb2015-05-23 22:24:10 +10002086 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002087 file: object = NULL
2088 /
2089
Nick Coghland5cacbb2015-05-23 22:24:10 +10002090Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002091[clinic start generated code]*/
2092
Brett Cannon4caa61d2014-01-09 19:03:32 -05002093static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002094_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2095/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002096{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002097 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002098 FILE *fp;
2099
Nick Coghland5cacbb2015-05-23 22:24:10 +10002100 name = PyObject_GetAttrString(spec, "name");
2101 if (name == NULL) {
2102 return NULL;
2103 }
2104
2105 path = PyObject_GetAttrString(spec, "origin");
2106 if (path == NULL) {
2107 Py_DECREF(name);
2108 return NULL;
2109 }
2110
2111 mod = _PyImport_FindExtensionObject(name, path);
2112 if (mod != NULL) {
2113 Py_DECREF(name);
2114 Py_DECREF(path);
2115 Py_INCREF(mod);
2116 return mod;
2117 }
2118
Brett Cannon4caa61d2014-01-09 19:03:32 -05002119 if (file != NULL) {
2120 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002121 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002122 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002123 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002125 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002127 else
2128 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002129
2130 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2131
2132 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002133 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (fp)
2135 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002136 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002137}
2138
Nick Coghland5cacbb2015-05-23 22:24:10 +10002139/*[clinic input]
2140_imp.exec_dynamic -> int
2141
2142 mod: object
2143 /
2144
2145Initialize an extension module.
2146[clinic start generated code]*/
2147
2148static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002149_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2150/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002151{
Larry Hastings1df0b352015-08-24 19:53:56 -07002152 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002153}
2154
2155
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002156#endif /* HAVE_DYNAMIC_LOADING */
2157
Larry Hastings7726ac92014-01-31 22:03:12 -08002158/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002159_imp.exec_builtin -> int
2160
2161 mod: object
2162 /
2163
2164Initialize a built-in module.
2165[clinic start generated code]*/
2166
2167static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002168_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2169/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002170{
2171 return exec_builtin_or_dynamic(mod);
2172}
2173
Barry Warsaw28a691b2010-04-17 00:19:56 +00002174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002175PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002176"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002177
Guido van Rossum79f25d91997-04-29 20:08:16 +00002178static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002179 _IMP_EXTENSION_SUFFIXES_METHODDEF
2180 _IMP_LOCK_HELD_METHODDEF
2181 _IMP_ACQUIRE_LOCK_METHODDEF
2182 _IMP_RELEASE_LOCK_METHODDEF
2183 _IMP_GET_FROZEN_OBJECT_METHODDEF
2184 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002185 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002186 _IMP_INIT_FROZEN_METHODDEF
2187 _IMP_IS_BUILTIN_METHODDEF
2188 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002189 _IMP_CREATE_DYNAMIC_METHODDEF
2190 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002191 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002192 _IMP__FIX_CO_FILENAME_METHODDEF
2193 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002194};
2195
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002196
Martin v. Löwis1a214512008-06-11 05:26:20 +00002197static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002199 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 doc_imp,
2201 0,
2202 imp_methods,
2203 NULL,
2204 NULL,
2205 NULL,
2206 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002207};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002208
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002209PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002210PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 m = PyModule_Create(&impmodule);
2215 if (m == NULL)
2216 goto failure;
2217 d = PyModule_GetDict(m);
2218 if (d == NULL)
2219 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002222 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 Py_XDECREF(m);
2224 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002225}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002226
2227
Guido van Rossumb18618d2000-05-03 23:44:39 +00002228/* API for embedding applications that want to add their own entries
2229 to the table of built-in modules. This should normally be called
2230 *before* Py_Initialize(). When the table resize fails, -1 is
2231 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002232
2233 After a similar function by Just van Rossum. */
2234
2235int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002236PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 static struct _inittab *our_copy = NULL;
2239 struct _inittab *p;
2240 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 /* Count the number of entries in both tables */
2243 for (n = 0; newtab[n].name != NULL; n++)
2244 ;
2245 if (n == 0)
2246 return 0; /* Nothing to do */
2247 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2248 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 /* Allocate new memory for the combined table */
2251 p = our_copy;
2252 PyMem_RESIZE(p, struct _inittab, i+n+1);
2253 if (p == NULL)
2254 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* Copy the tables into the new memory */
2257 if (our_copy != PyImport_Inittab)
2258 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2259 PyImport_Inittab = our_copy = p;
2260 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002263}
2264
2265/* Shorthand to add a single entry given a name and a function */
2266
2267int
Brett Cannona826f322009-04-02 03:41:46 +00002268PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002273
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002274 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002278}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002279
2280#ifdef __cplusplus
2281}
2282#endif