blob: 6b2634c3497afb1fc14f98649f6c0a885ba8b8a7 [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"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000015
Guido van Rossum55a83382000-09-20 20:31:38 +000016#ifdef HAVE_FCNTL_H
17#include <fcntl.h>
18#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019#ifdef __cplusplus
Brett Cannon9a5b25a2010-03-01 02:09:17 +000020extern "C" {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000022
Barry Warsaw28a691b2010-04-17 00:19:56 +000023#define CACHEDIR "__pycache__"
Guido van Rossum96774c12000-05-01 20:19:08 +000024
Victor Stinner95872862011-03-07 18:20:56 +010025/* See _PyImport_FixupExtensionObject() below */
Guido van Rossum25ce5661997-08-02 03:10:38 +000026static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000027
Guido van Rossum771c6c81997-10-31 18:37:24 +000028/* This table is defined in config.c: */
29extern struct _inittab _PyImport_Inittab[];
30
31struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000032
Victor Stinnerd0296212011-03-14 14:04:10 -040033static PyObject *initstr = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000034
Brett Cannon4caa61d2014-01-09 19:03:32 -050035/*[clinic input]
36module _imp
37[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030038/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
Brett Cannonfd4d0502014-05-30 11:21:14 -040039
40#include "clinic/import.c.h"
Brett Cannon4caa61d2014-01-09 19:03:32 -050041
Guido van Rossum1ae940a1995-01-02 19:04:15 +000042/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043
44void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000045_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046{
Serhiy Storchaka013bb912014-02-10 18:21:34 +020047 PyInterpreterState *interp = PyThreadState_Get()->interp;
Victor Stinnerd0296212011-03-14 14:04:10 -040048 initstr = PyUnicode_InternFromString("__init__");
49 if (initstr == NULL)
50 Py_FatalError("Can't initialize import variables");
Serhiy Storchaka013bb912014-02-10 18:21:34 +020051 interp->builtins_copy = PyDict_Copy(interp->builtins);
52 if (interp->builtins_copy == NULL)
53 Py_FatalError("Can't backup builtins dict");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054}
55
Guido van Rossum25ce5661997-08-02 03:10:38 +000056void
Just van Rossum52e14d62002-12-30 22:08:05 +000057_PyImportHooks_Init(void)
58{
Brett Cannonfd074152012-04-14 14:10:13 -040059 PyObject *v, *path_hooks = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 int err = 0;
Just van Rossum52e14d62002-12-30 22:08:05 +000061
Brett Cannonfd074152012-04-14 14:10:13 -040062 /* adding sys.path_hooks and sys.path_importer_cache */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 v = PyList_New(0);
64 if (v == NULL)
65 goto error;
66 err = PySys_SetObject("meta_path", v);
67 Py_DECREF(v);
68 if (err)
69 goto error;
70 v = PyDict_New();
71 if (v == NULL)
72 goto error;
73 err = PySys_SetObject("path_importer_cache", v);
74 Py_DECREF(v);
75 if (err)
76 goto error;
77 path_hooks = PyList_New(0);
78 if (path_hooks == NULL)
79 goto error;
80 err = PySys_SetObject("path_hooks", path_hooks);
81 if (err) {
Just van Rossum52e14d62002-12-30 22:08:05 +000082 error:
Brett Cannonfd074152012-04-14 14:10:13 -040083 PyErr_Print();
84 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
Nadeem Vawda8f46d652012-05-05 12:27:30 +020085 "or path_importer_cache failed");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 }
Brett Cannonfd074152012-04-14 14:10:13 -040087 Py_DECREF(path_hooks);
88}
89
90void
91_PyImportZip_Init(void)
92{
93 PyObject *path_hooks, *zimpimport;
94 int err = 0;
95
96 path_hooks = PySys_GetObject("path_hooks");
Victor Stinner1e53bba2013-07-16 22:26:05 +020097 if (path_hooks == NULL) {
98 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path_hooks");
Brett Cannonfd074152012-04-14 14:10:13 -040099 goto error;
Victor Stinner1e53bba2013-07-16 22:26:05 +0200100 }
Brett Cannonfd074152012-04-14 14:10:13 -0400101
102 if (Py_VerboseFlag)
103 PySys_WriteStderr("# installing zipimport hook\n");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 zimpimport = PyImport_ImportModule("zipimport");
106 if (zimpimport == NULL) {
107 PyErr_Clear(); /* No zip import module -- okay */
108 if (Py_VerboseFlag)
109 PySys_WriteStderr("# can't import zipimport\n");
110 }
111 else {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200112 _Py_IDENTIFIER(zipimporter);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200113 PyObject *zipimporter = _PyObject_GetAttrId(zimpimport,
114 &PyId_zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_DECREF(zimpimport);
116 if (zipimporter == NULL) {
117 PyErr_Clear(); /* No zipimporter object -- okay */
118 if (Py_VerboseFlag)
119 PySys_WriteStderr(
120 "# can't import zipimport.zipimporter\n");
121 }
122 else {
Brett Cannon8923a4d2012-04-24 22:03:46 -0400123 /* sys.path_hooks.insert(0, zipimporter) */
124 err = PyList_Insert(path_hooks, 0, zipimporter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 Py_DECREF(zipimporter);
Brett Cannonfd074152012-04-14 14:10:13 -0400126 if (err < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -0400128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 if (Py_VerboseFlag)
130 PySys_WriteStderr(
131 "# installed zipimport hook\n");
132 }
133 }
Brett Cannonfd074152012-04-14 14:10:13 -0400134
135 return;
136
137 error:
138 PyErr_Print();
Brett Cannonacf85cd2012-04-29 12:50:03 -0400139 Py_FatalError("initializing zipimport failed");
Just van Rossum52e14d62002-12-30 22:08:05 +0000140}
141
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000142/* Locking primitives to prevent parallel imports of the same module
143 in different threads to return with a partially loaded module.
144 These calls are serialized by the global interpreter lock. */
145
Guido van Rossum49b56061998-10-01 20:42:43 +0000146#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000147
Guido van Rossum65d5b571998-12-21 19:32:43 +0000148static PyThread_type_lock import_lock = 0;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200149static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000150static int import_lock_level = 0;
151
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000152void
153_PyImport_AcquireLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000154{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200155 unsigned long me = PyThread_get_thread_ident();
156 if (me == PYTHREAD_INVALID_THREAD_ID)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 return; /* Too bad */
158 if (import_lock == NULL) {
159 import_lock = PyThread_allocate_lock();
160 if (import_lock == NULL)
161 return; /* Nothing much we can do. */
162 }
163 if (import_lock_thread == me) {
164 import_lock_level++;
165 return;
166 }
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200167 if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
168 !PyThread_acquire_lock(import_lock, 0))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 {
170 PyThreadState *tstate = PyEval_SaveThread();
171 PyThread_acquire_lock(import_lock, 1);
172 PyEval_RestoreThread(tstate);
173 }
Antoine Pitrou202b6062012-12-18 22:18:17 +0100174 assert(import_lock_level == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 import_lock_thread = me;
176 import_lock_level = 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000177}
178
Benjamin Peterson0df35a92009-10-04 20:32:25 +0000179int
180_PyImport_ReleaseLock(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000181{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200182 unsigned long me = PyThread_get_thread_ident();
183 if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return 0; /* Too bad */
185 if (import_lock_thread != me)
186 return -1;
187 import_lock_level--;
Antoine Pitrou202b6062012-12-18 22:18:17 +0100188 assert(import_lock_level >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (import_lock_level == 0) {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200190 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyThread_release_lock(import_lock);
192 }
193 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000194}
195
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200196/* This function is called from PyOS_AfterFork_Child to ensure that newly
Gregory P. Smith24cec9f2010-03-01 06:18:41 +0000197 created child processes do not share locks with the parent.
198 We now acquire the import lock around fork() calls but on some platforms
199 (Solaris 9 and earlier? see isue7242) that still left us with problems. */
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000200
201void
202_PyImport_ReInitLock(void)
203{
Christian Heimes418fd742015-04-19 21:08:42 +0200204 if (import_lock != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 import_lock = PyThread_allocate_lock();
Christian Heimes418fd742015-04-19 21:08:42 +0200206 if (import_lock == NULL) {
207 Py_FatalError("PyImport_ReInitLock failed to create a new lock");
208 }
209 }
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000210 if (import_lock_level > 1) {
211 /* Forked as a side effect of import */
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200212 unsigned long me = PyThread_get_thread_ident();
Brett Cannone4710cf2012-11-15 21:39:36 -0500213 /* The following could fail if the lock is already held, but forking as
214 a side-effect of an import is a) rare, b) nuts, and c) difficult to
215 do thanks to the lock only being held when doing individual module
216 locks per import. */
217 PyThread_acquire_lock(import_lock, NOWAIT_LOCK);
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000218 import_lock_thread = me;
219 import_lock_level--;
220 } else {
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200221 import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
Nick Coghlanb2ddf792010-12-02 04:11:46 +0000222 import_lock_level = 0;
223 }
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000224}
225
Brett Cannon4caa61d2014-01-09 19:03:32 -0500226/*[clinic input]
227_imp.lock_held
228
229Return True if the import lock is currently held, else False.
230
231On platforms without threads, return False.
232[clinic start generated code]*/
233
Brett Cannon4caa61d2014-01-09 19:03:32 -0500234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300235_imp_lock_held_impl(PyObject *module)
236/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
Tim Peters69232342001-08-30 05:16:13 +0000237{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200238 return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
Tim Peters69232342001-08-30 05:16:13 +0000239}
240
Brett Cannon4caa61d2014-01-09 19:03:32 -0500241/*[clinic input]
242_imp.acquire_lock
243
244Acquires the interpreter's import lock for the current thread.
245
246This lock should be used by import hooks to ensure thread-safety when importing
247modules. On platforms without threads, this function does nothing.
248[clinic start generated code]*/
249
Brett Cannon4caa61d2014-01-09 19:03:32 -0500250static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300251_imp_acquire_lock_impl(PyObject *module)
252/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 _PyImport_AcquireLock();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200255 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000256}
257
Brett Cannon4caa61d2014-01-09 19:03:32 -0500258/*[clinic input]
259_imp.release_lock
260
261Release the interpreter's import lock.
262
263On platforms without threads, this function does nothing.
264[clinic start generated code]*/
265
Brett Cannon4caa61d2014-01-09 19:03:32 -0500266static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300267_imp_release_lock_impl(PyObject *module)
268/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (_PyImport_ReleaseLock() < 0) {
271 PyErr_SetString(PyExc_RuntimeError,
272 "not holding the import lock");
273 return NULL;
274 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200275 Py_RETURN_NONE;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000276}
277
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100278void
279_PyImport_Fini(void)
280{
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200281 Py_CLEAR(extensions);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100282 if (import_lock != NULL) {
283 PyThread_free_lock(import_lock);
284 import_lock = NULL;
285 }
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100286}
287
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288/* Helper for sys */
289
290PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000291PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000292{
Eric Snow86b7afd2017-09-04 17:54:09 -0600293 PyObject *sysdict = PyThreadState_GET()->interp->sysdict;
294 if (sysdict == NULL) {
295 Py_FatalError("PyImport_GetModuleDict: no sys module!");
296 }
297
298 _Py_IDENTIFIER(modules);
299 PyObject *modules = _PyDict_GetItemId(sysdict, &PyId_modules);
300 if (modules == NULL) {
301 Py_FatalError("lost sys.modules");
302 }
303 return modules;
304}
305
306/* In some corner cases it is important to be sure that the import
307 machinery has been initialized (or not cleaned up yet). For
308 example, see issue #4236 and PyModule_Create2(). */
309
310int
311_PyImport_IsInitialized(PyInterpreterState *interp)
312{
313 if (interp->sysdict == NULL)
314 return 0;
315 _Py_IDENTIFIER(modules);
316 PyObject *modules = _PyDict_GetItemId(interp->sysdict, &PyId_modules);
317 if (modules == NULL)
318 return 0;
319 return 1;
320}
321
322PyObject *
323_PyImport_GetModule(PyObject *name)
324{
325 PyObject *modules = PyImport_GetModuleDict();
326 if (PyDict_CheckExact(modules)) {
327 return PyDict_GetItem(modules, name);
328 }
329
330 PyObject *mod = PyObject_GetItem(modules, name);
331 // For backward-comaptibility we copy the behavior of PyDict_GetItem().
332 if (PyErr_Occurred()) {
333 PyErr_Clear();
334 }
335 Py_XDECREF(mod);
336 return mod;
337}
338
339PyObject *
340_PyImport_GetModuleWithError(PyObject *name)
341{
342 PyObject *modules = PyImport_GetModuleDict();
343 if (PyDict_CheckExact(modules)) {
344 return PyDict_GetItemWithError(modules, name);
345 }
346
347 PyObject *mod = PyObject_GetItem(modules, name);
348 // For backward-comaptibility we copy the behavior
349 // of PyDict_GetItemWithError().
350 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
351 PyErr_Clear();
352 }
353 return mod;
354}
355
356PyObject *
357_PyImport_GetModuleId(struct _Py_Identifier *nameid)
358{
359 PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
360 if (name == NULL) {
361 return NULL;
362 }
363 return _PyImport_GetModule(name);
364}
365
366int
367_PyImport_SetModule(PyObject *name, PyObject *m)
368{
369 PyObject *modules = PyImport_GetModuleDict();
370 return PyObject_SetItem(modules, name, m);
371}
372
373int
374_PyImport_SetModuleString(const char *name, PyObject *m)
375{
376 PyObject *modules = PyImport_GetModuleDict();
377 return PyMapping_SetItemString(modules, name, m);
378}
379
380PyObject *
381PyImport_GetModule(PyObject *name)
382{
383 PyObject *m;
384 PyObject *modules = PyImport_GetModuleDict();
385 if (modules == NULL) {
386 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
387 return NULL;
388 }
389 Py_INCREF(modules);
390 if (PyDict_CheckExact(modules)) {
391 m = PyDict_GetItemWithError(modules, name); /* borrowed */
392 Py_XINCREF(m);
393 }
394 else {
395 m = PyObject_GetItem(modules, name);
396 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
397 PyErr_Clear();
398 }
399 }
400 Py_DECREF(modules);
401 return m;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000402}
403
Guido van Rossum3f5da241990-12-20 15:06:42 +0000404
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405/* List of names to clear in sys */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200406static const char * const sys_deletes[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 "path", "argv", "ps1", "ps2",
408 "last_type", "last_value", "last_traceback",
409 "path_hooks", "path_importer_cache", "meta_path",
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200410 "__interactivehook__",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* misc stuff */
412 "flags", "float_info",
413 NULL
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000414};
415
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200416static const char * const sys_files[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 "stdin", "__stdin__",
418 "stdout", "__stdout__",
419 "stderr", "__stderr__",
420 NULL
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000421};
422
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000423/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000424
Guido van Rossum3f5da241990-12-20 15:06:42 +0000425void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000426PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000427{
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200428 Py_ssize_t pos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyObject *key, *value, *dict;
430 PyInterpreterState *interp = PyThreadState_GET()->interp;
Eric Snow86b7afd2017-09-04 17:54:09 -0600431 PyObject *modules = PyImport_GetModuleDict();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200432 PyObject *weaklist = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200433 const char * const *p;
Guido van Rossum758eec01998-01-19 21:58:26 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (modules == NULL)
436 return; /* Already done */
Guido van Rossum758eec01998-01-19 21:58:26 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* Delete some special variables first. These are common
439 places where user values hide and people complain when their
440 destructors fail. Since the modules containing them are
441 deleted *last* of all, they would come too late in the normal
442 destruction order. Sigh. */
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000443
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200444 /* XXX Perhaps these precautions are obsolete. Who knows? */
445
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200446 if (Py_VerboseFlag)
447 PySys_WriteStderr("# clear builtins._\n");
448 PyDict_SetItemString(interp->builtins, "_", Py_None);
449
450 for (p = sys_deletes; *p != NULL; p++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (Py_VerboseFlag)
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200452 PySys_WriteStderr("# clear sys.%s\n", *p);
453 PyDict_SetItemString(interp->sysdict, *p, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 }
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200455 for (p = sys_files; *p != NULL; p+=2) {
456 if (Py_VerboseFlag)
457 PySys_WriteStderr("# restore sys.%s\n", *p);
458 value = PyDict_GetItemString(interp->sysdict, *(p+1));
459 if (value == NULL)
460 value = Py_None;
461 PyDict_SetItemString(interp->sysdict, *p, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000463
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200464 /* We prepare a list which will receive (name, weakref) tuples of
465 modules when they are removed from sys.modules. The name is used
466 for diagnosis messages (in verbose mode), while the weakref helps
467 detect those modules which have been held alive. */
468 weaklist = PyList_New(0);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200469 if (weaklist == NULL)
470 PyErr_Clear();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200471
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200472#define STORE_MODULE_WEAKREF(name, mod) \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200473 if (weaklist != NULL) { \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200474 PyObject *wr = PyWeakref_NewRef(mod, NULL); \
475 if (name && wr) { \
476 PyObject *tup = PyTuple_Pack(2, name, wr); \
477 PyList_Append(weaklist, tup); \
478 Py_XDECREF(tup); \
479 } \
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200480 Py_XDECREF(wr); \
481 if (PyErr_Occurred()) \
482 PyErr_Clear(); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000484
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200485 /* Remove all modules from sys.modules, hoping that garbage collection
486 can reclaim most of them. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 pos = 0;
488 while (PyDict_Next(modules, &pos, &key, &value)) {
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200489 if (PyModule_Check(value)) {
490 if (Py_VerboseFlag && PyUnicode_Check(key))
Victor Stinnerab826d12014-07-07 23:06:15 +0200491 PySys_FormatStderr("# cleanup[2] removing %U\n", key);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200492 STORE_MODULE_WEAKREF(key, value);
Eric Snow86b7afd2017-09-04 17:54:09 -0600493 PyObject_SetItem(modules, key, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000496
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200497 /* Clear the modules dict. */
498 PyDict_Clear(modules);
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200499 /* Restore the original builtins dict, to ensure that any
500 user data gets cleared. */
501 dict = PyDict_Copy(interp->builtins);
502 if (dict == NULL)
503 PyErr_Clear();
504 PyDict_Clear(interp->builtins);
505 if (PyDict_Update(interp->builtins, interp->builtins_copy))
506 PyErr_Clear();
507 Py_XDECREF(dict);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200508 /* Clear module dict copies stored in the interpreter state */
509 _PyState_ClearModules();
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200510 /* Collect references */
511 _PyGC_CollectNoFail();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200512 /* Dump GC stats before it's too late, since it uses the warnings
513 machinery. */
514 _PyGC_DumpShutdownStats();
515
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200516 /* Now, if there are any modules left alive, clear their globals to
517 minimize potential leaks. All C extension modules actually end
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200518 up here, since they are kept alive in the interpreter state.
519
520 The special treatment of "builtins" here is because even
521 when it's not referenced as a module, its dictionary is
522 referenced by almost every module's __builtins__. Since
523 deleting a module clears its dictionary (even if there are
524 references left to it), we need to delete the "builtins"
525 module last. Likewise, we don't delete sys until the very
526 end because it is implicitly referenced (e.g. by print). */
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200527 if (weaklist != NULL) {
528 Py_ssize_t i, n;
529 n = PyList_GET_SIZE(weaklist);
530 for (i = 0; i < n; i++) {
531 PyObject *tup = PyList_GET_ITEM(weaklist, i);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200532 PyObject *name = PyTuple_GET_ITEM(tup, 0);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200533 PyObject *mod = PyWeakref_GET_OBJECT(PyTuple_GET_ITEM(tup, 1));
534 if (mod == Py_None)
535 continue;
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200536 assert(PyModule_Check(mod));
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200537 dict = PyModule_GetDict(mod);
538 if (dict == interp->builtins || dict == interp->sysdict)
539 continue;
540 Py_INCREF(mod);
Antoine Pitrou79ba3882013-08-06 22:50:15 +0200541 if (Py_VerboseFlag && PyUnicode_Check(name))
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200542 PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200543 _PyModule_Clear(mod);
544 Py_DECREF(mod);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200545 }
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200546 Py_DECREF(weaklist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000548
Serhiy Storchaka013bb912014-02-10 18:21:34 +0200549 /* Next, delete sys and builtins (in that order) */
550 if (Py_VerboseFlag)
551 PySys_FormatStderr("# cleanup[3] wiping sys\n");
552 _PyModule_ClearDict(interp->sysdict);
553 if (Py_VerboseFlag)
554 PySys_FormatStderr("# cleanup[3] wiping builtins\n");
555 _PyModule_ClearDict(interp->builtins);
556
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200557 /* Clear and delete the modules directory. Actual modules will
558 still be there only if imported during the execution of some
559 destructor. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 Py_DECREF(modules);
Antoine Pitroudcedaf62013-07-31 23:14:08 +0200561
562 /* Once more */
563 _PyGC_CollectNoFail();
564
565#undef STORE_MODULE_WEAKREF
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000566}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000567
568
Barry Warsaw28a691b2010-04-17 00:19:56 +0000569/* Helper for pythonrun.c -- return magic number and tag. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000570
571long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573{
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200574 long res;
Brett Cannon77b2abd2012-07-09 16:09:00 -0400575 PyInterpreterState *interp = PyThreadState_Get()->interp;
Eric Snow32439d62015-05-02 19:15:18 -0600576 PyObject *external, *pyc_magic;
577
578 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
579 if (external == NULL)
580 return -1;
581 pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
582 Py_DECREF(external);
Brett Cannon77b2abd2012-07-09 16:09:00 -0400583 if (pyc_magic == NULL)
584 return -1;
Antoine Pitrou44b4b6a2012-07-10 18:27:54 +0200585 res = PyLong_AsLong(pyc_magic);
Benjamin Peterson66f36592012-07-09 22:21:55 -0700586 Py_DECREF(pyc_magic);
587 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000588}
589
590
Brett Cannon3adc7b72012-07-09 14:22:12 -0400591extern const char * _PySys_ImplCacheTag;
592
Barry Warsaw28a691b2010-04-17 00:19:56 +0000593const char *
594PyImport_GetMagicTag(void)
595{
Brett Cannon3adc7b72012-07-09 14:22:12 -0400596 return _PySys_ImplCacheTag;
Barry Warsaw28a691b2010-04-17 00:19:56 +0000597}
598
Brett Cannon98979b82012-07-02 15:13:11 -0400599
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600/* Magic for extension modules (built-in as well as dynamically
601 loaded). To prevent initializing an extension module more than
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200602 once, we keep a static dictionary 'extensions' keyed by the tuple
603 (module name, module name) (for built-in modules) or by
604 (filename, module name) (for dynamically loaded modules), containing these
605 modules. A copy of the module's dictionary is stored by calling
606 _PyImport_FixupExtensionObject() immediately after the module initialization
607 function succeeds. A copy can be retrieved from there by calling
Victor Stinner95872862011-03-07 18:20:56 +0100608 _PyImport_FindExtensionObject().
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609
Barry Warsaw7c9627b2010-06-17 18:38:20 +0000610 Modules which do support multiple initialization set their m_size
611 field to a non-negative number (indicating the size of the
612 module-specific state). They are still recorded in the extensions
613 dictionary, to avoid loading shared libraries twice.
Martin v. Löwis1a214512008-06-11 05:26:20 +0000614*/
615
616int
Victor Stinner95872862011-03-07 18:20:56 +0100617_PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
Eric Snow86b7afd2017-09-04 17:54:09 -0600618 PyObject *filename, PyObject *modules)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000619{
Eric Snow86b7afd2017-09-04 17:54:09 -0600620 PyObject *dict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 struct PyModuleDef *def;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500622 int res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 if (extensions == NULL) {
624 extensions = PyDict_New();
625 if (extensions == NULL)
626 return -1;
627 }
628 if (mod == NULL || !PyModule_Check(mod)) {
629 PyErr_BadInternalCall();
630 return -1;
631 }
632 def = PyModule_GetDef(mod);
633 if (!def) {
634 PyErr_BadInternalCall();
635 return -1;
636 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600637 if (PyObject_SetItem(modules, name, mod) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return -1;
639 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow86b7afd2017-09-04 17:54:09 -0600640 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return -1;
642 }
643 if (def->m_size == -1) {
644 if (def->m_base.m_copy) {
645 /* Somebody already imported the module,
646 likely under a different name.
647 XXX this should really not happen. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200648 Py_CLEAR(def->m_base.m_copy);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
650 dict = PyModule_GetDict(mod);
651 if (dict == NULL)
652 return -1;
653 def->m_base.m_copy = PyDict_Copy(dict);
654 if (def->m_base.m_copy == NULL)
655 return -1;
656 }
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500657 key = PyTuple_Pack(2, filename, name);
658 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200659 return -1;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500660 res = PyDict_SetItem(extensions, key, (PyObject *)def);
661 Py_DECREF(key);
662 if (res < 0)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200663 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000665}
666
Victor Stinner49d3f252010-10-17 01:24:53 +0000667int
Eric Snow86b7afd2017-09-04 17:54:09 -0600668_PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000669{
670 int res;
Victor Stinner95872862011-03-07 18:20:56 +0100671 PyObject *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100672 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100673 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000674 return -1;
Eric Snow86b7afd2017-09-04 17:54:09 -0600675 res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100676 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000677 return res;
678}
679
Guido van Rossum25ce5661997-08-02 03:10:38 +0000680PyObject *
Victor Stinner95872862011-03-07 18:20:56 +0100681_PyImport_FindExtensionObject(PyObject *name, PyObject *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000682{
Eric Snow86b7afd2017-09-04 17:54:09 -0600683 PyObject *modules = PyImport_GetModuleDict();
684 return _PyImport_FindExtensionObjectEx(name, filename, modules);
685}
686
687PyObject *
688_PyImport_FindExtensionObjectEx(PyObject *name, PyObject *filename,
689 PyObject *modules)
690{
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500691 PyObject *mod, *mdict, *key;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyModuleDef* def;
693 if (extensions == NULL)
694 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500695 key = PyTuple_Pack(2, filename, name);
696 if (key == NULL)
Andrew Svetlov6b2cbeb2012-12-14 17:04:59 +0200697 return NULL;
Benjamin Peterson5cb8a312012-12-15 00:05:16 -0500698 def = (PyModuleDef *)PyDict_GetItem(extensions, key);
699 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (def == NULL)
701 return NULL;
702 if (def->m_size == -1) {
703 /* Module does not support repeated initialization */
704 if (def->m_base.m_copy == NULL)
705 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600706 mod = _PyImport_AddModuleObject(name, modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (mod == NULL)
708 return NULL;
709 mdict = PyModule_GetDict(mod);
710 if (mdict == NULL)
711 return NULL;
712 if (PyDict_Update(mdict, def->m_base.m_copy))
713 return NULL;
714 }
715 else {
716 if (def->m_base.m_init == NULL)
717 return NULL;
718 mod = def->m_base.m_init();
719 if (mod == NULL)
720 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600721 if (PyObject_SetItem(modules, name, mod) == -1) {
Christian Heimes09ca7942013-07-20 14:51:53 +0200722 Py_DECREF(mod);
723 return NULL;
724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 Py_DECREF(mod);
726 }
727 if (_PyState_AddModule(mod, def) < 0) {
Eric Snow86b7afd2017-09-04 17:54:09 -0600728 PyMapping_DelItem(modules, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 Py_DECREF(mod);
730 return NULL;
731 }
732 if (Py_VerboseFlag)
Victor Stinner95872862011-03-07 18:20:56 +0100733 PySys_FormatStderr("import %U # previously loaded (%R)\n",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 name, filename);
735 return mod;
Brett Cannon9a5b25a2010-03-01 02:09:17 +0000736
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737}
738
Victor Stinner49d3f252010-10-17 01:24:53 +0000739PyObject *
Eric Snow86b7afd2017-09-04 17:54:09 -0600740_PyImport_FindBuiltin(const char *name, PyObject *modules)
Victor Stinner49d3f252010-10-17 01:24:53 +0000741{
Victor Stinner95872862011-03-07 18:20:56 +0100742 PyObject *res, *nameobj;
Victor Stinner21fcd0c2011-03-07 18:28:15 +0100743 nameobj = PyUnicode_InternFromString(name);
Victor Stinner95872862011-03-07 18:20:56 +0100744 if (nameobj == NULL)
Victor Stinner49d3f252010-10-17 01:24:53 +0000745 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600746 res = _PyImport_FindExtensionObjectEx(nameobj, nameobj, modules);
Victor Stinner95872862011-03-07 18:20:56 +0100747 Py_DECREF(nameobj);
Victor Stinner49d3f252010-10-17 01:24:53 +0000748 return res;
749}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750
751/* Get the module object corresponding to a module name.
752 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000753 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000754 Because the former action is most common, THIS DOES NOT RETURN A
755 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000756
Guido van Rossum79f25d91997-04-29 20:08:16 +0000757PyObject *
Victor Stinner27ee0892011-03-04 12:57:09 +0000758PyImport_AddModuleObject(PyObject *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *modules = PyImport_GetModuleDict();
Eric Snow86b7afd2017-09-04 17:54:09 -0600761 return _PyImport_AddModuleObject(name, modules);
762}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763
Eric Snow86b7afd2017-09-04 17:54:09 -0600764PyObject *
765_PyImport_AddModuleObject(PyObject *name, PyObject *modules)
766{
767 PyObject *m;
768 if (PyDict_CheckExact(modules)) {
769 m = PyDict_GetItemWithError(modules, name);
770 }
771 else {
772 m = PyObject_GetItem(modules, name);
773 // For backward-comaptibility we copy the behavior
774 // of PyDict_GetItemWithError().
775 if (PyErr_ExceptionMatches(PyExc_KeyError)) {
776 PyErr_Clear();
777 }
Serhiy Storchaka48a583b2016-02-10 10:31:20 +0200778 }
779 if (PyErr_Occurred()) {
780 return NULL;
781 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600782 if (m != NULL && PyModule_Check(m)) {
783 return m;
784 }
Victor Stinner27ee0892011-03-04 12:57:09 +0000785 m = PyModule_NewObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (m == NULL)
787 return NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -0600788 if (PyObject_SetItem(modules, name, m) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_DECREF(m);
790 return NULL;
791 }
792 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000795}
796
Victor Stinner27ee0892011-03-04 12:57:09 +0000797PyObject *
798PyImport_AddModule(const char *name)
799{
800 PyObject *nameobj, *module;
801 nameobj = PyUnicode_FromString(name);
802 if (nameobj == NULL)
803 return NULL;
804 module = PyImport_AddModuleObject(nameobj);
805 Py_DECREF(nameobj);
806 return module;
807}
808
809
Tim Peters1cd70172004-08-02 03:52:12 +0000810/* Remove name from sys.modules, if it's there. */
811static void
Victor Stinner27ee0892011-03-04 12:57:09 +0000812remove_module(PyObject *name)
Tim Peters1cd70172004-08-02 03:52:12 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyObject *modules = PyImport_GetModuleDict();
Eric Snow86b7afd2017-09-04 17:54:09 -0600815 if (PyMapping_DelItem(modules, name) < 0) {
816 if (!PyMapping_HasKey(modules, name)) {
817 return;
818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_FatalError("import: deleting existing key in"
820 "sys.modules failed");
Eric Snow86b7afd2017-09-04 17:54:09 -0600821 }
Tim Peters1cd70172004-08-02 03:52:12 +0000822}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000823
Christian Heimes3b06e532008-01-07 20:12:44 +0000824
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000825/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000826 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
827 * removed from sys.modules, to avoid leaving damaged module objects
828 * in sys.modules. The caller may wish to restore the original
829 * module object (if any) in this case; PyImport_ReloadModule is an
830 * example.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000831 *
832 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
833 * interface. The other two exist primarily for backward compatibility.
Tim Peters1cd70172004-08-02 03:52:12 +0000834 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000835PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300836PyImport_ExecCodeModule(const char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return PyImport_ExecCodeModuleWithPathnames(
839 name, co, (char *)NULL, (char *)NULL);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000840}
841
842PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300843PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return PyImport_ExecCodeModuleWithPathnames(
846 name, co, pathname, (char *)NULL);
Barry Warsaw28a691b2010-04-17 00:19:56 +0000847}
848
849PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +0300850PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
851 const char *pathname,
852 const char *cpathname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000853{
Victor Stinner27ee0892011-03-04 12:57:09 +0000854 PyObject *m = NULL;
Eric Snow32439d62015-05-02 19:15:18 -0600855 PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
Victor Stinner27ee0892011-03-04 12:57:09 +0000856
857 nameobj = PyUnicode_FromString(name);
858 if (nameobj == NULL)
859 return NULL;
860
Victor Stinner27ee0892011-03-04 12:57:09 +0000861 if (cpathname != NULL) {
862 cpathobj = PyUnicode_DecodeFSDefault(cpathname);
863 if (cpathobj == NULL)
864 goto error;
Brett Cannona6473f92012-07-13 13:57:03 -0400865 }
866 else
Victor Stinner27ee0892011-03-04 12:57:09 +0000867 cpathobj = NULL;
Brett Cannona6473f92012-07-13 13:57:03 -0400868
869 if (pathname != NULL) {
870 pathobj = PyUnicode_DecodeFSDefault(pathname);
871 if (pathobj == NULL)
872 goto error;
873 }
874 else if (cpathobj != NULL) {
875 PyInterpreterState *interp = PyThreadState_GET()->interp;
876 _Py_IDENTIFIER(_get_sourcefile);
877
878 if (interp == NULL) {
879 Py_FatalError("PyImport_ExecCodeModuleWithPathnames: "
880 "no interpreter!");
881 }
882
Eric Snow32439d62015-05-02 19:15:18 -0600883 external= PyObject_GetAttrString(interp->importlib,
884 "_bootstrap_external");
885 if (external != NULL) {
886 pathobj = _PyObject_CallMethodIdObjArgs(external,
887 &PyId__get_sourcefile, cpathobj,
888 NULL);
889 Py_DECREF(external);
890 }
Brett Cannona6473f92012-07-13 13:57:03 -0400891 if (pathobj == NULL)
892 PyErr_Clear();
893 }
894 else
895 pathobj = NULL;
896
Victor Stinner27ee0892011-03-04 12:57:09 +0000897 m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
898error:
899 Py_DECREF(nameobj);
900 Py_XDECREF(pathobj);
901 Py_XDECREF(cpathobj);
902 return m;
903}
904
Brett Cannon18fc4e72014-04-04 10:01:46 -0400905static PyObject *
906module_dict_for_exec(PyObject *name)
Victor Stinner27ee0892011-03-04 12:57:09 +0000907{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400908 PyObject *m, *d = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000909
Victor Stinner27ee0892011-03-04 12:57:09 +0000910 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (m == NULL)
912 return NULL;
913 /* If the module is being reloaded, we get the old module back
914 and re-use its dict to exec the new code. */
915 d = PyModule_GetDict(m);
916 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
917 if (PyDict_SetItemString(d, "__builtins__",
Brett Cannon18fc4e72014-04-04 10:01:46 -0400918 PyEval_GetBuiltins()) != 0) {
919 remove_module(name);
920 return NULL;
921 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 }
Brett Cannon18fc4e72014-04-04 10:01:46 -0400923
Eric Snow08197a42014-05-12 17:54:55 -0600924 return d; /* Return a borrowed reference. */
Brett Cannon18fc4e72014-04-04 10:01:46 -0400925}
926
927static PyObject *
928exec_code_in_module(PyObject *name, PyObject *module_dict, PyObject *code_object)
929{
Brett Cannon18fc4e72014-04-04 10:01:46 -0400930 PyObject *v, *m;
931
932 v = PyEval_EvalCode(code_object, module_dict, module_dict);
933 if (v == NULL) {
934 remove_module(name);
935 return NULL;
936 }
937 Py_DECREF(v);
938
Eric Snow86b7afd2017-09-04 17:54:09 -0600939 m = _PyImport_GetModule(name);
940 if (m == NULL) {
Brett Cannon18fc4e72014-04-04 10:01:46 -0400941 PyErr_Format(PyExc_ImportError,
942 "Loaded module %R not found in sys.modules",
943 name);
944 return NULL;
945 }
946
947 Py_INCREF(m);
948
949 return m;
950}
951
952PyObject*
953PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
954 PyObject *cpathname)
955{
Eric Snow32439d62015-05-02 19:15:18 -0600956 PyObject *d, *external, *res;
Eric Snow08197a42014-05-12 17:54:55 -0600957 PyInterpreterState *interp = PyThreadState_GET()->interp;
958 _Py_IDENTIFIER(_fix_up_module);
Brett Cannon18fc4e72014-04-04 10:01:46 -0400959
960 d = module_dict_for_exec(name);
961 if (d == NULL) {
962 return NULL;
963 }
964
Eric Snow08197a42014-05-12 17:54:55 -0600965 if (pathname == NULL) {
966 pathname = ((PyCodeObject *)co)->co_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 }
Eric Snow32439d62015-05-02 19:15:18 -0600968 external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
969 if (external == NULL)
970 return NULL;
971 res = _PyObject_CallMethodIdObjArgs(external,
Eric Snow08197a42014-05-12 17:54:55 -0600972 &PyId__fix_up_module,
973 d, name, pathname, cpathname, NULL);
Eric Snow32439d62015-05-02 19:15:18 -0600974 Py_DECREF(external);
Eric Snow08197a42014-05-12 17:54:55 -0600975 if (res != NULL) {
Eric Snow58cfdd82014-05-29 12:31:39 -0600976 Py_DECREF(res);
Eric Snow08197a42014-05-12 17:54:55 -0600977 res = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 }
Eric Snow08197a42014-05-12 17:54:55 -0600979 return res;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000980}
981
982
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000983static void
984update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *constants, *tmp;
987 Py_ssize_t i, n;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (PyUnicode_Compare(co->co_filename, oldname))
990 return;
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000991
Serhiy Storchaka576f1322016-01-05 21:27:54 +0200992 Py_INCREF(newname);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300993 Py_XSETREF(co->co_filename, newname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 constants = co->co_consts;
996 n = PyTuple_GET_SIZE(constants);
997 for (i = 0; i < n; i++) {
998 tmp = PyTuple_GET_ITEM(constants, i);
999 if (PyCode_Check(tmp))
1000 update_code_filenames((PyCodeObject *)tmp,
1001 oldname, newname);
1002 }
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001003}
1004
Victor Stinner2f42ae52011-03-20 00:41:24 +01001005static void
1006update_compiled_module(PyCodeObject *co, PyObject *newname)
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001007{
Victor Stinner2f42ae52011-03-20 00:41:24 +01001008 PyObject *oldname;
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001009
Victor Stinner2f42ae52011-03-20 00:41:24 +01001010 if (PyUnicode_Compare(co->co_filename, newname) == 0)
1011 return;
Hirokazu Yamamoto4f447fb2009-03-04 01:52:10 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 oldname = co->co_filename;
1014 Py_INCREF(oldname);
1015 update_code_filenames(co, oldname, newname);
1016 Py_DECREF(oldname);
Antoine Pitroud35cbf62009-01-06 19:02:24 +00001017}
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001018
Brett Cannon4caa61d2014-01-09 19:03:32 -05001019/*[clinic input]
1020_imp._fix_co_filename
1021
1022 code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
1023 Code object to change.
1024
1025 path: unicode
1026 File path to use.
1027 /
1028
1029Changes code.co_filename to specify the passed-in file path.
1030[clinic start generated code]*/
1031
Brett Cannon4caa61d2014-01-09 19:03:32 -05001032static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001033_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
Larry Hastings89964c42015-04-14 18:07:59 -04001034 PyObject *path)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001035/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
Brett Cannon442c9b92011-03-23 16:14:42 -07001036
Brett Cannon4caa61d2014-01-09 19:03:32 -05001037{
Brett Cannona6dec2e2014-01-10 07:43:55 -05001038 update_compiled_module(code, path);
Brett Cannon442c9b92011-03-23 16:14:42 -07001039
1040 Py_RETURN_NONE;
1041}
1042
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001043
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001044/* Forward */
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001045static const struct _frozen * find_frozen(PyObject *);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001046
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001047
1048/* Helper to test for built-in module */
1049
1050static int
Victor Stinner95872862011-03-07 18:20:56 +01001051is_builtin(PyObject *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001052{
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001053 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001055 if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (PyImport_Inittab[i].initfunc == NULL)
1057 return -1;
1058 else
1059 return 1;
1060 }
1061 }
1062 return 0;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001063}
1064
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001065
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001066/* Return a finder object for a sys.path/pkg.__path__ item 'p',
Just van Rossum52e14d62002-12-30 22:08:05 +00001067 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001068 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001069 that can handle the path item. Return None if no hook could;
Brett Cannonfdcdd9e2016-07-08 11:00:00 -07001070 this tells our caller that the path based finder could not find
1071 a finder for this path item. Cache the result in
1072 path_importer_cache.
Just van Rossum52e14d62002-12-30 22:08:05 +00001073 Returns a borrowed reference. */
1074
1075static PyObject *
1076get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyObject *p)
Just van Rossum52e14d62002-12-30 22:08:05 +00001078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyObject *importer;
1080 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 /* These conditions are the caller's responsibility: */
1083 assert(PyList_Check(path_hooks));
1084 assert(PyDict_Check(path_importer_cache));
Just van Rossum52e14d62002-12-30 22:08:05 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 nhooks = PyList_Size(path_hooks);
1087 if (nhooks < 0)
1088 return NULL; /* Shouldn't happen */
Just van Rossum52e14d62002-12-30 22:08:05 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 importer = PyDict_GetItem(path_importer_cache, p);
1091 if (importer != NULL)
1092 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 /* set path_importer_cache[p] to None to avoid recursion */
1095 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1096 return NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 for (j = 0; j < nhooks; j++) {
1099 PyObject *hook = PyList_GetItem(path_hooks, j);
1100 if (hook == NULL)
1101 return NULL;
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01001102 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (importer != NULL)
1104 break;
Just van Rossum52e14d62002-12-30 22:08:05 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1107 return NULL;
1108 }
1109 PyErr_Clear();
1110 }
1111 if (importer == NULL) {
Brett Cannonaa936422012-04-27 15:30:58 -04001112 return Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 }
1114 if (importer != NULL) {
1115 int err = PyDict_SetItem(path_importer_cache, p, importer);
1116 Py_DECREF(importer);
1117 if (err != 0)
1118 return NULL;
1119 }
1120 return importer;
Just van Rossum52e14d62002-12-30 22:08:05 +00001121}
1122
Christian Heimes9cd17752007-11-18 19:35:23 +00001123PyAPI_FUNC(PyObject *)
1124PyImport_GetImporter(PyObject *path) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
Christian Heimes9cd17752007-11-18 19:35:23 +00001126
Victor Stinner1e53bba2013-07-16 22:26:05 +02001127 path_importer_cache = PySys_GetObject("path_importer_cache");
1128 path_hooks = PySys_GetObject("path_hooks");
1129 if (path_importer_cache != NULL && path_hooks != NULL) {
1130 importer = get_path_importer(path_importer_cache,
1131 path_hooks, path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
1133 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1134 return importer;
Christian Heimes9cd17752007-11-18 19:35:23 +00001135}
1136
Nick Coghland5cacbb2015-05-23 22:24:10 +10001137/*[clinic input]
1138_imp.create_builtin
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001139
Nick Coghland5cacbb2015-05-23 22:24:10 +10001140 spec: object
1141 /
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001142
Nick Coghland5cacbb2015-05-23 22:24:10 +10001143Create an extension module.
1144[clinic start generated code]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001145
Nick Coghland5cacbb2015-05-23 22:24:10 +10001146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001147_imp_create_builtin(PyObject *module, PyObject *spec)
1148/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 struct _inittab *p;
Nick Coghland5cacbb2015-05-23 22:24:10 +10001151 PyObject *name;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001152 const char *namestr;
Victor Stinner5eb4f592013-11-14 22:38:52 +01001153 PyObject *mod;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001154
Nick Coghland5cacbb2015-05-23 22:24:10 +10001155 name = PyObject_GetAttrString(spec, "name");
1156 if (name == NULL) {
1157 return NULL;
1158 }
1159
Victor Stinner5eb4f592013-11-14 22:38:52 +01001160 mod = _PyImport_FindExtensionObject(name, name);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001161 if (mod || PyErr_Occurred()) {
1162 Py_DECREF(name);
Raymond Hettingerf0afe772016-08-31 08:44:11 -07001163 Py_XINCREF(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10001164 return mod;
1165 }
1166
1167 namestr = PyUnicode_AsUTF8(name);
1168 if (namestr == NULL) {
1169 Py_DECREF(name);
1170 return NULL;
1171 }
Guido van Rossum25ce5661997-08-02 03:10:38 +00001172
Eric Snow86b7afd2017-09-04 17:54:09 -06001173 PyObject *modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 for (p = PyImport_Inittab; p->name != NULL; p++) {
Antoine Pitrou6c40eb72012-01-18 20:16:09 +01001175 PyModuleDef *def;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001176 if (_PyUnicode_EqualToASCIIString(name, p->name)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 if (p->initfunc == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001178 /* Cannot re-init internal module ("sys" or "builtins") */
1179 mod = PyImport_AddModule(namestr);
1180 Py_DECREF(name);
1181 return mod;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 mod = (*p->initfunc)();
Nick Coghland5cacbb2015-05-23 22:24:10 +10001184 if (mod == NULL) {
1185 Py_DECREF(name);
1186 return NULL;
1187 }
1188 if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1189 Py_DECREF(name);
1190 return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1191 } else {
1192 /* Remember pointer to module init function. */
1193 def = PyModule_GetDef(mod);
Christian Heimesa78b6272016-09-09 00:25:03 +02001194 if (def == NULL) {
1195 Py_DECREF(name);
1196 return NULL;
1197 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001198 def->m_base.m_init = p->initfunc;
Eric Snow86b7afd2017-09-04 17:54:09 -06001199 if (modules == NULL) {
1200 modules = PyImport_GetModuleDict();
1201 }
1202 if (_PyImport_FixupExtensionObject(mod, name, name,
1203 modules) < 0) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10001204 Py_DECREF(name);
1205 return NULL;
1206 }
1207 Py_DECREF(name);
1208 return mod;
1209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 }
1211 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10001212 Py_DECREF(name);
1213 Py_RETURN_NONE;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001214}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001215
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001216
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001217/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001218
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001219static const struct _frozen *
Victor Stinner53dc7352011-03-20 01:50:21 +01001220find_frozen(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001221{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001222 const struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001223
Victor Stinner53dc7352011-03-20 01:50:21 +01001224 if (name == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return NULL;
Benjamin Petersond968e272008-11-05 22:48:33 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 for (p = PyImport_FrozenModules; ; p++) {
1228 if (p->name == NULL)
1229 return NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001230 if (_PyUnicode_EqualToASCIIString(name, p->name))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 break;
1232 }
1233 return p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001234}
1235
Guido van Rossum79f25d91997-04-29 20:08:16 +00001236static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001237get_frozen_object(PyObject *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001238{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001239 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (p == NULL) {
1243 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001244 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 name);
1246 return NULL;
1247 }
1248 if (p->code == NULL) {
1249 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001250 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 name);
1252 return NULL;
1253 }
1254 size = p->size;
1255 if (size < 0)
1256 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001257 return PyMarshal_ReadObjectFromString((const char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001258}
1259
Brett Cannon8d110132009-03-15 02:20:16 +00001260static PyObject *
Victor Stinner53dc7352011-03-20 01:50:21 +01001261is_frozen_package(PyObject *name)
Brett Cannon8d110132009-03-15 02:20:16 +00001262{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001263 const struct _frozen *p = find_frozen(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 int size;
Brett Cannon8d110132009-03-15 02:20:16 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (p == NULL) {
1267 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001268 "No such frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 name);
1270 return NULL;
1271 }
Brett Cannon8d110132009-03-15 02:20:16 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 size = p->size;
Brett Cannon8d110132009-03-15 02:20:16 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (size < 0)
1276 Py_RETURN_TRUE;
1277 else
1278 Py_RETURN_FALSE;
Brett Cannon8d110132009-03-15 02:20:16 +00001279}
1280
1281
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001282/* Initialize a frozen module.
Brett Cannon3c2ac442009-03-08 20:49:47 +00001283 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001284 an exception set if the initialization failed.
1285 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001286
1287int
Victor Stinner53dc7352011-03-20 01:50:21 +01001288PyImport_ImportFrozenModuleObject(PyObject *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001289{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07001290 const struct _frozen *p;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001291 PyObject *co, *m, *d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 int ispackage;
1293 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001294
Victor Stinner53dc7352011-03-20 01:50:21 +01001295 p = find_frozen(name);
1296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (p == NULL)
1298 return 0;
1299 if (p->code == NULL) {
1300 PyErr_Format(PyExc_ImportError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001301 "Excluded frozen object named %R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 name);
1303 return -1;
1304 }
1305 size = p->size;
1306 ispackage = (size < 0);
1307 if (ispackage)
1308 size = -size;
Serhiy Storchakac6792272013-10-19 21:03:34 +03001309 co = PyMarshal_ReadObjectFromString((const char *)p->code, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (co == NULL)
1311 return -1;
1312 if (!PyCode_Check(co)) {
1313 PyErr_Format(PyExc_TypeError,
Victor Stinner53dc7352011-03-20 01:50:21 +01001314 "frozen object %R is not a code object",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 name);
1316 goto err_return;
1317 }
1318 if (ispackage) {
Brett Cannon3e0651b2013-05-31 23:18:39 -04001319 /* Set __path__ to the empty list */
Brett Cannon18fc4e72014-04-04 10:01:46 -04001320 PyObject *l;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 int err;
Victor Stinner53dc7352011-03-20 01:50:21 +01001322 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (m == NULL)
1324 goto err_return;
1325 d = PyModule_GetDict(m);
Brett Cannon3e0651b2013-05-31 23:18:39 -04001326 l = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (l == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 goto err_return;
1329 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 err = PyDict_SetItemString(d, "__path__", l);
1331 Py_DECREF(l);
1332 if (err != 0)
1333 goto err_return;
1334 }
Brett Cannon18fc4e72014-04-04 10:01:46 -04001335 d = module_dict_for_exec(name);
1336 if (d == NULL) {
Victor Stinner53dc7352011-03-20 01:50:21 +01001337 goto err_return;
Brett Cannon18fc4e72014-04-04 10:01:46 -04001338 }
1339 m = exec_code_in_module(name, d, co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (m == NULL)
1341 goto err_return;
1342 Py_DECREF(co);
1343 Py_DECREF(m);
1344 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001345err_return:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_DECREF(co);
1347 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001348}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001349
Victor Stinner53dc7352011-03-20 01:50:21 +01001350int
Serhiy Storchakac6792272013-10-19 21:03:34 +03001351PyImport_ImportFrozenModule(const char *name)
Victor Stinner53dc7352011-03-20 01:50:21 +01001352{
1353 PyObject *nameobj;
1354 int ret;
1355 nameobj = PyUnicode_InternFromString(name);
1356 if (nameobj == NULL)
1357 return -1;
1358 ret = PyImport_ImportFrozenModuleObject(nameobj);
1359 Py_DECREF(nameobj);
1360 return ret;
1361}
1362
Guido van Rossum74e6a111994-08-29 12:54:38 +00001363
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001364/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001365 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001366
Guido van Rossum79f25d91997-04-29 20:08:16 +00001367PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001368PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 PyObject *pname;
1371 PyObject *result;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 pname = PyUnicode_FromString(name);
1374 if (pname == NULL)
1375 return NULL;
1376 result = PyImport_Import(pname);
1377 Py_DECREF(pname);
1378 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001379}
1380
Christian Heimes072c0f12008-01-03 23:01:04 +00001381/* Import a module without blocking
1382 *
1383 * At first it tries to fetch the module from sys.modules. If the module was
1384 * never loaded before it loads it with PyImport_ImportModule() unless another
1385 * thread holds the import lock. In the latter case the function raises an
1386 * ImportError instead of blocking.
1387 *
1388 * Returns the module object with incremented ref count.
1389 */
1390PyObject *
1391PyImport_ImportModuleNoBlock(const char *name)
1392{
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001393 return PyImport_ImportModule(name);
Christian Heimes072c0f12008-01-03 23:01:04 +00001394}
1395
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001396
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001397/* Remove importlib frames from the traceback,
1398 * except in Verbose mode. */
1399static void
1400remove_importlib_frames(void)
1401{
1402 const char *importlib_filename = "<frozen importlib._bootstrap>";
Eric Snow32439d62015-05-02 19:15:18 -06001403 const char *external_filename = "<frozen importlib._bootstrap_external>";
Nick Coghlan42c07662012-07-31 21:14:18 +10001404 const char *remove_frames = "_call_with_frames_removed";
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001405 int always_trim = 0;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001406 int in_importlib = 0;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001407 PyObject *exception, *value, *base_tb, *tb;
Benjamin Petersonfa873702012-07-09 13:43:53 -07001408 PyObject **prev_link, **outer_link = NULL;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001409
1410 /* Synopsis: if it's an ImportError, we trim all importlib chunks
Nick Coghlan42c07662012-07-31 21:14:18 +10001411 from the traceback. We always trim chunks
1412 which end with a call to "_call_with_frames_removed". */
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001413
1414 PyErr_Fetch(&exception, &value, &base_tb);
1415 if (!exception || Py_VerboseFlag)
1416 goto done;
1417 if (PyType_IsSubtype((PyTypeObject *) exception,
1418 (PyTypeObject *) PyExc_ImportError))
1419 always_trim = 1;
1420
1421 prev_link = &base_tb;
1422 tb = base_tb;
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001423 while (tb != NULL) {
1424 PyTracebackObject *traceback = (PyTracebackObject *)tb;
1425 PyObject *next = (PyObject *) traceback->tb_next;
1426 PyFrameObject *frame = traceback->tb_frame;
1427 PyCodeObject *code = frame->f_code;
1428 int now_in_importlib;
1429
1430 assert(PyTraceBack_Check(tb));
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001431 now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1432 _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001433 if (now_in_importlib && !in_importlib) {
1434 /* This is the link to this chunk of importlib tracebacks */
1435 outer_link = prev_link;
1436 }
1437 in_importlib = now_in_importlib;
1438
1439 if (in_importlib &&
1440 (always_trim ||
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001441 _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001442 Py_XINCREF(next);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001443 Py_XSETREF(*outer_link, next);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001444 prev_link = outer_link;
1445 }
1446 else {
1447 prev_link = (PyObject **) &traceback->tb_next;
1448 }
1449 tb = next;
1450 }
1451done:
1452 PyErr_Restore(exception, value, base_tb);
1453}
1454
1455
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001456static PyObject *
1457resolve_name(PyObject *name, PyObject *globals, int level)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001458{
Eric Snowb523f842013-11-22 09:05:39 -07001459 _Py_IDENTIFIER(__spec__);
Brett Cannonfd074152012-04-14 14:10:13 -04001460 _Py_IDENTIFIER(__package__);
1461 _Py_IDENTIFIER(__path__);
1462 _Py_IDENTIFIER(__name__);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001463 _Py_IDENTIFIER(parent);
1464 PyObject *abs_name;
1465 PyObject *package = NULL;
1466 PyObject *spec;
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001467 Py_ssize_t last_dot;
1468 PyObject *base;
1469 int level_up;
1470
1471 if (globals == NULL) {
1472 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1473 goto error;
1474 }
1475 if (!PyDict_Check(globals)) {
1476 PyErr_SetString(PyExc_TypeError, "globals must be a dict");
1477 goto error;
1478 }
1479 package = _PyDict_GetItemId(globals, &PyId___package__);
1480 if (package == Py_None) {
1481 package = NULL;
1482 }
1483 spec = _PyDict_GetItemId(globals, &PyId___spec__);
1484
1485 if (package != NULL) {
1486 Py_INCREF(package);
1487 if (!PyUnicode_Check(package)) {
1488 PyErr_SetString(PyExc_TypeError, "package must be a string");
1489 goto error;
1490 }
1491 else if (spec != NULL && spec != Py_None) {
1492 int equal;
1493 PyObject *parent = _PyObject_GetAttrId(spec, &PyId_parent);
1494 if (parent == NULL) {
1495 goto error;
1496 }
1497
1498 equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1499 Py_DECREF(parent);
1500 if (equal < 0) {
1501 goto error;
1502 }
1503 else if (equal == 0) {
1504 if (PyErr_WarnEx(PyExc_ImportWarning,
1505 "__package__ != __spec__.parent", 1) < 0) {
1506 goto error;
1507 }
1508 }
1509 }
1510 }
1511 else if (spec != NULL && spec != Py_None) {
1512 package = _PyObject_GetAttrId(spec, &PyId_parent);
1513 if (package == NULL) {
1514 goto error;
1515 }
1516 else if (!PyUnicode_Check(package)) {
1517 PyErr_SetString(PyExc_TypeError,
1518 "__spec__.parent must be a string");
1519 goto error;
1520 }
1521 }
1522 else {
1523 if (PyErr_WarnEx(PyExc_ImportWarning,
1524 "can't resolve package from __spec__ or __package__, "
1525 "falling back on __name__ and __path__", 1) < 0) {
1526 goto error;
1527 }
1528
1529 package = _PyDict_GetItemId(globals, &PyId___name__);
1530 if (package == NULL) {
1531 PyErr_SetString(PyExc_KeyError, "'__name__' not in globals");
1532 goto error;
1533 }
1534
1535 Py_INCREF(package);
1536 if (!PyUnicode_Check(package)) {
1537 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
1538 goto error;
1539 }
1540
1541 if (_PyDict_GetItemId(globals, &PyId___path__) == NULL) {
1542 Py_ssize_t dot;
1543
1544 if (PyUnicode_READY(package) < 0) {
1545 goto error;
1546 }
1547
1548 dot = PyUnicode_FindChar(package, '.',
1549 0, PyUnicode_GET_LENGTH(package), -1);
1550 if (dot == -2) {
1551 goto error;
1552 }
1553
1554 if (dot >= 0) {
1555 PyObject *substr = PyUnicode_Substring(package, 0, dot);
1556 if (substr == NULL) {
1557 goto error;
1558 }
1559 Py_SETREF(package, substr);
1560 }
1561 }
1562 }
1563
1564 last_dot = PyUnicode_GET_LENGTH(package);
1565 if (last_dot == 0) {
1566 PyErr_SetString(PyExc_ImportError,
1567 "attempted relative import with no known parent package");
1568 goto error;
1569 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001570
1571 for (level_up = 1; level_up < level; level_up += 1) {
1572 last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1573 if (last_dot == -2) {
1574 goto error;
1575 }
1576 else if (last_dot == -1) {
1577 PyErr_SetString(PyExc_ValueError,
1578 "attempted relative import beyond top-level "
1579 "package");
1580 goto error;
1581 }
1582 }
1583
1584 base = PyUnicode_Substring(package, 0, last_dot);
1585 Py_DECREF(package);
1586 if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1587 return base;
1588 }
1589
1590 abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1591 Py_DECREF(base);
1592 return abs_name;
1593
1594 error:
1595 Py_XDECREF(package);
1596 return NULL;
1597}
1598
1599PyObject *
1600PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1601 PyObject *locals, PyObject *fromlist,
1602 int level)
1603{
Brett Cannonfd074152012-04-14 14:10:13 -04001604 _Py_IDENTIFIER(_find_and_load);
1605 _Py_IDENTIFIER(_handle_fromlist);
Brett Cannonfd074152012-04-14 14:10:13 -04001606 PyObject *abs_name = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001607 PyObject *final_mod = NULL;
1608 PyObject *mod = NULL;
1609 PyObject *package = NULL;
Brett Cannonfd074152012-04-14 14:10:13 -04001610 PyInterpreterState *interp = PyThreadState_GET()->interp;
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001611 int has_from;
Brett Cannonfd074152012-04-14 14:10:13 -04001612
Brett Cannonfd074152012-04-14 14:10:13 -04001613 if (name == NULL) {
1614 PyErr_SetString(PyExc_ValueError, "Empty module name");
1615 goto error;
1616 }
1617
1618 /* The below code is importlib.__import__() & _gcd_import(), ported to C
1619 for added performance. */
1620
1621 if (!PyUnicode_Check(name)) {
1622 PyErr_SetString(PyExc_TypeError, "module name must be a string");
1623 goto error;
1624 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001625 if (PyUnicode_READY(name) < 0) {
Brett Cannonfd074152012-04-14 14:10:13 -04001626 goto error;
1627 }
1628 if (level < 0) {
1629 PyErr_SetString(PyExc_ValueError, "level must be >= 0");
1630 goto error;
1631 }
Brett Cannon849113a2016-01-22 15:25:50 -08001632
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001633 if (level > 0) {
1634 abs_name = resolve_name(name, globals, level);
1635 if (abs_name == NULL)
Brett Cannon9fa81262016-01-22 16:39:02 -08001636 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001637 }
1638 else { /* level == 0 */
1639 if (PyUnicode_GET_LENGTH(name) == 0) {
1640 PyErr_SetString(PyExc_ValueError, "Empty module name");
1641 goto error;
1642 }
Brett Cannonfd074152012-04-14 14:10:13 -04001643 abs_name = name;
1644 Py_INCREF(abs_name);
1645 }
1646
Eric Snow86b7afd2017-09-04 17:54:09 -06001647 mod = _PyImport_GetModule(abs_name);
Serhiy Storchakab4baace2017-07-06 08:09:03 +03001648 if (mod != NULL && mod != Py_None) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001649 _Py_IDENTIFIER(__spec__);
1650 _Py_IDENTIFIER(_initializing);
1651 _Py_IDENTIFIER(_lock_unlock_module);
Eric Snowb523f842013-11-22 09:05:39 -07001652 PyObject *value = NULL;
1653 PyObject *spec;
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001654 int initializing = 0;
1655
Brett Cannonfd074152012-04-14 14:10:13 -04001656 Py_INCREF(mod);
Antoine Pitrou03989852012-08-28 00:24:52 +02001657 /* Optimization: only call _bootstrap._lock_unlock_module() if
Eric Snowb523f842013-11-22 09:05:39 -07001658 __spec__._initializing is true.
1659 NOTE: because of this, initializing must be set *before*
Antoine Pitrou03989852012-08-28 00:24:52 +02001660 stuffing the new module in sys.modules.
1661 */
Eric Snowb523f842013-11-22 09:05:39 -07001662 spec = _PyObject_GetAttrId(mod, &PyId___spec__);
1663 if (spec != NULL) {
1664 value = _PyObject_GetAttrId(spec, &PyId__initializing);
1665 Py_DECREF(spec);
1666 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001667 if (value == NULL)
1668 PyErr_Clear();
1669 else {
1670 initializing = PyObject_IsTrue(value);
1671 Py_DECREF(value);
1672 if (initializing == -1)
1673 PyErr_Clear();
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001674 if (initializing > 0) {
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001675 value = _PyObject_CallMethodIdObjArgs(interp->importlib,
1676 &PyId__lock_unlock_module, abs_name,
1677 NULL);
1678 if (value == NULL)
1679 goto error;
1680 Py_DECREF(value);
1681 }
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001682 }
Brett Cannonfd074152012-04-14 14:10:13 -04001683 }
1684 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001685 mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001686 &PyId__find_and_load, abs_name,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001687 interp->import_func, NULL);
Brett Cannonfd074152012-04-14 14:10:13 -04001688 if (mod == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001689 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001690 }
1691 }
1692
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001693 has_from = 0;
1694 if (fromlist != NULL && fromlist != Py_None) {
1695 has_from = PyObject_IsTrue(fromlist);
1696 if (has_from < 0)
1697 goto error;
1698 }
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001699 if (!has_from) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001700 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1701 if (level == 0 || len > 0) {
1702 Py_ssize_t dot;
Brett Cannonfd074152012-04-14 14:10:13 -04001703
Victor Stinner744c34e2016-05-20 11:36:13 +02001704 dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1705 if (dot == -2) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001706 goto error;
Brett Cannonfd074152012-04-14 14:10:13 -04001707 }
1708
Victor Stinner744c34e2016-05-20 11:36:13 +02001709 if (dot == -1) {
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001710 /* No dot in module name, simple exit */
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001711 final_mod = mod;
1712 Py_INCREF(mod);
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001713 goto error;
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001714 }
1715
Brett Cannonfd074152012-04-14 14:10:13 -04001716 if (level == 0) {
Victor Stinner744c34e2016-05-20 11:36:13 +02001717 PyObject *front = PyUnicode_Substring(name, 0, dot);
1718 if (front == NULL) {
1719 goto error;
1720 }
1721
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001722 final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
Antoine Pitroub78174c2012-05-06 17:15:23 +02001723 Py_DECREF(front);
Brett Cannonfd074152012-04-14 14:10:13 -04001724 }
1725 else {
Victor Stinner744c34e2016-05-20 11:36:13 +02001726 Py_ssize_t cut_off = len - dot;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001727 Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001728 PyObject *to_return = PyUnicode_Substring(abs_name, 0,
Brett Cannonfd074152012-04-14 14:10:13 -04001729 abs_name_len - cut_off);
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001730 if (to_return == NULL) {
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001731 goto error;
Antoine Pitrou22a1d172012-04-16 22:06:21 +02001732 }
Brett Cannonfd074152012-04-14 14:10:13 -04001733
Eric Snow86b7afd2017-09-04 17:54:09 -06001734 final_mod = _PyImport_GetModule(to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001735 Py_DECREF(to_return);
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001736 if (final_mod == NULL) {
1737 PyErr_Format(PyExc_KeyError,
1738 "%R not in sys.modules as expected",
1739 to_return);
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001740 goto error;
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001741 }
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001742 Py_INCREF(final_mod);
Brett Cannonfd074152012-04-14 14:10:13 -04001743 }
1744 }
1745 else {
1746 final_mod = mod;
1747 Py_INCREF(mod);
1748 }
1749 }
1750 else {
Alexandre Vassalotti865eaa12013-05-02 10:44:04 -07001751 final_mod = _PyObject_CallMethodIdObjArgs(interp->importlib,
Brett Cannonfd074152012-04-14 14:10:13 -04001752 &PyId__handle_fromlist, mod,
Serhiy Storchaka133138a2016-08-02 22:51:21 +03001753 fromlist, interp->import_func,
Brett Cannonfd074152012-04-14 14:10:13 -04001754 NULL);
1755 }
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001756
Brett Cannonfd074152012-04-14 14:10:13 -04001757 error:
1758 Py_XDECREF(abs_name);
Brett Cannonfd074152012-04-14 14:10:13 -04001759 Py_XDECREF(mod);
1760 Py_XDECREF(package);
Antoine Pitroubc07a5c2012-07-08 12:01:27 +02001761 if (final_mod == NULL)
1762 remove_importlib_frames();
Brett Cannonfd074152012-04-14 14:10:13 -04001763 return final_mod;
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001764}
1765
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001766PyObject *
Benjamin Peterson04778a82011-05-25 09:29:00 -05001767PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
Victor Stinnerfe93faf2011-03-14 15:54:52 -04001768 PyObject *fromlist, int level)
1769{
1770 PyObject *nameobj, *mod;
1771 nameobj = PyUnicode_FromString(name);
1772 if (nameobj == NULL)
1773 return NULL;
1774 mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1775 fromlist, level);
1776 Py_DECREF(nameobj);
1777 return mod;
1778}
1779
1780
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001781/* Re-import a module of any kind and return its module object, WITH
1782 INCREMENTED REFERENCE COUNT */
1783
Guido van Rossum79f25d91997-04-29 20:08:16 +00001784PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001785PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001786{
Eric Snow86b7afd2017-09-04 17:54:09 -06001787 _Py_IDENTIFIER(imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001788 _Py_IDENTIFIER(reload);
1789 PyObject *reloaded_module = NULL;
Eric Snow86b7afd2017-09-04 17:54:09 -06001790 PyObject *imp = _PyImport_GetModuleId(&PyId_imp);
Brett Cannon62228db2012-04-29 14:38:11 -04001791 if (imp == NULL) {
1792 imp = PyImport_ImportModule("imp");
1793 if (imp == NULL) {
1794 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
Brett Cannon62228db2012-04-29 14:38:11 -04001797 else {
1798 Py_INCREF(imp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 }
Victor Stinnerad3c03b2011-03-14 09:21:33 -04001800
Victor Stinner55ba38a2016-12-09 16:09:30 +01001801 reloaded_module = _PyObject_CallMethodIdObjArgs(imp, &PyId_reload, m, NULL);
Brett Cannon62228db2012-04-29 14:38:11 -04001802 Py_DECREF(imp);
1803 return reloaded_module;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001804}
1805
1806
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001807/* Higher-level import emulator which emulates the "import" statement
1808 more accurately -- it invokes the __import__() function from the
1809 builtins of the current globals. This means that the import is
1810 done using whatever import hooks are installed in the current
Brett Cannonbc2eff32010-09-19 21:39:02 +00001811 environment.
Guido van Rossum6058eb41998-12-21 19:51:00 +00001812 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00001813 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00001814 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001815
1816PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001817PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 static PyObject *silly_list = NULL;
1820 static PyObject *builtins_str = NULL;
1821 static PyObject *import_str = NULL;
1822 PyObject *globals = NULL;
1823 PyObject *import = NULL;
1824 PyObject *builtins = NULL;
1825 PyObject *r = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 /* Initialize constant string objects */
1828 if (silly_list == NULL) {
1829 import_str = PyUnicode_InternFromString("__import__");
1830 if (import_str == NULL)
1831 return NULL;
1832 builtins_str = PyUnicode_InternFromString("__builtins__");
1833 if (builtins_str == NULL)
1834 return NULL;
Brett Cannonbc2eff32010-09-19 21:39:02 +00001835 silly_list = PyList_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (silly_list == NULL)
1837 return NULL;
1838 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 /* Get the builtins from current globals */
1841 globals = PyEval_GetGlobals();
1842 if (globals != NULL) {
1843 Py_INCREF(globals);
1844 builtins = PyObject_GetItem(globals, builtins_str);
1845 if (builtins == NULL)
1846 goto err;
1847 }
1848 else {
1849 /* No globals -- use standard builtins, and fake globals */
1850 builtins = PyImport_ImportModuleLevel("builtins",
1851 NULL, NULL, NULL, 0);
1852 if (builtins == NULL)
1853 return NULL;
1854 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1855 if (globals == NULL)
1856 goto err;
1857 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 /* Get the __import__ function from the builtins */
1860 if (PyDict_Check(builtins)) {
1861 import = PyObject_GetItem(builtins, import_str);
1862 if (import == NULL)
1863 PyErr_SetObject(PyExc_KeyError, import_str);
1864 }
1865 else
1866 import = PyObject_GetAttr(builtins, import_str);
1867 if (import == NULL)
1868 goto err;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 /* Call the __import__ function with the proper argument list
Brett Cannonbc2eff32010-09-19 21:39:02 +00001871 Always use absolute import here.
1872 Calling for side-effect of import. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
1874 globals, silly_list, 0, NULL);
Brett Cannonbc2eff32010-09-19 21:39:02 +00001875 if (r == NULL)
1876 goto err;
1877 Py_DECREF(r);
1878
Eric Snow86b7afd2017-09-04 17:54:09 -06001879 r = _PyImport_GetModule(module_name);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001880 if (r != NULL) {
Brett Cannonbc2eff32010-09-19 21:39:02 +00001881 Py_INCREF(r);
Serhiy Storchaka145541c2017-06-15 20:54:38 +03001882 }
1883 else if (!PyErr_Occurred()) {
1884 PyErr_SetObject(PyExc_KeyError, module_name);
1885 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001886
1887 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 Py_XDECREF(globals);
1889 Py_XDECREF(builtins);
1890 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 return r;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001893}
1894
Brett Cannon4caa61d2014-01-09 19:03:32 -05001895/*[clinic input]
1896_imp.extension_suffixes
1897
1898Returns the list of file suffixes used to identify extension modules.
1899[clinic start generated code]*/
1900
Brett Cannon4caa61d2014-01-09 19:03:32 -05001901static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001902_imp_extension_suffixes_impl(PyObject *module)
1903/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 PyObject *list;
Brett Cannon2657df42012-05-04 15:20:40 -04001906 const char *suffix;
1907 unsigned int index = 0;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 list = PyList_New(0);
1910 if (list == NULL)
1911 return NULL;
Brett Cannon2657df42012-05-04 15:20:40 -04001912#ifdef HAVE_DYNAMIC_LOADING
1913 while ((suffix = _PyImport_DynLoadFiletab[index])) {
1914 PyObject *item = PyUnicode_FromString(suffix);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 if (item == NULL) {
1916 Py_DECREF(list);
1917 return NULL;
1918 }
1919 if (PyList_Append(list, item) < 0) {
1920 Py_DECREF(list);
1921 Py_DECREF(item);
1922 return NULL;
1923 }
1924 Py_DECREF(item);
Brett Cannon2657df42012-05-04 15:20:40 -04001925 index += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
Brett Cannon2657df42012-05-04 15:20:40 -04001927#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 return list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001929}
1930
Brett Cannon4caa61d2014-01-09 19:03:32 -05001931/*[clinic input]
Brett Cannon4caa61d2014-01-09 19:03:32 -05001932_imp.init_frozen
1933
1934 name: unicode
1935 /
1936
1937Initializes a frozen module.
1938[clinic start generated code]*/
1939
Brett Cannon4caa61d2014-01-09 19:03:32 -05001940static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001941_imp_init_frozen_impl(PyObject *module, PyObject *name)
1942/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 int ret;
1945 PyObject *m;
Brett Cannon4caa61d2014-01-09 19:03:32 -05001946
Victor Stinner53dc7352011-03-20 01:50:21 +01001947 ret = PyImport_ImportFrozenModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 if (ret < 0)
1949 return NULL;
1950 if (ret == 0) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001951 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 }
Victor Stinner53dc7352011-03-20 01:50:21 +01001953 m = PyImport_AddModuleObject(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 Py_XINCREF(m);
1955 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001956}
1957
Brett Cannon4caa61d2014-01-09 19:03:32 -05001958/*[clinic input]
1959_imp.get_frozen_object
1960
1961 name: unicode
1962 /
1963
1964Create a code object for a frozen module.
1965[clinic start generated code]*/
1966
Brett Cannon4caa61d2014-01-09 19:03:32 -05001967static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001968_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
1969/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 return get_frozen_object(name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001972}
1973
Brett Cannon4caa61d2014-01-09 19:03:32 -05001974/*[clinic input]
1975_imp.is_frozen_package
1976
1977 name: unicode
1978 /
1979
1980Returns True if the module name is of a frozen package.
1981[clinic start generated code]*/
1982
Brett Cannon4caa61d2014-01-09 19:03:32 -05001983static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001984_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
1985/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05001986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 return is_frozen_package(name);
Brett Cannon8d110132009-03-15 02:20:16 +00001988}
1989
Brett Cannon4caa61d2014-01-09 19:03:32 -05001990/*[clinic input]
1991_imp.is_builtin
1992
1993 name: unicode
1994 /
1995
1996Returns True if the module name corresponds to a built-in module.
1997[clinic start generated code]*/
1998
Guido van Rossum79f25d91997-04-29 20:08:16 +00001999static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002000_imp_is_builtin_impl(PyObject *module, PyObject *name)
2001/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002002{
Brett Cannon4caa61d2014-01-09 19:03:32 -05002003 return PyLong_FromLong(is_builtin(name));
2004}
2005
2006/*[clinic input]
2007_imp.is_frozen
2008
2009 name: unicode
2010 /
2011
2012Returns True if the module name corresponds to a frozen module.
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_impl(PyObject *module, PyObject *name)
2017/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002018{
Benjamin Peterson6fba3db2013-03-18 23:13:31 -07002019 const struct _frozen *p;
Brett Cannon4caa61d2014-01-09 19:03:32 -05002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 p = find_frozen(name);
2022 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002023}
2024
Larry Hastings1df0b352015-08-24 19:53:56 -07002025/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2026static int
2027exec_builtin_or_dynamic(PyObject *mod) {
2028 PyModuleDef *def;
2029 void *state;
2030
2031 if (!PyModule_Check(mod)) {
2032 return 0;
2033 }
2034
2035 def = PyModule_GetDef(mod);
2036 if (def == NULL) {
Larry Hastings1df0b352015-08-24 19:53:56 -07002037 return 0;
2038 }
Brett Cannon52794db2016-09-07 17:00:43 -07002039
Larry Hastings1df0b352015-08-24 19:53:56 -07002040 state = PyModule_GetState(mod);
Larry Hastings1df0b352015-08-24 19:53:56 -07002041 if (state) {
2042 /* Already initialized; skip reload */
2043 return 0;
2044 }
Brett Cannon52794db2016-09-07 17:00:43 -07002045
Larry Hastings1df0b352015-08-24 19:53:56 -07002046 return PyModule_ExecDef(mod, def);
2047}
2048
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002049#ifdef HAVE_DYNAMIC_LOADING
2050
Brett Cannon4caa61d2014-01-09 19:03:32 -05002051/*[clinic input]
Nick Coghland5cacbb2015-05-23 22:24:10 +10002052_imp.create_dynamic
Brett Cannon4caa61d2014-01-09 19:03:32 -05002053
Nick Coghland5cacbb2015-05-23 22:24:10 +10002054 spec: object
Brett Cannon4caa61d2014-01-09 19:03:32 -05002055 file: object = NULL
2056 /
2057
Nick Coghland5cacbb2015-05-23 22:24:10 +10002058Create an extension module.
Brett Cannon4caa61d2014-01-09 19:03:32 -05002059[clinic start generated code]*/
2060
Brett Cannon4caa61d2014-01-09 19:03:32 -05002061static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002062_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2063/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
Brett Cannon4caa61d2014-01-09 19:03:32 -05002064{
Nick Coghland5cacbb2015-05-23 22:24:10 +10002065 PyObject *mod, *name, *path;
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002066 FILE *fp;
2067
Nick Coghland5cacbb2015-05-23 22:24:10 +10002068 name = PyObject_GetAttrString(spec, "name");
2069 if (name == NULL) {
2070 return NULL;
2071 }
2072
2073 path = PyObject_GetAttrString(spec, "origin");
2074 if (path == NULL) {
2075 Py_DECREF(name);
2076 return NULL;
2077 }
2078
2079 mod = _PyImport_FindExtensionObject(name, path);
2080 if (mod != NULL) {
2081 Py_DECREF(name);
2082 Py_DECREF(path);
2083 Py_INCREF(mod);
2084 return mod;
2085 }
2086
Brett Cannon4caa61d2014-01-09 19:03:32 -05002087 if (file != NULL) {
2088 fp = _Py_fopen_obj(path, "r");
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002089 if (fp == NULL) {
Nick Coghland5cacbb2015-05-23 22:24:10 +10002090 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002091 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 return NULL;
Victor Stinnere9ddbf62011-03-22 10:46:35 +01002093 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 }
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002095 else
2096 fp = NULL;
Nick Coghland5cacbb2015-05-23 22:24:10 +10002097
2098 mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2099
2100 Py_DECREF(name);
Brett Cannon4caa61d2014-01-09 19:03:32 -05002101 Py_DECREF(path);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (fp)
2103 fclose(fp);
Victor Stinnerfefd70c2011-03-14 15:54:07 -04002104 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002105}
2106
Nick Coghland5cacbb2015-05-23 22:24:10 +10002107/*[clinic input]
2108_imp.exec_dynamic -> int
2109
2110 mod: object
2111 /
2112
2113Initialize an extension module.
2114[clinic start generated code]*/
2115
2116static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002117_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2118/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
Nick Coghland5cacbb2015-05-23 22:24:10 +10002119{
Larry Hastings1df0b352015-08-24 19:53:56 -07002120 return exec_builtin_or_dynamic(mod);
Nick Coghland5cacbb2015-05-23 22:24:10 +10002121}
2122
2123
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002124#endif /* HAVE_DYNAMIC_LOADING */
2125
Larry Hastings7726ac92014-01-31 22:03:12 -08002126/*[clinic input]
Larry Hastings1df0b352015-08-24 19:53:56 -07002127_imp.exec_builtin -> int
2128
2129 mod: object
2130 /
2131
2132Initialize a built-in module.
2133[clinic start generated code]*/
2134
2135static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002136_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2137/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
Larry Hastings1df0b352015-08-24 19:53:56 -07002138{
2139 return exec_builtin_or_dynamic(mod);
2140}
2141
Barry Warsaw28a691b2010-04-17 00:19:56 +00002142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002143PyDoc_STRVAR(doc_imp,
Brett Cannon6f44d662012-04-15 16:08:47 -04002144"(Extremely) low-level import machinery bits as used by importlib and imp.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002145
Guido van Rossum79f25d91997-04-29 20:08:16 +00002146static PyMethodDef imp_methods[] = {
Brett Cannon4caa61d2014-01-09 19:03:32 -05002147 _IMP_EXTENSION_SUFFIXES_METHODDEF
2148 _IMP_LOCK_HELD_METHODDEF
2149 _IMP_ACQUIRE_LOCK_METHODDEF
2150 _IMP_RELEASE_LOCK_METHODDEF
2151 _IMP_GET_FROZEN_OBJECT_METHODDEF
2152 _IMP_IS_FROZEN_PACKAGE_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002153 _IMP_CREATE_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002154 _IMP_INIT_FROZEN_METHODDEF
2155 _IMP_IS_BUILTIN_METHODDEF
2156 _IMP_IS_FROZEN_METHODDEF
Nick Coghland5cacbb2015-05-23 22:24:10 +10002157 _IMP_CREATE_DYNAMIC_METHODDEF
2158 _IMP_EXEC_DYNAMIC_METHODDEF
Larry Hastings1df0b352015-08-24 19:53:56 -07002159 _IMP_EXEC_BUILTIN_METHODDEF
Brett Cannon4caa61d2014-01-09 19:03:32 -05002160 _IMP__FIX_CO_FILENAME_METHODDEF
2161 {NULL, NULL} /* sentinel */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002162};
2163
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002164
Martin v. Löwis1a214512008-06-11 05:26:20 +00002165static struct PyModuleDef impmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyModuleDef_HEAD_INIT,
Brett Cannon6f44d662012-04-15 16:08:47 -04002167 "_imp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 doc_imp,
2169 0,
2170 imp_methods,
2171 NULL,
2172 NULL,
2173 NULL,
2174 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002175};
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002176
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002177PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002178PyInit_imp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 m = PyModule_Create(&impmodule);
2183 if (m == NULL)
2184 goto failure;
2185 d = PyModule_GetDict(m);
2186 if (d == NULL)
2187 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 return m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002190 failure:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Py_XDECREF(m);
2192 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002193}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002194
2195
Guido van Rossumb18618d2000-05-03 23:44:39 +00002196/* API for embedding applications that want to add their own entries
2197 to the table of built-in modules. This should normally be called
2198 *before* Py_Initialize(). When the table resize fails, -1 is
2199 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002200
2201 After a similar function by Just van Rossum. */
2202
2203int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002204PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 static struct _inittab *our_copy = NULL;
2207 struct _inittab *p;
2208 int i, n;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* Count the number of entries in both tables */
2211 for (n = 0; newtab[n].name != NULL; n++)
2212 ;
2213 if (n == 0)
2214 return 0; /* Nothing to do */
2215 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2216 ;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* Allocate new memory for the combined table */
2219 p = our_copy;
2220 PyMem_RESIZE(p, struct _inittab, i+n+1);
2221 if (p == NULL)
2222 return -1;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Copy the tables into the new memory */
2225 if (our_copy != PyImport_Inittab)
2226 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2227 PyImport_Inittab = our_copy = p;
2228 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 return 0;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002231}
2232
2233/* Shorthand to add a single entry given a name and a function */
2234
2235int
Brett Cannona826f322009-04-02 03:41:46 +00002236PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 struct _inittab newtab[2];
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 memset(newtab, '\0', sizeof newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002241
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002242 newtab[0].name = name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 newtab[0].initfunc = initfunc;
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 return PyImport_ExtendInittab(newtab);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002246}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002247
2248#ifdef __cplusplus
2249}
2250#endif