Branch data Line data Source code
1 : : /* Module definition and import implementation */
2 : :
3 : : #include "Python.h"
4 : :
5 : : #include "pycore_import.h" // _PyImport_BootstrapImp()
6 : : #include "pycore_initconfig.h" // _PyStatus_OK()
7 : : #include "pycore_interp.h" // struct _import_runtime_state
8 : : #include "pycore_namespace.h" // _PyNamespace_Type
9 : : #include "pycore_pyerrors.h" // _PyErr_SetString()
10 : : #include "pycore_pyhash.h" // _Py_KeyedHash()
11 : : #include "pycore_pylifecycle.h"
12 : : #include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
13 : : #include "pycore_pystate.h" // _PyInterpreterState_GET()
14 : : #include "pycore_sysmodule.h" // _PySys_Audit()
15 : : #include "marshal.h" // PyMarshal_ReadObjectFromString()
16 : : #include "importdl.h" // _PyImport_DynLoadFiletab
17 : : #include "pydtrace.h" // PyDTrace_IMPORT_FIND_LOAD_START_ENABLED()
18 : : #include <stdbool.h> // bool
19 : :
20 : : #ifdef HAVE_FCNTL_H
21 : : #include <fcntl.h>
22 : : #endif
23 : : #ifdef __cplusplus
24 : : extern "C" {
25 : : #endif
26 : :
27 : :
28 : : /*[clinic input]
29 : : module _imp
30 : : [clinic start generated code]*/
31 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
32 : :
33 : : #include "clinic/import.c.h"
34 : :
35 : :
36 : : /*******************************/
37 : : /* process-global import state */
38 : : /*******************************/
39 : :
40 : : /* This table is defined in config.c: */
41 : : extern struct _inittab _PyImport_Inittab[];
42 : :
43 : : // This is not used after Py_Initialize() is called.
44 : : // (See _PyRuntimeState.imports.inittab.)
45 : : struct _inittab *PyImport_Inittab = _PyImport_Inittab;
46 : : // When we dynamically allocate a larger table for PyImport_ExtendInittab(),
47 : : // we track the pointer here so we can deallocate it during finalization.
48 : : static struct _inittab *inittab_copy = NULL;
49 : :
50 : :
51 : : /*******************************/
52 : : /* runtime-global import state */
53 : : /*******************************/
54 : :
55 : : #define INITTAB _PyRuntime.imports.inittab
56 : : #define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
57 : : #define EXTENSIONS _PyRuntime.imports.extensions
58 : :
59 : : #define PKGCONTEXT (_PyRuntime.imports.pkgcontext)
60 : :
61 : :
62 : : /*******************************/
63 : : /* interpreter import state */
64 : : /*******************************/
65 : :
66 : : #define MODULES(interp) \
67 : : (interp)->imports.modules
68 : : #define MODULES_BY_INDEX(interp) \
69 : : (interp)->imports.modules_by_index
70 : : #define IMPORTLIB(interp) \
71 : : (interp)->imports.importlib
72 : : #define OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) \
73 : : (interp)->imports.override_multi_interp_extensions_check
74 : : #define OVERRIDE_FROZEN_MODULES(interp) \
75 : : (interp)->imports.override_frozen_modules
76 : : #ifdef HAVE_DLOPEN
77 : : # define DLOPENFLAGS(interp) \
78 : : (interp)->imports.dlopenflags
79 : : #endif
80 : : #define IMPORT_FUNC(interp) \
81 : : (interp)->imports.import_func
82 : :
83 : : #define IMPORT_LOCK(interp) \
84 : : (interp)->imports.lock.mutex
85 : : #define IMPORT_LOCK_THREAD(interp) \
86 : : (interp)->imports.lock.thread
87 : : #define IMPORT_LOCK_LEVEL(interp) \
88 : : (interp)->imports.lock.level
89 : :
90 : : #define FIND_AND_LOAD(interp) \
91 : : (interp)->imports.find_and_load
92 : :
93 : :
94 : : /*******************/
95 : : /* the import lock */
96 : : /*******************/
97 : :
98 : : /* Locking primitives to prevent parallel imports of the same module
99 : : in different threads to return with a partially loaded module.
100 : : These calls are serialized by the global interpreter lock. */
101 : :
102 : : void
103 : 4609 : _PyImport_AcquireLock(PyInterpreterState *interp)
104 : : {
105 : 4609 : unsigned long me = PyThread_get_thread_ident();
106 [ - + ]: 4609 : if (me == PYTHREAD_INVALID_THREAD_ID)
107 : 0 : return; /* Too bad */
108 [ + + ]: 4609 : if (IMPORT_LOCK(interp) == NULL) {
109 : 25 : IMPORT_LOCK(interp) = PyThread_allocate_lock();
110 [ - + ]: 25 : if (IMPORT_LOCK(interp) == NULL)
111 : 0 : return; /* Nothing much we can do. */
112 : : }
113 [ - + ]: 4609 : if (IMPORT_LOCK_THREAD(interp) == me) {
114 : 0 : IMPORT_LOCK_LEVEL(interp)++;
115 : 0 : return;
116 : : }
117 [ + - - + ]: 9218 : if (IMPORT_LOCK_THREAD(interp) != PYTHREAD_INVALID_THREAD_ID ||
118 : 4609 : !PyThread_acquire_lock(IMPORT_LOCK(interp), 0))
119 : : {
120 : 0 : PyThreadState *tstate = PyEval_SaveThread();
121 : 0 : PyThread_acquire_lock(IMPORT_LOCK(interp), WAIT_LOCK);
122 : 0 : PyEval_RestoreThread(tstate);
123 : : }
124 : : assert(IMPORT_LOCK_LEVEL(interp) == 0);
125 : 4609 : IMPORT_LOCK_THREAD(interp) = me;
126 : 4609 : IMPORT_LOCK_LEVEL(interp) = 1;
127 : : }
128 : :
129 : : int
130 : 4609 : _PyImport_ReleaseLock(PyInterpreterState *interp)
131 : : {
132 : 4609 : unsigned long me = PyThread_get_thread_ident();
133 [ + - - + ]: 4609 : if (me == PYTHREAD_INVALID_THREAD_ID || IMPORT_LOCK(interp) == NULL)
134 : 0 : return 0; /* Too bad */
135 [ - + ]: 4609 : if (IMPORT_LOCK_THREAD(interp) != me)
136 : 0 : return -1;
137 : 4609 : IMPORT_LOCK_LEVEL(interp)--;
138 : : assert(IMPORT_LOCK_LEVEL(interp) >= 0);
139 [ + - ]: 4609 : if (IMPORT_LOCK_LEVEL(interp) == 0) {
140 : 4609 : IMPORT_LOCK_THREAD(interp) = PYTHREAD_INVALID_THREAD_ID;
141 : 4609 : PyThread_release_lock(IMPORT_LOCK(interp));
142 : : }
143 : 4609 : return 1;
144 : : }
145 : :
146 : : #ifdef HAVE_FORK
147 : : /* This function is called from PyOS_AfterFork_Child() to ensure that newly
148 : : created child processes do not share locks with the parent.
149 : : We now acquire the import lock around fork() calls but on some platforms
150 : : (Solaris 9 and earlier? see isue7242) that still left us with problems. */
151 : : PyStatus
152 : 0 : _PyImport_ReInitLock(PyInterpreterState *interp)
153 : : {
154 [ # # ]: 0 : if (IMPORT_LOCK(interp) != NULL) {
155 [ # # ]: 0 : if (_PyThread_at_fork_reinit(&IMPORT_LOCK(interp)) < 0) {
156 : 0 : return _PyStatus_ERR("failed to create a new lock");
157 : : }
158 : : }
159 : :
160 [ # # ]: 0 : if (IMPORT_LOCK_LEVEL(interp) > 1) {
161 : : /* Forked as a side effect of import */
162 : 0 : unsigned long me = PyThread_get_thread_ident();
163 : 0 : PyThread_acquire_lock(IMPORT_LOCK(interp), WAIT_LOCK);
164 : 0 : IMPORT_LOCK_THREAD(interp) = me;
165 : 0 : IMPORT_LOCK_LEVEL(interp)--;
166 : : } else {
167 : 0 : IMPORT_LOCK_THREAD(interp) = PYTHREAD_INVALID_THREAD_ID;
168 : 0 : IMPORT_LOCK_LEVEL(interp) = 0;
169 : : }
170 : 0 : return _PyStatus_OK();
171 : : }
172 : : #endif
173 : :
174 : :
175 : : /***************/
176 : : /* sys.modules */
177 : : /***************/
178 : :
179 : : PyObject *
180 : 29 : _PyImport_InitModules(PyInterpreterState *interp)
181 : : {
182 : : assert(MODULES(interp) == NULL);
183 : 29 : MODULES(interp) = PyDict_New();
184 [ - + ]: 29 : if (MODULES(interp) == NULL) {
185 : 0 : return NULL;
186 : : }
187 : 29 : return MODULES(interp);
188 : : }
189 : :
190 : : PyObject *
191 : 58 : _PyImport_GetModules(PyInterpreterState *interp)
192 : : {
193 : 58 : return MODULES(interp);
194 : : }
195 : :
196 : : void
197 : 25 : _PyImport_ClearModules(PyInterpreterState *interp)
198 : : {
199 : 25 : Py_SETREF(MODULES(interp), NULL);
200 : 25 : }
201 : :
202 : : PyObject *
203 : 19 : PyImport_GetModuleDict(void)
204 : : {
205 : 19 : PyInterpreterState *interp = _PyInterpreterState_GET();
206 [ - + ]: 19 : if (MODULES(interp) == NULL) {
207 : 0 : Py_FatalError("interpreter has no modules dictionary");
208 : : }
209 : 19 : return MODULES(interp);
210 : : }
211 : :
212 : : // This is only kept around for extensions that use _Py_IDENTIFIER.
213 : : PyObject *
214 : 0 : _PyImport_GetModuleId(_Py_Identifier *nameid)
215 : : {
216 : 0 : PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
217 [ # # ]: 0 : if (name == NULL) {
218 : 0 : return NULL;
219 : : }
220 : 0 : return PyImport_GetModule(name);
221 : : }
222 : :
223 : : int
224 : 4 : _PyImport_SetModule(PyObject *name, PyObject *m)
225 : : {
226 : 4 : PyInterpreterState *interp = _PyInterpreterState_GET();
227 : 4 : PyObject *modules = MODULES(interp);
228 : 4 : return PyObject_SetItem(modules, name, m);
229 : : }
230 : :
231 : : int
232 : 25 : _PyImport_SetModuleString(const char *name, PyObject *m)
233 : : {
234 : 25 : PyInterpreterState *interp = _PyInterpreterState_GET();
235 : 25 : PyObject *modules = MODULES(interp);
236 : 25 : return PyMapping_SetItemString(modules, name, m);
237 : : }
238 : :
239 : : static PyObject *
240 : 5555 : import_get_module(PyThreadState *tstate, PyObject *name)
241 : : {
242 : 5555 : PyObject *modules = MODULES(tstate->interp);
243 [ - + ]: 5555 : if (modules == NULL) {
244 : 0 : _PyErr_SetString(tstate, PyExc_RuntimeError,
245 : : "unable to get sys.modules");
246 : 0 : return NULL;
247 : : }
248 : :
249 : : PyObject *m;
250 : 5555 : Py_INCREF(modules);
251 [ + - ]: 5555 : if (PyDict_CheckExact(modules)) {
252 : 5555 : m = PyDict_GetItemWithError(modules, name); /* borrowed */
253 : 5555 : Py_XINCREF(m);
254 : : }
255 : : else {
256 : 0 : m = PyObject_GetItem(modules, name);
257 [ # # # # ]: 0 : if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
258 : 0 : _PyErr_Clear(tstate);
259 : : }
260 : : }
261 : 5555 : Py_DECREF(modules);
262 : 5555 : return m;
263 : : }
264 : :
265 : : static int
266 : 3605 : import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
267 : : {
268 : : PyObject *spec;
269 : :
270 : : /* Optimization: only call _bootstrap._lock_unlock_module() if
271 : : __spec__._initializing is true.
272 : : NOTE: because of this, initializing must be set *before*
273 : : stuffing the new module in sys.modules.
274 : : */
275 : 3605 : spec = PyObject_GetAttr(mod, &_Py_ID(__spec__));
276 : 3605 : int busy = _PyModuleSpec_IsInitializing(spec);
277 : 3605 : Py_XDECREF(spec);
278 [ + + ]: 3605 : if (busy) {
279 : : /* Wait until module is done importing. */
280 : 235 : PyObject *value = _PyObject_CallMethodOneArg(
281 : : IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
282 [ - + ]: 235 : if (value == NULL) {
283 : 0 : return -1;
284 : : }
285 : 235 : Py_DECREF(value);
286 : : }
287 : 3605 : return 0;
288 : : }
289 : :
290 : : static void remove_importlib_frames(PyThreadState *tstate);
291 : :
292 : : PyObject *
293 : 96 : PyImport_GetModule(PyObject *name)
294 : : {
295 : 96 : PyThreadState *tstate = _PyThreadState_GET();
296 : : PyObject *mod;
297 : :
298 : 96 : mod = import_get_module(tstate, name);
299 [ + + + - ]: 96 : if (mod != NULL && mod != Py_None) {
300 [ - + ]: 47 : if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
301 : 0 : Py_DECREF(mod);
302 : 0 : remove_importlib_frames(tstate);
303 : 0 : return NULL;
304 : : }
305 : : }
306 : 96 : return mod;
307 : : }
308 : :
309 : : /* Get the module object corresponding to a module name.
310 : : First check the modules dictionary if there's one there,
311 : : if not, create a new one and insert it in the modules dictionary. */
312 : :
313 : : static PyObject *
314 : 101 : import_add_module(PyThreadState *tstate, PyObject *name)
315 : : {
316 : 101 : PyObject *modules = MODULES(tstate->interp);
317 [ - + ]: 101 : if (modules == NULL) {
318 : 0 : _PyErr_SetString(tstate, PyExc_RuntimeError,
319 : : "no import module dictionary");
320 : 0 : return NULL;
321 : : }
322 : :
323 : : PyObject *m;
324 [ + - ]: 101 : if (PyDict_CheckExact(modules)) {
325 : 101 : m = Py_XNewRef(PyDict_GetItemWithError(modules, name));
326 : : }
327 : : else {
328 : 0 : m = PyObject_GetItem(modules, name);
329 : : // For backward-compatibility we copy the behavior
330 : : // of PyDict_GetItemWithError().
331 [ # # ]: 0 : if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
332 : 0 : _PyErr_Clear(tstate);
333 : : }
334 : : }
335 [ - + ]: 101 : if (_PyErr_Occurred(tstate)) {
336 : 0 : return NULL;
337 : : }
338 [ + + + - ]: 101 : if (m != NULL && PyModule_Check(m)) {
339 : 51 : return m;
340 : : }
341 : 50 : Py_XDECREF(m);
342 : 50 : m = PyModule_NewObject(name);
343 [ - + ]: 50 : if (m == NULL)
344 : 0 : return NULL;
345 [ - + ]: 50 : if (PyObject_SetItem(modules, name, m) != 0) {
346 : 0 : Py_DECREF(m);
347 : 0 : return NULL;
348 : : }
349 : :
350 : 50 : return m;
351 : : }
352 : :
353 : : PyObject *
354 : 73 : PyImport_AddModuleObject(PyObject *name)
355 : : {
356 : 73 : PyThreadState *tstate = _PyThreadState_GET();
357 : 73 : PyObject *mod = import_add_module(tstate, name);
358 [ + - ]: 73 : if (mod) {
359 : 73 : PyObject *ref = PyWeakref_NewRef(mod, NULL);
360 : 73 : Py_DECREF(mod);
361 [ - + ]: 73 : if (ref == NULL) {
362 : 0 : return NULL;
363 : : }
364 : 73 : mod = PyWeakref_GetObject(ref);
365 : 73 : Py_DECREF(ref);
366 : : }
367 : 73 : return mod; /* borrowed reference */
368 : : }
369 : :
370 : :
371 : : PyObject *
372 : 73 : PyImport_AddModule(const char *name)
373 : : {
374 : 73 : PyObject *nameobj = PyUnicode_FromString(name);
375 [ - + ]: 73 : if (nameobj == NULL) {
376 : 0 : return NULL;
377 : : }
378 : 73 : PyObject *module = PyImport_AddModuleObject(nameobj);
379 : 73 : Py_DECREF(nameobj);
380 : 73 : return module;
381 : : }
382 : :
383 : :
384 : : /* Remove name from sys.modules, if it's there.
385 : : * Can be called with an exception raised.
386 : : * If fail to remove name a new exception will be chained with the old
387 : : * exception, otherwise the old exception is preserved.
388 : : */
389 : : static void
390 : 0 : remove_module(PyThreadState *tstate, PyObject *name)
391 : : {
392 : 0 : PyObject *exc = _PyErr_GetRaisedException(tstate);
393 : :
394 : 0 : PyObject *modules = MODULES(tstate->interp);
395 [ # # ]: 0 : if (PyDict_CheckExact(modules)) {
396 : 0 : PyObject *mod = _PyDict_Pop(modules, name, Py_None);
397 : 0 : Py_XDECREF(mod);
398 : : }
399 [ # # ]: 0 : else if (PyMapping_DelItem(modules, name) < 0) {
400 [ # # ]: 0 : if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
401 : 0 : _PyErr_Clear(tstate);
402 : : }
403 : : }
404 : :
405 : 0 : _PyErr_ChainExceptions1(exc);
406 : 0 : }
407 : :
408 : :
409 : : /************************************/
410 : : /* per-interpreter modules-by-index */
411 : : /************************************/
412 : :
413 : : Py_ssize_t
414 : 481 : _PyImport_GetNextModuleIndex(void)
415 : : {
416 : 481 : LAST_MODULE_INDEX++;
417 : 481 : return LAST_MODULE_INDEX;
418 : : }
419 : :
420 : : static const char *
421 : 1 : _modules_by_index_check(PyInterpreterState *interp, Py_ssize_t index)
422 : : {
423 [ + - ]: 1 : if (index == 0) {
424 : 1 : return "invalid module index";
425 : : }
426 [ # # ]: 0 : if (MODULES_BY_INDEX(interp) == NULL) {
427 : 0 : return "Interpreters module-list not accessible.";
428 : : }
429 [ # # ]: 0 : if (index > PyList_GET_SIZE(MODULES_BY_INDEX(interp))) {
430 : 0 : return "Module index out of bounds.";
431 : : }
432 : 0 : return NULL;
433 : : }
434 : :
435 : : static PyObject *
436 : 1 : _modules_by_index_get(PyInterpreterState *interp, PyModuleDef *def)
437 : : {
438 : 1 : Py_ssize_t index = def->m_base.m_index;
439 [ + - ]: 1 : if (_modules_by_index_check(interp, index) != NULL) {
440 : 1 : return NULL;
441 : : }
442 : 0 : PyObject *res = PyList_GET_ITEM(MODULES_BY_INDEX(interp), index);
443 [ # # ]: 0 : return res==Py_None ? NULL : res;
444 : : }
445 : :
446 : : static int
447 : 109 : _modules_by_index_set(PyInterpreterState *interp,
448 : : PyModuleDef *def, PyObject *module)
449 : : {
450 : : assert(def != NULL);
451 : : assert(def->m_slots == NULL);
452 : : assert(def->m_base.m_index > 0);
453 : :
454 [ + + ]: 109 : if (MODULES_BY_INDEX(interp) == NULL) {
455 : 29 : MODULES_BY_INDEX(interp) = PyList_New(0);
456 [ - + ]: 29 : if (MODULES_BY_INDEX(interp) == NULL) {
457 : 0 : return -1;
458 : : }
459 : : }
460 : :
461 : 109 : Py_ssize_t index = def->m_base.m_index;
462 [ + + ]: 453 : while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
463 [ - + ]: 344 : if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
464 : 0 : return -1;
465 : : }
466 : : }
467 : :
468 : 109 : return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
469 : : }
470 : :
471 : : static int
472 : 0 : _modules_by_index_clear_one(PyInterpreterState *interp, PyModuleDef *def)
473 : : {
474 : 0 : Py_ssize_t index = def->m_base.m_index;
475 : 0 : const char *err = _modules_by_index_check(interp, index);
476 [ # # ]: 0 : if (err != NULL) {
477 : 0 : Py_FatalError(err);
478 : : return -1;
479 : : }
480 : 0 : return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(Py_None));
481 : : }
482 : :
483 : :
484 : : PyObject*
485 : 1 : PyState_FindModule(PyModuleDef* module)
486 : : {
487 : 1 : PyInterpreterState *interp = _PyInterpreterState_GET();
488 [ - + ]: 1 : if (module->m_slots) {
489 : 0 : return NULL;
490 : : }
491 : 1 : return _modules_by_index_get(interp, module);
492 : : }
493 : :
494 : : /* _PyState_AddModule() has been completely removed from the C-API
495 : : (and was removed from the limited API in 3.6). However, we're
496 : : playing it safe and keeping it around for any stable ABI extensions
497 : : built against 3.2-3.5. */
498 : : int
499 : 0 : _PyState_AddModule(PyThreadState *tstate, PyObject* module, PyModuleDef* def)
500 : : {
501 [ # # ]: 0 : if (!def) {
502 : : assert(_PyErr_Occurred(tstate));
503 : 0 : return -1;
504 : : }
505 [ # # ]: 0 : if (def->m_slots) {
506 : 0 : _PyErr_SetString(tstate,
507 : : PyExc_SystemError,
508 : : "PyState_AddModule called on module with slots");
509 : 0 : return -1;
510 : : }
511 : 0 : return _modules_by_index_set(tstate->interp, def, module);
512 : : }
513 : :
514 : : int
515 : 2 : PyState_AddModule(PyObject* module, PyModuleDef* def)
516 : : {
517 [ - + ]: 2 : if (!def) {
518 : 0 : Py_FatalError("module definition is NULL");
519 : : return -1;
520 : : }
521 : :
522 : 2 : PyThreadState *tstate = _PyThreadState_GET();
523 [ - + ]: 2 : if (def->m_slots) {
524 : 0 : _PyErr_SetString(tstate,
525 : : PyExc_SystemError,
526 : : "PyState_AddModule called on module with slots");
527 : 0 : return -1;
528 : : }
529 : :
530 : 2 : PyInterpreterState *interp = tstate->interp;
531 : 2 : Py_ssize_t index = def->m_base.m_index;
532 [ + - - + ]: 4 : if (MODULES_BY_INDEX(interp) &&
533 : 2 : index < PyList_GET_SIZE(MODULES_BY_INDEX(interp)) &&
534 [ # # ]: 0 : module == PyList_GET_ITEM(MODULES_BY_INDEX(interp), index))
535 : : {
536 : 0 : _Py_FatalErrorFormat(__func__, "module %p already added", module);
537 : : return -1;
538 : : }
539 : :
540 : 2 : return _modules_by_index_set(interp, def, module);
541 : : }
542 : :
543 : : int
544 : 0 : PyState_RemoveModule(PyModuleDef* def)
545 : : {
546 : 0 : PyThreadState *tstate = _PyThreadState_GET();
547 [ # # ]: 0 : if (def->m_slots) {
548 : 0 : _PyErr_SetString(tstate,
549 : : PyExc_SystemError,
550 : : "PyState_RemoveModule called on module with slots");
551 : 0 : return -1;
552 : : }
553 : 0 : return _modules_by_index_clear_one(tstate->interp, def);
554 : : }
555 : :
556 : :
557 : : // Used by finalize_modules()
558 : : void
559 : 25 : _PyImport_ClearModulesByIndex(PyInterpreterState *interp)
560 : : {
561 [ - + ]: 25 : if (!MODULES_BY_INDEX(interp)) {
562 : 0 : return;
563 : : }
564 : :
565 : : Py_ssize_t i;
566 [ + + ]: 357 : for (i = 0; i < PyList_GET_SIZE(MODULES_BY_INDEX(interp)); i++) {
567 : 332 : PyObject *m = PyList_GET_ITEM(MODULES_BY_INDEX(interp), i);
568 [ + + ]: 332 : if (PyModule_Check(m)) {
569 : : /* cleanup the saved copy of module dicts */
570 : 95 : PyModuleDef *md = PyModule_GetDef(m);
571 [ + - ]: 95 : if (md) {
572 [ + + ]: 95 : Py_CLEAR(md->m_base.m_copy);
573 : : }
574 : : }
575 : : }
576 : :
577 : : /* Setting modules_by_index to NULL could be dangerous, so we
578 : : clear the list instead. */
579 [ - + ]: 25 : if (PyList_SetSlice(MODULES_BY_INDEX(interp),
580 : : 0, PyList_GET_SIZE(MODULES_BY_INDEX(interp)),
581 : : NULL)) {
582 : 0 : PyErr_WriteUnraisable(MODULES_BY_INDEX(interp));
583 : : }
584 : : }
585 : :
586 : :
587 : : /*********************/
588 : : /* extension modules */
589 : : /*********************/
590 : :
591 : : /*
592 : : It may help to have a big picture view of what happens
593 : : when an extension is loaded. This includes when it is imported
594 : : for the first time or via imp.load_dynamic().
595 : :
596 : : Here's a summary, using imp.load_dynamic() as the starting point:
597 : :
598 : : 1. imp.load_dynamic() -> importlib._bootstrap._load()
599 : : 2. _load(): acquire import lock
600 : : 3. _load() -> importlib._bootstrap._load_unlocked()
601 : : 4. _load_unlocked() -> importlib._bootstrap.module_from_spec()
602 : : 5. module_from_spec() -> ExtensionFileLoader.create_module()
603 : : 6. create_module() -> _imp.create_dynamic()
604 : : (see below)
605 : : 7. module_from_spec() -> importlib._bootstrap._init_module_attrs()
606 : : 8. _load_unlocked(): sys.modules[name] = module
607 : : 9. _load_unlocked() -> ExtensionFileLoader.exec_module()
608 : : 10. exec_module() -> _imp.exec_dynamic()
609 : : (see below)
610 : : 11. _load(): release import lock
611 : :
612 : :
613 : : ...for single-phase init modules, where m_size == -1:
614 : :
615 : : (6). first time (not found in _PyRuntime.imports.extensions):
616 : : 1. _imp_create_dynamic_impl() -> import_find_extension()
617 : : 2. _imp_create_dynamic_impl() -> _PyImport_LoadDynamicModuleWithSpec()
618 : : 3. _PyImport_LoadDynamicModuleWithSpec(): load <module init func>
619 : : 4. _PyImport_LoadDynamicModuleWithSpec(): call <module init func>
620 : : 5. <module init func> -> PyModule_Create() -> PyModule_Create2() -> PyModule_CreateInitialized()
621 : : 6. PyModule_CreateInitialized() -> PyModule_New()
622 : : 7. PyModule_CreateInitialized(): allocate mod->md_state
623 : : 8. PyModule_CreateInitialized() -> PyModule_AddFunctions()
624 : : 9. PyModule_CreateInitialized() -> PyModule_SetDocString()
625 : : 10. PyModule_CreateInitialized(): set mod->md_def
626 : : 11. <module init func>: initialize the module
627 : : 12. _PyImport_LoadDynamicModuleWithSpec() -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
628 : : 13. _PyImport_LoadDynamicModuleWithSpec(): set def->m_base.m_init
629 : : 14. _PyImport_LoadDynamicModuleWithSpec(): set __file__
630 : : 15. _PyImport_LoadDynamicModuleWithSpec() -> _PyImport_FixupExtensionObject()
631 : : 16. _PyImport_FixupExtensionObject(): add it to interp->imports.modules_by_index
632 : : 17. _PyImport_FixupExtensionObject(): copy __dict__ into def->m_base.m_copy
633 : : 18. _PyImport_FixupExtensionObject(): add it to _PyRuntime.imports.extensions
634 : :
635 : : (6). subsequent times (found in _PyRuntime.imports.extensions):
636 : : 1. _imp_create_dynamic_impl() -> import_find_extension()
637 : : 2. import_find_extension() -> import_add_module()
638 : : 3. if name in sys.modules: use that module
639 : : 4. else:
640 : : 1. import_add_module() -> PyModule_NewObject()
641 : : 2. import_add_module(): set it on sys.modules
642 : : 5. import_find_extension(): copy the "m_copy" dict into __dict__
643 : : 6. _imp_create_dynamic_impl() -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
644 : :
645 : : (10). (every time):
646 : : 1. noop
647 : :
648 : :
649 : : ...for single-phase init modules, where m_size >= 0:
650 : :
651 : : (6). not main interpreter and never loaded there - every time (not found in _PyRuntime.imports.extensions):
652 : : 1-16. (same as for m_size == -1)
653 : :
654 : : (6). main interpreter - first time (not found in _PyRuntime.imports.extensions):
655 : : 1-16. (same as for m_size == -1)
656 : : 17. _PyImport_FixupExtensionObject(): add it to _PyRuntime.imports.extensions
657 : :
658 : : (6). previously loaded in main interpreter (found in _PyRuntime.imports.extensions):
659 : : 1. _imp_create_dynamic_impl() -> import_find_extension()
660 : : 2. import_find_extension(): call def->m_base.m_init
661 : : 3. import_find_extension(): add the module to sys.modules
662 : :
663 : : (10). every time:
664 : : 1. noop
665 : :
666 : :
667 : : ...for multi-phase init modules:
668 : :
669 : : (6). every time:
670 : : 1. _imp_create_dynamic_impl() -> import_find_extension() (not found)
671 : : 2. _imp_create_dynamic_impl() -> _PyImport_LoadDynamicModuleWithSpec()
672 : : 3. _PyImport_LoadDynamicModuleWithSpec(): load module init func
673 : : 4. _PyImport_LoadDynamicModuleWithSpec(): call module init func
674 : : 5. _PyImport_LoadDynamicModuleWithSpec() -> PyModule_FromDefAndSpec()
675 : : 6. PyModule_FromDefAndSpec(): gather/check moduledef slots
676 : : 7. if there's a Py_mod_create slot:
677 : : 1. PyModule_FromDefAndSpec(): call its function
678 : : 8. else:
679 : : 1. PyModule_FromDefAndSpec() -> PyModule_NewObject()
680 : : 9: PyModule_FromDefAndSpec(): set mod->md_def
681 : : 10. PyModule_FromDefAndSpec() -> _add_methods_to_object()
682 : : 11. PyModule_FromDefAndSpec() -> PyModule_SetDocString()
683 : :
684 : : (10). every time:
685 : : 1. _imp_exec_dynamic_impl() -> exec_builtin_or_dynamic()
686 : : 2. if mod->md_state == NULL (including if m_size == 0):
687 : : 1. exec_builtin_or_dynamic() -> PyModule_ExecDef()
688 : : 2. PyModule_ExecDef(): allocate mod->md_state
689 : : 3. if there's a Py_mod_exec slot:
690 : : 1. PyModule_ExecDef(): call its function
691 : : */
692 : :
693 : :
694 : : /* Make sure name is fully qualified.
695 : :
696 : : This is a bit of a hack: when the shared library is loaded,
697 : : the module name is "package.module", but the module calls
698 : : PyModule_Create*() with just "module" for the name. The shared
699 : : library loader squirrels away the true name of the module in
700 : : _PyRuntime.imports.pkgcontext, and PyModule_Create*() will
701 : : substitute this (if the name actually matches).
702 : : */
703 : : const char *
704 : 104 : _PyImport_ResolveNameWithPackageContext(const char *name)
705 : : {
706 [ + + ]: 104 : if (PKGCONTEXT != NULL) {
707 : 19 : const char *p = strrchr(PKGCONTEXT, '.');
708 [ - + - - ]: 19 : if (p != NULL && strcmp(name, p+1) == 0) {
709 : 0 : name = PKGCONTEXT;
710 : 0 : PKGCONTEXT = NULL;
711 : : }
712 : : }
713 : 104 : return name;
714 : : }
715 : :
716 : : const char *
717 : 228 : _PyImport_SwapPackageContext(const char *newcontext)
718 : : {
719 : 228 : const char *oldcontext = PKGCONTEXT;
720 : 228 : PKGCONTEXT = newcontext;
721 : 228 : return oldcontext;
722 : : }
723 : :
724 : : #ifdef HAVE_DLOPEN
725 : : int
726 : 114 : _PyImport_GetDLOpenFlags(PyInterpreterState *interp)
727 : : {
728 : 114 : return DLOPENFLAGS(interp);
729 : : }
730 : :
731 : : void
732 : 0 : _PyImport_SetDLOpenFlags(PyInterpreterState *interp, int new_val)
733 : : {
734 : 0 : DLOPENFLAGS(interp) = new_val;
735 : 0 : }
736 : : #endif // HAVE_DLOPEN
737 : :
738 : :
739 : : /* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
740 : : static int
741 : 463 : exec_builtin_or_dynamic(PyObject *mod) {
742 : : PyModuleDef *def;
743 : : void *state;
744 : :
745 [ - + ]: 463 : if (!PyModule_Check(mod)) {
746 : 0 : return 0;
747 : : }
748 : :
749 : 463 : def = PyModule_GetDef(mod);
750 [ - + ]: 463 : if (def == NULL) {
751 : 0 : return 0;
752 : : }
753 : :
754 : 463 : state = PyModule_GetState(mod);
755 [ + + ]: 463 : if (state) {
756 : : /* Already initialized; skip reload */
757 : 29 : return 0;
758 : : }
759 : :
760 : 434 : return PyModule_ExecDef(mod, def);
761 : : }
762 : :
763 : :
764 : : static int clear_singlephase_extension(PyInterpreterState *interp,
765 : : PyObject *name, PyObject *filename);
766 : :
767 : : // Currently, this is only used for testing.
768 : : // (See _testinternalcapi.clear_extension().)
769 : : int
770 : 0 : _PyImport_ClearExtension(PyObject *name, PyObject *filename)
771 : : {
772 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
773 : :
774 : : /* Clearing a module's C globals is up to the module. */
775 [ # # ]: 0 : if (clear_singlephase_extension(interp, name, filename) < 0) {
776 : 0 : return -1;
777 : : }
778 : :
779 : : // In the future we'll probably also make sure the extension's
780 : : // file handle (and DL handle) is closed (requires saving it).
781 : :
782 : 0 : return 0;
783 : : }
784 : :
785 : :
786 : : /*******************/
787 : :
788 : : #if defined(__EMSCRIPTEN__) && defined(PY_CALL_TRAMPOLINE)
789 : : #include <emscripten.h>
790 : : EM_JS(PyObject*, _PyImport_InitFunc_TrampolineCall, (PyModInitFunction func), {
791 : : return wasmTable.get(func)();
792 : : });
793 : : #endif // __EMSCRIPTEN__ && PY_CALL_TRAMPOLINE
794 : :
795 : :
796 : : /*****************************/
797 : : /* single-phase init modules */
798 : : /*****************************/
799 : :
800 : : /*
801 : : We support a number of kinds of single-phase init builtin/extension modules:
802 : :
803 : : * "basic"
804 : : * no module state (PyModuleDef.m_size == -1)
805 : : * does not support repeated init (we use PyModuleDef.m_base.m_copy)
806 : : * may have process-global state
807 : : * the module's def is cached in _PyRuntime.imports.extensions,
808 : : by (name, filename)
809 : : * "reinit"
810 : : * no module state (PyModuleDef.m_size == 0)
811 : : * supports repeated init (m_copy is never used)
812 : : * should not have any process-global state
813 : : * its def is never cached in _PyRuntime.imports.extensions
814 : : (except, currently, under the main interpreter, for some reason)
815 : : * "with state" (almost the same as reinit)
816 : : * has module state (PyModuleDef.m_size > 0)
817 : : * supports repeated init (m_copy is never used)
818 : : * should not have any process-global state
819 : : * its def is never cached in _PyRuntime.imports.extensions
820 : : (except, currently, under the main interpreter, for some reason)
821 : :
822 : : There are also variants within those classes:
823 : :
824 : : * two or more modules share a PyModuleDef
825 : : * a module's init func uses another module's PyModuleDef
826 : : * a module's init func calls another's module's init func
827 : : * a module's init "func" is actually a variable statically initialized
828 : : to another module's init func
829 : : * two or modules share "methods"
830 : : * a module's init func copies another module's PyModuleDef
831 : : (with a different name)
832 : : * (basic-only) two or modules share process-global state
833 : :
834 : : In the first case, where modules share a PyModuleDef, the following
835 : : notable weirdness happens:
836 : :
837 : : * the module's __name__ matches the def, not the requested name
838 : : * the last module (with the same def) to be imported for the first time wins
839 : : * returned by PyState_Find_Module() (via interp->modules_by_index)
840 : : * (non-basic-only) its init func is used when re-loading any of them
841 : : (via the def's m_init)
842 : : * (basic-only) the copy of its __dict__ is used when re-loading any of them
843 : : (via the def's m_copy)
844 : :
845 : : However, the following happens as expected:
846 : :
847 : : * a new module object (with its own __dict__) is created for each request
848 : : * the module's __spec__ has the requested name
849 : : * the loaded module is cached in sys.modules under the requested name
850 : : * the m_index field of the shared def is not changed,
851 : : so at least PyState_FindModule() will always look in the same place
852 : :
853 : : For "basic" modules there are other quirks:
854 : :
855 : : * (whether sharing a def or not) when loaded the first time,
856 : : m_copy is set before _init_module_attrs() is called
857 : : in importlib._bootstrap.module_from_spec(),
858 : : so when the module is re-loaded, the previous value
859 : : for __wpec__ (and others) is reset, possibly unexpectedly.
860 : :
861 : : Generally, when multiple interpreters are involved, some of the above
862 : : gets even messier.
863 : : */
864 : :
865 : : /* Magic for extension modules (built-in as well as dynamically
866 : : loaded). To prevent initializing an extension module more than
867 : : once, we keep a static dictionary 'extensions' keyed by the tuple
868 : : (module name, module name) (for built-in modules) or by
869 : : (filename, module name) (for dynamically loaded modules), containing these
870 : : modules. A copy of the module's dictionary is stored by calling
871 : : _PyImport_FixupExtensionObject() immediately after the module initialization
872 : : function succeeds. A copy can be retrieved from there by calling
873 : : import_find_extension().
874 : :
875 : : Modules which do support multiple initialization set their m_size
876 : : field to a non-negative number (indicating the size of the
877 : : module-specific state). They are still recorded in the extensions
878 : : dictionary, to avoid loading shared libraries twice.
879 : : */
880 : :
881 : : static PyModuleDef *
882 : 463 : _extensions_cache_get(PyObject *filename, PyObject *name)
883 : : {
884 : 463 : PyObject *extensions = EXTENSIONS;
885 [ - + ]: 463 : if (extensions == NULL) {
886 : 0 : return NULL;
887 : : }
888 : 463 : PyObject *key = PyTuple_Pack(2, filename, name);
889 [ - + ]: 463 : if (key == NULL) {
890 : 0 : return NULL;
891 : : }
892 : 463 : PyModuleDef *def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
893 : 463 : Py_DECREF(key);
894 : 463 : return def;
895 : : }
896 : :
897 : : static int
898 : 103 : _extensions_cache_set(PyObject *filename, PyObject *name, PyModuleDef *def)
899 : : {
900 : 103 : PyObject *extensions = EXTENSIONS;
901 [ + + ]: 103 : if (extensions == NULL) {
902 : 29 : extensions = PyDict_New();
903 [ - + ]: 29 : if (extensions == NULL) {
904 : 0 : return -1;
905 : : }
906 : 29 : EXTENSIONS = extensions;
907 : : }
908 : 103 : PyObject *key = PyTuple_Pack(2, filename, name);
909 [ - + ]: 103 : if (key == NULL) {
910 : 0 : return -1;
911 : : }
912 : 103 : int res = PyDict_SetItem(extensions, key, (PyObject *)def);
913 : 103 : Py_DECREF(key);
914 [ - + ]: 103 : if (res < 0) {
915 : 0 : return -1;
916 : : }
917 : 103 : return 0;
918 : : }
919 : :
920 : : static int
921 : 0 : _extensions_cache_delete(PyObject *filename, PyObject *name)
922 : : {
923 : 0 : PyObject *extensions = EXTENSIONS;
924 [ # # ]: 0 : if (extensions == NULL) {
925 : 0 : return 0;
926 : : }
927 : 0 : PyObject *key = PyTuple_Pack(2, filename, name);
928 [ # # ]: 0 : if (key == NULL) {
929 : 0 : return -1;
930 : : }
931 [ # # ]: 0 : if (PyDict_DelItem(extensions, key) < 0) {
932 [ # # ]: 0 : if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
933 : 0 : Py_DECREF(key);
934 : 0 : return -1;
935 : : }
936 : 0 : PyErr_Clear();
937 : : }
938 : 0 : Py_DECREF(key);
939 : 0 : return 0;
940 : : }
941 : :
942 : : static void
943 : 25 : _extensions_cache_clear_all(void)
944 : : {
945 [ + - ]: 25 : Py_CLEAR(EXTENSIONS);
946 : 25 : }
947 : :
948 : :
949 : : static bool
950 : 20 : check_multi_interp_extensions(PyInterpreterState *interp)
951 : : {
952 : 20 : int override = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
953 [ - + ]: 20 : if (override < 0) {
954 : 0 : return false;
955 : : }
956 [ - + ]: 20 : else if (override > 0) {
957 : 0 : return true;
958 : : }
959 [ - + ]: 20 : else if (_PyInterpreterState_HasFeature(
960 : : interp, Py_RTFLAGS_MULTI_INTERP_EXTENSIONS)) {
961 : 0 : return true;
962 : : }
963 : 20 : return false;
964 : : }
965 : :
966 : : int
967 : 20 : _PyImport_CheckSubinterpIncompatibleExtensionAllowed(const char *name)
968 : : {
969 : 20 : PyInterpreterState *interp = _PyInterpreterState_Get();
970 [ - + ]: 20 : if (check_multi_interp_extensions(interp)) {
971 : : assert(!_Py_IsMainInterpreter(interp));
972 : 0 : PyErr_Format(PyExc_ImportError,
973 : : "module %s does not support loading in subinterpreters",
974 : : name);
975 : 0 : return -1;
976 : : }
977 : 20 : return 0;
978 : : }
979 : :
980 : : static PyObject *
981 : 73 : get_core_module_dict(PyInterpreterState *interp,
982 : : PyObject *name, PyObject *filename)
983 : : {
984 : : /* Only builtin modules are core. */
985 [ + + ]: 73 : if (filename == name) {
986 : : assert(!PyErr_Occurred());
987 [ + + ]: 59 : if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
988 : 30 : return interp->sysdict_copy;
989 : : }
990 : : assert(!PyErr_Occurred());
991 [ + - ]: 29 : if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
992 : 29 : return interp->builtins_copy;
993 : : }
994 : : assert(!PyErr_Occurred());
995 : : }
996 : 14 : return NULL;
997 : : }
998 : :
999 : : static inline int
1000 : 72 : is_core_module(PyInterpreterState *interp, PyObject *name, PyObject *filename)
1001 : : {
1002 : 72 : return get_core_module_dict(interp, name, filename) != NULL;
1003 : : }
1004 : :
1005 : : static int
1006 : 103 : fix_up_extension(PyObject *mod, PyObject *name, PyObject *filename)
1007 : : {
1008 [ + - - + ]: 103 : if (mod == NULL || !PyModule_Check(mod)) {
1009 : 0 : PyErr_BadInternalCall();
1010 : 0 : return -1;
1011 : : }
1012 : :
1013 : 103 : struct PyModuleDef *def = PyModule_GetDef(mod);
1014 [ - + ]: 103 : if (!def) {
1015 : 0 : PyErr_BadInternalCall();
1016 : 0 : return -1;
1017 : : }
1018 : :
1019 : 103 : PyThreadState *tstate = _PyThreadState_GET();
1020 [ - + ]: 103 : if (_modules_by_index_set(tstate->interp, def, mod) < 0) {
1021 : 0 : return -1;
1022 : : }
1023 : :
1024 : : // bpo-44050: Extensions and def->m_base.m_copy can be updated
1025 : : // when the extension module doesn't support sub-interpreters.
1026 [ + + ]: 103 : if (def->m_size == -1) {
1027 [ + + ]: 72 : if (!is_core_module(tstate->interp, name, filename)) {
1028 [ - + ]: 43 : if (def->m_base.m_copy) {
1029 : : /* Somebody already imported the module,
1030 : : likely under a different name.
1031 : : XXX this should really not happen. */
1032 [ # # ]: 0 : Py_CLEAR(def->m_base.m_copy);
1033 : : }
1034 : 43 : PyObject *dict = PyModule_GetDict(mod);
1035 [ - + ]: 43 : if (dict == NULL) {
1036 : 0 : return -1;
1037 : : }
1038 : 43 : def->m_base.m_copy = PyDict_Copy(dict);
1039 [ - + ]: 43 : if (def->m_base.m_copy == NULL) {
1040 : 0 : return -1;
1041 : : }
1042 : : }
1043 : : }
1044 : :
1045 : : // XXX Why special-case the main interpreter?
1046 [ - + - - ]: 103 : if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
1047 [ - + ]: 103 : if (_extensions_cache_set(filename, name, def) < 0) {
1048 : 0 : return -1;
1049 : : }
1050 : : }
1051 : :
1052 : 103 : return 0;
1053 : : }
1054 : :
1055 : : int
1056 : 45 : _PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
1057 : : PyObject *filename, PyObject *modules)
1058 : : {
1059 [ - + ]: 45 : if (PyObject_SetItem(modules, name, mod) < 0) {
1060 : 0 : return -1;
1061 : : }
1062 [ - + ]: 45 : if (fix_up_extension(mod, name, filename) < 0) {
1063 : 0 : PyMapping_DelItem(modules, name);
1064 : 0 : return -1;
1065 : : }
1066 : 45 : return 0;
1067 : : }
1068 : :
1069 : :
1070 : : static PyObject *
1071 : 463 : import_find_extension(PyThreadState *tstate, PyObject *name,
1072 : : PyObject *filename)
1073 : : {
1074 : : /* Only single-phase init modules will be in the cache. */
1075 : 463 : PyModuleDef *def = _extensions_cache_get(filename, name);
1076 [ + + ]: 463 : if (def == NULL) {
1077 : 459 : return NULL;
1078 : : }
1079 : :
1080 : : PyObject *mod, *mdict;
1081 : 4 : PyObject *modules = MODULES(tstate->interp);
1082 : :
1083 [ + + ]: 4 : if (def->m_size == -1) {
1084 : 3 : PyObject *m_copy = def->m_base.m_copy;
1085 : : /* Module does not support repeated initialization */
1086 [ + + ]: 3 : if (m_copy == NULL) {
1087 : 1 : m_copy = get_core_module_dict(tstate->interp, name, filename);
1088 [ - + ]: 1 : if (m_copy == NULL) {
1089 : 0 : return NULL;
1090 : : }
1091 : : }
1092 : 3 : mod = import_add_module(tstate, name);
1093 [ - + ]: 3 : if (mod == NULL) {
1094 : 0 : return NULL;
1095 : : }
1096 : 3 : mdict = PyModule_GetDict(mod);
1097 [ - + ]: 3 : if (mdict == NULL) {
1098 : 0 : Py_DECREF(mod);
1099 : 0 : return NULL;
1100 : : }
1101 [ - + ]: 3 : if (PyDict_Update(mdict, m_copy)) {
1102 : 0 : Py_DECREF(mod);
1103 : 0 : return NULL;
1104 : : }
1105 : : }
1106 : : else {
1107 [ - + ]: 1 : if (def->m_base.m_init == NULL)
1108 : 0 : return NULL;
1109 : 1 : mod = _PyImport_InitFunc_TrampolineCall(def->m_base.m_init);
1110 [ - + ]: 1 : if (mod == NULL)
1111 : 0 : return NULL;
1112 [ - + ]: 1 : if (PyObject_SetItem(modules, name, mod) == -1) {
1113 : 0 : Py_DECREF(mod);
1114 : 0 : return NULL;
1115 : : }
1116 : : }
1117 [ - + ]: 4 : if (_modules_by_index_set(tstate->interp, def, mod) < 0) {
1118 : 0 : PyMapping_DelItem(modules, name);
1119 : 0 : Py_DECREF(mod);
1120 : 0 : return NULL;
1121 : : }
1122 : :
1123 : 4 : int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
1124 [ - + ]: 4 : if (verbose) {
1125 : 0 : PySys_FormatStderr("import %U # previously loaded (%R)\n",
1126 : : name, filename);
1127 : : }
1128 : 4 : return mod;
1129 : : }
1130 : :
1131 : : static int
1132 : 0 : clear_singlephase_extension(PyInterpreterState *interp,
1133 : : PyObject *name, PyObject *filename)
1134 : : {
1135 : 0 : PyModuleDef *def = _extensions_cache_get(filename, name);
1136 [ # # ]: 0 : if (def == NULL) {
1137 [ # # ]: 0 : if (PyErr_Occurred()) {
1138 : 0 : return -1;
1139 : : }
1140 : 0 : return 0;
1141 : : }
1142 : :
1143 : : /* Clear data set when the module was initially loaded. */
1144 : 0 : def->m_base.m_init = NULL;
1145 [ # # ]: 0 : Py_CLEAR(def->m_base.m_copy);
1146 : : // We leave m_index alone since there's no reason to reset it.
1147 : :
1148 : : /* Clear the PyState_*Module() cache entry. */
1149 [ # # ]: 0 : if (_modules_by_index_check(interp, def->m_base.m_index) == NULL) {
1150 [ # # ]: 0 : if (_modules_by_index_clear_one(interp, def) < 0) {
1151 : 0 : return -1;
1152 : : }
1153 : : }
1154 : :
1155 : : /* Clear the cached module def. */
1156 [ # # ]: 0 : if (_extensions_cache_delete(filename, name) < 0) {
1157 : 0 : return -1;
1158 : : }
1159 : :
1160 : 0 : return 0;
1161 : : }
1162 : :
1163 : :
1164 : : /*******************/
1165 : : /* builtin modules */
1166 : : /*******************/
1167 : :
1168 : : int
1169 : 58 : _PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
1170 : : {
1171 : 58 : int res = -1;
1172 : : PyObject *nameobj;
1173 : 58 : nameobj = PyUnicode_InternFromString(name);
1174 [ - + ]: 58 : if (nameobj == NULL) {
1175 : 0 : return -1;
1176 : : }
1177 [ - + ]: 58 : if (PyObject_SetItem(modules, nameobj, mod) < 0) {
1178 : 0 : goto finally;
1179 : : }
1180 [ - + ]: 58 : if (fix_up_extension(mod, nameobj, nameobj) < 0) {
1181 : 0 : PyMapping_DelItem(modules, nameobj);
1182 : 0 : goto finally;
1183 : : }
1184 : 58 : res = 0;
1185 : :
1186 : 58 : finally:
1187 : 58 : Py_DECREF(nameobj);
1188 : 58 : return res;
1189 : : }
1190 : :
1191 : : /* Helper to test for built-in module */
1192 : :
1193 : : static int
1194 : 875 : is_builtin(PyObject *name)
1195 : : {
1196 : : int i;
1197 : 875 : struct _inittab *inittab = INITTAB;
1198 [ + + ]: 22146 : for (i = 0; inittab[i].name != NULL; i++) {
1199 [ + + ]: 21564 : if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
1200 [ - + ]: 293 : if (inittab[i].initfunc == NULL)
1201 : 0 : return -1;
1202 : : else
1203 : 293 : return 1;
1204 : : }
1205 : : }
1206 : 582 : return 0;
1207 : : }
1208 : :
1209 : : static PyObject*
1210 : 348 : create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
1211 : : {
1212 : 348 : PyObject *mod = import_find_extension(tstate, name, name);
1213 [ + + - + ]: 348 : if (mod || _PyErr_Occurred(tstate)) {
1214 : 3 : return mod;
1215 : : }
1216 : :
1217 : 345 : PyObject *modules = MODULES(tstate->interp);
1218 [ + - ]: 5082 : for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
1219 [ + + ]: 5082 : if (_PyUnicode_EqualToASCIIString(name, p->name)) {
1220 [ - + ]: 345 : if (p->initfunc == NULL) {
1221 : : /* Cannot re-init internal module ("sys" or "builtins") */
1222 : 0 : mod = PyImport_AddModuleObject(name);
1223 : 0 : return Py_XNewRef(mod);
1224 : : }
1225 : 345 : mod = _PyImport_InitFunc_TrampolineCall(*p->initfunc);
1226 [ - + ]: 345 : if (mod == NULL) {
1227 : 0 : return NULL;
1228 : : }
1229 : :
1230 [ + + ]: 345 : if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
1231 : 319 : return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
1232 : : }
1233 : : else {
1234 : : /* Remember pointer to module init function. */
1235 : 26 : PyModuleDef *def = PyModule_GetDef(mod);
1236 [ - + ]: 26 : if (def == NULL) {
1237 : 0 : return NULL;
1238 : : }
1239 : :
1240 : 26 : def->m_base.m_init = p->initfunc;
1241 [ - + ]: 26 : if (_PyImport_FixupExtensionObject(mod, name, name,
1242 : : modules) < 0) {
1243 : 0 : return NULL;
1244 : : }
1245 : 26 : return mod;
1246 : : }
1247 : : }
1248 : : }
1249 : :
1250 : : // not found
1251 : 0 : Py_RETURN_NONE;
1252 : : }
1253 : :
1254 : :
1255 : : /*****************************/
1256 : : /* the builtin modules table */
1257 : : /*****************************/
1258 : :
1259 : : /* API for embedding applications that want to add their own entries
1260 : : to the table of built-in modules. This should normally be called
1261 : : *before* Py_Initialize(). When the table resize fails, -1 is
1262 : : returned and the existing table is unchanged.
1263 : :
1264 : : After a similar function by Just van Rossum. */
1265 : :
1266 : : int
1267 : 0 : PyImport_ExtendInittab(struct _inittab *newtab)
1268 : : {
1269 : : struct _inittab *p;
1270 : : size_t i, n;
1271 : 0 : int res = 0;
1272 : :
1273 [ # # ]: 0 : if (INITTAB != NULL) {
1274 : 0 : Py_FatalError("PyImport_ExtendInittab() may not be called after Py_Initialize()");
1275 : : }
1276 : :
1277 : : /* Count the number of entries in both tables */
1278 [ # # ]: 0 : for (n = 0; newtab[n].name != NULL; n++)
1279 : : ;
1280 [ # # ]: 0 : if (n == 0)
1281 : 0 : return 0; /* Nothing to do */
1282 [ # # ]: 0 : for (i = 0; PyImport_Inittab[i].name != NULL; i++)
1283 : : ;
1284 : :
1285 : : /* Force default raw memory allocator to get a known allocator to be able
1286 : : to release the memory in _PyImport_Fini2() */
1287 : : PyMemAllocatorEx old_alloc;
1288 : 0 : _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1289 : :
1290 : : /* Allocate new memory for the combined table */
1291 : 0 : p = NULL;
1292 [ # # ]: 0 : if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
1293 : 0 : size_t size = sizeof(struct _inittab) * (i + n + 1);
1294 : 0 : p = PyMem_RawRealloc(inittab_copy, size);
1295 : : }
1296 [ # # ]: 0 : if (p == NULL) {
1297 : 0 : res = -1;
1298 : 0 : goto done;
1299 : : }
1300 : :
1301 : : /* Copy the tables into the new memory at the first call
1302 : : to PyImport_ExtendInittab(). */
1303 [ # # ]: 0 : if (inittab_copy != PyImport_Inittab) {
1304 : 0 : memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
1305 : : }
1306 : 0 : memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
1307 : 0 : PyImport_Inittab = inittab_copy = p;
1308 : :
1309 : 0 : done:
1310 : 0 : PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1311 : 0 : return res;
1312 : : }
1313 : :
1314 : : /* Shorthand to add a single entry given a name and a function */
1315 : :
1316 : : int
1317 : 0 : PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
1318 : : {
1319 : : struct _inittab newtab[2];
1320 : :
1321 [ # # ]: 0 : if (INITTAB != NULL) {
1322 : 0 : Py_FatalError("PyImport_AppendInittab() may not be called after Py_Initialize()");
1323 : : }
1324 : :
1325 : 0 : memset(newtab, '\0', sizeof newtab);
1326 : :
1327 : 0 : newtab[0].name = name;
1328 : 0 : newtab[0].initfunc = initfunc;
1329 : :
1330 : 0 : return PyImport_ExtendInittab(newtab);
1331 : : }
1332 : :
1333 : :
1334 : : /* the internal table */
1335 : :
1336 : : static int
1337 : 29 : init_builtin_modules_table(void)
1338 : : {
1339 : : size_t size;
1340 [ + + ]: 899 : for (size = 0; PyImport_Inittab[size].name != NULL; size++)
1341 : : ;
1342 : 29 : size++;
1343 : :
1344 : : /* Make the copy. */
1345 : 29 : struct _inittab *copied = PyMem_RawMalloc(size * sizeof(struct _inittab));
1346 [ - + ]: 29 : if (copied == NULL) {
1347 : 0 : return -1;
1348 : : }
1349 : 29 : memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
1350 : 29 : INITTAB = copied;
1351 : 29 : return 0;
1352 : : }
1353 : :
1354 : : static void
1355 : 25 : fini_builtin_modules_table(void)
1356 : : {
1357 : 25 : struct _inittab *inittab = INITTAB;
1358 : 25 : INITTAB = NULL;
1359 : 25 : PyMem_RawFree(inittab);
1360 : 25 : }
1361 : :
1362 : : PyObject *
1363 : 29 : _PyImport_GetBuiltinModuleNames(void)
1364 : : {
1365 : 29 : PyObject *list = PyList_New(0);
1366 [ - + ]: 29 : if (list == NULL) {
1367 : 0 : return NULL;
1368 : : }
1369 : 29 : struct _inittab *inittab = INITTAB;
1370 [ + + ]: 899 : for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
1371 : 870 : PyObject *name = PyUnicode_FromString(inittab[i].name);
1372 [ - + ]: 870 : if (name == NULL) {
1373 : 0 : Py_DECREF(list);
1374 : 0 : return NULL;
1375 : : }
1376 [ - + ]: 870 : if (PyList_Append(list, name) < 0) {
1377 : 0 : Py_DECREF(name);
1378 : 0 : Py_DECREF(list);
1379 : 0 : return NULL;
1380 : : }
1381 : 870 : Py_DECREF(name);
1382 : : }
1383 : 29 : return list;
1384 : : }
1385 : :
1386 : :
1387 : : /********************/
1388 : : /* the magic number */
1389 : : /********************/
1390 : :
1391 : : /* Helper for pythonrun.c -- return magic number and tag. */
1392 : :
1393 : : long
1394 : 22 : PyImport_GetMagicNumber(void)
1395 : : {
1396 : : long res;
1397 : 22 : PyInterpreterState *interp = _PyInterpreterState_GET();
1398 : : PyObject *external, *pyc_magic;
1399 : :
1400 : 22 : external = PyObject_GetAttrString(IMPORTLIB(interp), "_bootstrap_external");
1401 [ - + ]: 22 : if (external == NULL)
1402 : 0 : return -1;
1403 : 22 : pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
1404 : 22 : Py_DECREF(external);
1405 [ - + ]: 22 : if (pyc_magic == NULL)
1406 : 0 : return -1;
1407 : 22 : res = PyLong_AsLong(pyc_magic);
1408 : 22 : Py_DECREF(pyc_magic);
1409 : 22 : return res;
1410 : : }
1411 : :
1412 : :
1413 : : extern const char * _PySys_ImplCacheTag;
1414 : :
1415 : : const char *
1416 : 0 : PyImport_GetMagicTag(void)
1417 : : {
1418 : 0 : return _PySys_ImplCacheTag;
1419 : : }
1420 : :
1421 : :
1422 : : /*********************************/
1423 : : /* a Python module's code object */
1424 : : /*********************************/
1425 : :
1426 : : /* Execute a code object in a module and return the module object
1427 : : * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
1428 : : * removed from sys.modules, to avoid leaving damaged module objects
1429 : : * in sys.modules. The caller may wish to restore the original
1430 : : * module object (if any) in this case; PyImport_ReloadModule is an
1431 : : * example.
1432 : : *
1433 : : * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
1434 : : * interface. The other two exist primarily for backward compatibility.
1435 : : */
1436 : : PyObject *
1437 : 0 : PyImport_ExecCodeModule(const char *name, PyObject *co)
1438 : : {
1439 : 0 : return PyImport_ExecCodeModuleWithPathnames(
1440 : : name, co, (char *)NULL, (char *)NULL);
1441 : : }
1442 : :
1443 : : PyObject *
1444 : 0 : PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
1445 : : {
1446 : 0 : return PyImport_ExecCodeModuleWithPathnames(
1447 : : name, co, pathname, (char *)NULL);
1448 : : }
1449 : :
1450 : : PyObject *
1451 : 0 : PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
1452 : : const char *pathname,
1453 : : const char *cpathname)
1454 : : {
1455 : 0 : PyObject *m = NULL;
1456 : 0 : PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
1457 : :
1458 : 0 : nameobj = PyUnicode_FromString(name);
1459 [ # # ]: 0 : if (nameobj == NULL)
1460 : 0 : return NULL;
1461 : :
1462 [ # # ]: 0 : if (cpathname != NULL) {
1463 : 0 : cpathobj = PyUnicode_DecodeFSDefault(cpathname);
1464 [ # # ]: 0 : if (cpathobj == NULL)
1465 : 0 : goto error;
1466 : : }
1467 : : else
1468 : 0 : cpathobj = NULL;
1469 : :
1470 [ # # ]: 0 : if (pathname != NULL) {
1471 : 0 : pathobj = PyUnicode_DecodeFSDefault(pathname);
1472 [ # # ]: 0 : if (pathobj == NULL)
1473 : 0 : goto error;
1474 : : }
1475 [ # # ]: 0 : else if (cpathobj != NULL) {
1476 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
1477 : :
1478 [ # # ]: 0 : if (interp == NULL) {
1479 : 0 : Py_FatalError("no current interpreter");
1480 : : }
1481 : :
1482 : 0 : external= PyObject_GetAttrString(IMPORTLIB(interp),
1483 : : "_bootstrap_external");
1484 [ # # ]: 0 : if (external != NULL) {
1485 : 0 : pathobj = _PyObject_CallMethodOneArg(
1486 : : external, &_Py_ID(_get_sourcefile), cpathobj);
1487 : 0 : Py_DECREF(external);
1488 : : }
1489 [ # # ]: 0 : if (pathobj == NULL)
1490 : 0 : PyErr_Clear();
1491 : : }
1492 : : else
1493 : 0 : pathobj = NULL;
1494 : :
1495 : 0 : m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
1496 : 0 : error:
1497 : 0 : Py_DECREF(nameobj);
1498 : 0 : Py_XDECREF(pathobj);
1499 : 0 : Py_XDECREF(cpathobj);
1500 : 0 : return m;
1501 : : }
1502 : :
1503 : : static PyObject *
1504 : 25 : module_dict_for_exec(PyThreadState *tstate, PyObject *name)
1505 : : {
1506 : : PyObject *m, *d;
1507 : :
1508 : 25 : m = import_add_module(tstate, name);
1509 [ - + ]: 25 : if (m == NULL)
1510 : 0 : return NULL;
1511 : : /* If the module is being reloaded, we get the old module back
1512 : : and re-use its dict to exec the new code. */
1513 : 25 : d = PyModule_GetDict(m);
1514 : 25 : int r = PyDict_Contains(d, &_Py_ID(__builtins__));
1515 [ + - ]: 25 : if (r == 0) {
1516 : 25 : r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
1517 : : }
1518 [ - + ]: 25 : if (r < 0) {
1519 : 0 : remove_module(tstate, name);
1520 : 0 : Py_DECREF(m);
1521 : 0 : return NULL;
1522 : : }
1523 : :
1524 : 25 : Py_INCREF(d);
1525 : 25 : Py_DECREF(m);
1526 : 25 : return d;
1527 : : }
1528 : :
1529 : : static PyObject *
1530 : 25 : exec_code_in_module(PyThreadState *tstate, PyObject *name,
1531 : : PyObject *module_dict, PyObject *code_object)
1532 : : {
1533 : : PyObject *v, *m;
1534 : :
1535 : 25 : v = PyEval_EvalCode(code_object, module_dict, module_dict);
1536 [ - + ]: 25 : if (v == NULL) {
1537 : 0 : remove_module(tstate, name);
1538 : 0 : return NULL;
1539 : : }
1540 : 25 : Py_DECREF(v);
1541 : :
1542 : 25 : m = import_get_module(tstate, name);
1543 [ - + - - ]: 25 : if (m == NULL && !_PyErr_Occurred(tstate)) {
1544 : 0 : _PyErr_Format(tstate, PyExc_ImportError,
1545 : : "Loaded module %R not found in sys.modules",
1546 : : name);
1547 : : }
1548 : :
1549 : 25 : return m;
1550 : : }
1551 : :
1552 : : PyObject*
1553 : 0 : PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
1554 : : PyObject *cpathname)
1555 : : {
1556 : 0 : PyThreadState *tstate = _PyThreadState_GET();
1557 : : PyObject *d, *external, *res;
1558 : :
1559 : 0 : d = module_dict_for_exec(tstate, name);
1560 [ # # ]: 0 : if (d == NULL) {
1561 : 0 : return NULL;
1562 : : }
1563 : :
1564 [ # # ]: 0 : if (pathname == NULL) {
1565 : 0 : pathname = ((PyCodeObject *)co)->co_filename;
1566 : : }
1567 : 0 : external = PyObject_GetAttrString(IMPORTLIB(tstate->interp),
1568 : : "_bootstrap_external");
1569 [ # # ]: 0 : if (external == NULL) {
1570 : 0 : Py_DECREF(d);
1571 : 0 : return NULL;
1572 : : }
1573 : 0 : res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module),
1574 : : d, name, pathname, cpathname, NULL);
1575 : 0 : Py_DECREF(external);
1576 [ # # ]: 0 : if (res != NULL) {
1577 : 0 : Py_DECREF(res);
1578 : 0 : res = exec_code_in_module(tstate, name, d, co);
1579 : : }
1580 : 0 : Py_DECREF(d);
1581 : 0 : return res;
1582 : : }
1583 : :
1584 : :
1585 : : static void
1586 : 0 : update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
1587 : : {
1588 : : PyObject *constants, *tmp;
1589 : : Py_ssize_t i, n;
1590 : :
1591 [ # # ]: 0 : if (PyUnicode_Compare(co->co_filename, oldname))
1592 : 0 : return;
1593 : :
1594 : 0 : Py_XSETREF(co->co_filename, Py_NewRef(newname));
1595 : :
1596 : 0 : constants = co->co_consts;
1597 : 0 : n = PyTuple_GET_SIZE(constants);
1598 [ # # ]: 0 : for (i = 0; i < n; i++) {
1599 : 0 : tmp = PyTuple_GET_ITEM(constants, i);
1600 [ # # ]: 0 : if (PyCode_Check(tmp))
1601 : 0 : update_code_filenames((PyCodeObject *)tmp,
1602 : : oldname, newname);
1603 : : }
1604 : : }
1605 : :
1606 : : static void
1607 : 386 : update_compiled_module(PyCodeObject *co, PyObject *newname)
1608 : : {
1609 : : PyObject *oldname;
1610 : :
1611 [ + - ]: 386 : if (PyUnicode_Compare(co->co_filename, newname) == 0)
1612 : 386 : return;
1613 : :
1614 : 0 : oldname = co->co_filename;
1615 : 0 : Py_INCREF(oldname);
1616 : 0 : update_code_filenames(co, oldname, newname);
1617 : 0 : Py_DECREF(oldname);
1618 : : }
1619 : :
1620 : :
1621 : : /******************/
1622 : : /* frozen modules */
1623 : : /******************/
1624 : :
1625 : : /* Return true if the name is an alias. In that case, "alias" is set
1626 : : to the original module name. If it is an alias but the original
1627 : : module isn't known then "alias" is set to NULL while true is returned. */
1628 : : static bool
1629 : 269 : resolve_module_alias(const char *name, const struct _module_alias *aliases,
1630 : : const char **alias)
1631 : : {
1632 : : const struct _module_alias *entry;
1633 : 1321 : for (entry = aliases; ; entry++) {
1634 [ + + ]: 1321 : if (entry->name == NULL) {
1635 : : /* It isn't an alias. */
1636 : 144 : return false;
1637 : : }
1638 [ + + ]: 1177 : if (strcmp(name, entry->name) == 0) {
1639 [ + - ]: 125 : if (alias != NULL) {
1640 : 125 : *alias = entry->orig;
1641 : : }
1642 : 125 : return true;
1643 : : }
1644 : : }
1645 : : }
1646 : :
1647 : : static bool
1648 : 717 : use_frozen(void)
1649 : : {
1650 : 717 : PyInterpreterState *interp = _PyInterpreterState_GET();
1651 : 717 : int override = OVERRIDE_FROZEN_MODULES(interp);
1652 [ - + ]: 717 : if (override > 0) {
1653 : 0 : return true;
1654 : : }
1655 [ - + ]: 717 : else if (override < 0) {
1656 : 0 : return false;
1657 : : }
1658 : : else {
1659 : 717 : return interp->config.use_frozen_modules;
1660 : : }
1661 : : }
1662 : :
1663 : : static PyObject *
1664 : 0 : list_frozen_module_names(void)
1665 : : {
1666 : 0 : PyObject *names = PyList_New(0);
1667 [ # # ]: 0 : if (names == NULL) {
1668 : 0 : return NULL;
1669 : : }
1670 : 0 : bool enabled = use_frozen();
1671 : : const struct _frozen *p;
1672 : : #define ADD_MODULE(name) \
1673 : : do { \
1674 : : PyObject *nameobj = PyUnicode_FromString(name); \
1675 : : if (nameobj == NULL) { \
1676 : : goto error; \
1677 : : } \
1678 : : int res = PyList_Append(names, nameobj); \
1679 : : Py_DECREF(nameobj); \
1680 : : if (res != 0) { \
1681 : : goto error; \
1682 : : } \
1683 : : } while(0)
1684 : : // We always use the bootstrap modules.
1685 : 0 : for (p = _PyImport_FrozenBootstrap; ; p++) {
1686 [ # # ]: 0 : if (p->name == NULL) {
1687 : 0 : break;
1688 : : }
1689 [ # # # # ]: 0 : ADD_MODULE(p->name);
1690 : : }
1691 : : // Frozen stdlib modules may be disabled.
1692 : 0 : for (p = _PyImport_FrozenStdlib; ; p++) {
1693 [ # # ]: 0 : if (p->name == NULL) {
1694 : 0 : break;
1695 : : }
1696 [ # # ]: 0 : if (enabled) {
1697 [ # # # # ]: 0 : ADD_MODULE(p->name);
1698 : : }
1699 : : }
1700 : 0 : for (p = _PyImport_FrozenTest; ; p++) {
1701 [ # # ]: 0 : if (p->name == NULL) {
1702 : 0 : break;
1703 : : }
1704 [ # # ]: 0 : if (enabled) {
1705 [ # # # # ]: 0 : ADD_MODULE(p->name);
1706 : : }
1707 : : }
1708 : : #undef ADD_MODULE
1709 : : // Add any custom modules.
1710 [ # # ]: 0 : if (PyImport_FrozenModules != NULL) {
1711 : 0 : for (p = PyImport_FrozenModules; ; p++) {
1712 [ # # ]: 0 : if (p->name == NULL) {
1713 : 0 : break;
1714 : : }
1715 : 0 : PyObject *nameobj = PyUnicode_FromString(p->name);
1716 [ # # ]: 0 : if (nameobj == NULL) {
1717 : 0 : goto error;
1718 : : }
1719 : 0 : int found = PySequence_Contains(names, nameobj);
1720 [ # # ]: 0 : if (found < 0) {
1721 : 0 : Py_DECREF(nameobj);
1722 : 0 : goto error;
1723 : : }
1724 [ # # ]: 0 : else if (found) {
1725 : 0 : Py_DECREF(nameobj);
1726 : : }
1727 : : else {
1728 : 0 : int res = PyList_Append(names, nameobj);
1729 : 0 : Py_DECREF(nameobj);
1730 [ # # ]: 0 : if (res != 0) {
1731 : 0 : goto error;
1732 : : }
1733 : : }
1734 : : }
1735 : : }
1736 : 0 : return names;
1737 : :
1738 : 0 : error:
1739 : 0 : Py_DECREF(names);
1740 : 0 : return NULL;
1741 : : }
1742 : :
1743 : : typedef enum {
1744 : : FROZEN_OKAY,
1745 : : FROZEN_BAD_NAME, // The given module name wasn't valid.
1746 : : FROZEN_NOT_FOUND, // It wasn't in PyImport_FrozenModules.
1747 : : FROZEN_DISABLED, // -X frozen_modules=off (and not essential)
1748 : : FROZEN_EXCLUDED, /* The PyImport_FrozenModules entry has NULL "code"
1749 : : (module is present but marked as unimportable, stops search). */
1750 : : FROZEN_INVALID, /* The PyImport_FrozenModules entry is bogus
1751 : : (eg. does not contain executable code). */
1752 : : } frozen_status;
1753 : :
1754 : : static inline void
1755 : 0 : set_frozen_error(frozen_status status, PyObject *modname)
1756 : : {
1757 : 0 : const char *err = NULL;
1758 [ # # # # : 0 : switch (status) {
# # ]
1759 : 0 : case FROZEN_BAD_NAME:
1760 : : case FROZEN_NOT_FOUND:
1761 : 0 : err = "No such frozen object named %R";
1762 : 0 : break;
1763 : 0 : case FROZEN_DISABLED:
1764 : 0 : err = "Frozen modules are disabled and the frozen object named %R is not essential";
1765 : 0 : break;
1766 : 0 : case FROZEN_EXCLUDED:
1767 : 0 : err = "Excluded frozen object named %R";
1768 : 0 : break;
1769 : 0 : case FROZEN_INVALID:
1770 : 0 : err = "Frozen object named %R is invalid";
1771 : 0 : break;
1772 : 0 : case FROZEN_OKAY:
1773 : : // There was no error.
1774 : 0 : break;
1775 : 0 : default:
1776 : 0 : Py_UNREACHABLE();
1777 : : }
1778 [ # # ]: 0 : if (err != NULL) {
1779 : 0 : PyObject *msg = PyUnicode_FromFormat(err, modname);
1780 [ # # ]: 0 : if (msg == NULL) {
1781 : 0 : PyErr_Clear();
1782 : : }
1783 : 0 : PyErr_SetImportError(msg, modname, NULL);
1784 : 0 : Py_XDECREF(msg);
1785 : : }
1786 : 0 : }
1787 : :
1788 : : static const struct _frozen *
1789 : 892 : look_up_frozen(const char *name)
1790 : : {
1791 : : const struct _frozen *p;
1792 : : // We always use the bootstrap modules.
1793 : 3193 : for (p = _PyImport_FrozenBootstrap; ; p++) {
1794 [ + + ]: 3193 : if (p->name == NULL) {
1795 : : // We hit the end-of-list sentinel value.
1796 : 717 : break;
1797 : : }
1798 [ + + ]: 2476 : if (strcmp(name, p->name) == 0) {
1799 : 175 : return p;
1800 : : }
1801 : : }
1802 : : // Prefer custom modules, if any. Frozen stdlib modules can be
1803 : : // disabled here by setting "code" to NULL in the array entry.
1804 [ - + ]: 717 : if (PyImport_FrozenModules != NULL) {
1805 : 0 : for (p = PyImport_FrozenModules; ; p++) {
1806 [ # # ]: 0 : if (p->name == NULL) {
1807 : 0 : break;
1808 : : }
1809 [ # # ]: 0 : if (strcmp(name, p->name) == 0) {
1810 : 0 : return p;
1811 : : }
1812 : : }
1813 : : }
1814 : : // Frozen stdlib modules may be disabled.
1815 [ + - ]: 717 : if (use_frozen()) {
1816 : 5763 : for (p = _PyImport_FrozenStdlib; ; p++) {
1817 [ + + ]: 5763 : if (p->name == NULL) {
1818 : 623 : break;
1819 : : }
1820 [ + + ]: 5140 : if (strcmp(name, p->name) == 0) {
1821 : 94 : return p;
1822 : : }
1823 : : }
1824 : 3879 : for (p = _PyImport_FrozenTest; ; p++) {
1825 [ + + ]: 3879 : if (p->name == NULL) {
1826 : 623 : break;
1827 : : }
1828 [ - + ]: 3256 : if (strcmp(name, p->name) == 0) {
1829 : 0 : return p;
1830 : : }
1831 : : }
1832 : : }
1833 : 623 : return NULL;
1834 : : }
1835 : :
1836 : : struct frozen_info {
1837 : : PyObject *nameobj;
1838 : : const char *data;
1839 : : PyObject *(*get_code)(void);
1840 : : Py_ssize_t size;
1841 : : bool is_package;
1842 : : bool is_alias;
1843 : : const char *origname;
1844 : : };
1845 : :
1846 : : static frozen_status
1847 : 892 : find_frozen(PyObject *nameobj, struct frozen_info *info)
1848 : : {
1849 [ + - ]: 892 : if (info != NULL) {
1850 : 892 : memset(info, 0, sizeof(*info));
1851 : : }
1852 : :
1853 [ + - - + ]: 892 : if (nameobj == NULL || nameobj == Py_None) {
1854 : 0 : return FROZEN_BAD_NAME;
1855 : : }
1856 : 892 : const char *name = PyUnicode_AsUTF8(nameobj);
1857 [ - + ]: 892 : if (name == NULL) {
1858 : : // Note that this function previously used
1859 : : // _PyUnicode_EqualToASCIIString(). We clear the error here
1860 : : // (instead of propagating it) to match the earlier behavior
1861 : : // more closely.
1862 : 0 : PyErr_Clear();
1863 : 0 : return FROZEN_BAD_NAME;
1864 : : }
1865 : :
1866 : 892 : const struct _frozen *p = look_up_frozen(name);
1867 [ + + ]: 892 : if (p == NULL) {
1868 : 623 : return FROZEN_NOT_FOUND;
1869 : : }
1870 [ + - ]: 269 : if (info != NULL) {
1871 : 269 : info->nameobj = nameobj; // borrowed
1872 : 269 : info->data = (const char *)p->code;
1873 : 269 : info->get_code = p->get_code;
1874 : 269 : info->size = p->size;
1875 : 269 : info->is_package = p->is_package;
1876 [ - + ]: 269 : if (p->size < 0) {
1877 : : // backward compatibility with negative size values
1878 : 0 : info->size = -(p->size);
1879 : 0 : info->is_package = true;
1880 : : }
1881 : 269 : info->origname = name;
1882 : 269 : info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
1883 : : &info->origname);
1884 : : }
1885 [ + + + - : 269 : if (p->code == NULL && p->size == 0 && p->get_code != NULL) {
+ - ]
1886 : : /* It is only deepfrozen. */
1887 : 122 : return FROZEN_OKAY;
1888 : : }
1889 [ - + ]: 147 : if (p->code == NULL) {
1890 : : /* It is frozen but marked as un-importable. */
1891 : 0 : return FROZEN_EXCLUDED;
1892 : : }
1893 [ + - - + ]: 147 : if (p->code[0] == '\0' || p->size == 0) {
1894 : : /* Does not contain executable code. */
1895 : 0 : return FROZEN_INVALID;
1896 : : }
1897 : 147 : return FROZEN_OKAY;
1898 : : }
1899 : :
1900 : : static PyObject *
1901 : 122 : unmarshal_frozen_code(struct frozen_info *info)
1902 : : {
1903 [ + + ]: 122 : if (info->get_code) {
1904 : 59 : PyObject *code = info->get_code();
1905 : : assert(code != NULL);
1906 : 59 : return code;
1907 : : }
1908 : 63 : PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
1909 [ - + ]: 63 : if (co == NULL) {
1910 : : /* Does not contain executable code. */
1911 : 0 : set_frozen_error(FROZEN_INVALID, info->nameobj);
1912 : 0 : return NULL;
1913 : : }
1914 [ - + ]: 63 : if (!PyCode_Check(co)) {
1915 : : // We stick with TypeError for backward compatibility.
1916 : 0 : PyErr_Format(PyExc_TypeError,
1917 : : "frozen object %R is not a code object",
1918 : : info->nameobj);
1919 : 0 : Py_DECREF(co);
1920 : 0 : return NULL;
1921 : : }
1922 : 63 : return co;
1923 : : }
1924 : :
1925 : :
1926 : : /* Initialize a frozen module.
1927 : : Return 1 for success, 0 if the module is not found, and -1 with
1928 : : an exception set if the initialization failed.
1929 : : This function is also used from frozenmain.c */
1930 : :
1931 : : int
1932 : 25 : PyImport_ImportFrozenModuleObject(PyObject *name)
1933 : : {
1934 : 25 : PyThreadState *tstate = _PyThreadState_GET();
1935 : 25 : PyObject *co, *m, *d = NULL;
1936 : : int err;
1937 : :
1938 : : struct frozen_info info;
1939 : 25 : frozen_status status = find_frozen(name, &info);
1940 [ + - - + ]: 25 : if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
1941 : 0 : return 0;
1942 : : }
1943 [ - + ]: 25 : else if (status == FROZEN_BAD_NAME) {
1944 : 0 : return 0;
1945 : : }
1946 [ - + ]: 25 : else if (status != FROZEN_OKAY) {
1947 : 0 : set_frozen_error(status, name);
1948 : 0 : return -1;
1949 : : }
1950 : 25 : co = unmarshal_frozen_code(&info);
1951 [ - + ]: 25 : if (co == NULL) {
1952 : 0 : return -1;
1953 : : }
1954 [ - + ]: 25 : if (info.is_package) {
1955 : : /* Set __path__ to the empty list */
1956 : : PyObject *l;
1957 : 0 : m = import_add_module(tstate, name);
1958 [ # # ]: 0 : if (m == NULL)
1959 : 0 : goto err_return;
1960 : 0 : d = PyModule_GetDict(m);
1961 : 0 : l = PyList_New(0);
1962 [ # # ]: 0 : if (l == NULL) {
1963 : 0 : Py_DECREF(m);
1964 : 0 : goto err_return;
1965 : : }
1966 : 0 : err = PyDict_SetItemString(d, "__path__", l);
1967 : 0 : Py_DECREF(l);
1968 : 0 : Py_DECREF(m);
1969 [ # # ]: 0 : if (err != 0)
1970 : 0 : goto err_return;
1971 : : }
1972 : 25 : d = module_dict_for_exec(tstate, name);
1973 [ - + ]: 25 : if (d == NULL) {
1974 : 0 : goto err_return;
1975 : : }
1976 : 25 : m = exec_code_in_module(tstate, name, d, co);
1977 [ - + ]: 25 : if (m == NULL) {
1978 : 0 : goto err_return;
1979 : : }
1980 : 25 : Py_DECREF(m);
1981 : : /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
1982 : : PyObject *origname;
1983 [ + - ]: 25 : if (info.origname) {
1984 : 25 : origname = PyUnicode_FromString(info.origname);
1985 [ - + ]: 25 : if (origname == NULL) {
1986 : 0 : goto err_return;
1987 : : }
1988 : : }
1989 : : else {
1990 : 0 : origname = Py_NewRef(Py_None);
1991 : : }
1992 : 25 : err = PyDict_SetItemString(d, "__origname__", origname);
1993 : 25 : Py_DECREF(origname);
1994 [ - + ]: 25 : if (err != 0) {
1995 : 0 : goto err_return;
1996 : : }
1997 : 25 : Py_DECREF(d);
1998 : 25 : Py_DECREF(co);
1999 : 25 : return 1;
2000 : :
2001 : 0 : err_return:
2002 : 0 : Py_XDECREF(d);
2003 : 0 : Py_DECREF(co);
2004 : 0 : return -1;
2005 : : }
2006 : :
2007 : : int
2008 : 25 : PyImport_ImportFrozenModule(const char *name)
2009 : : {
2010 : : PyObject *nameobj;
2011 : : int ret;
2012 : 25 : nameobj = PyUnicode_InternFromString(name);
2013 [ - + ]: 25 : if (nameobj == NULL)
2014 : 0 : return -1;
2015 : 25 : ret = PyImport_ImportFrozenModuleObject(nameobj);
2016 : 25 : Py_DECREF(nameobj);
2017 : 25 : return ret;
2018 : : }
2019 : :
2020 : :
2021 : : /*************/
2022 : : /* importlib */
2023 : : /*************/
2024 : :
2025 : : /* Import the _imp extension by calling manually _imp.create_builtin() and
2026 : : _imp.exec_builtin() since importlib is not initialized yet. Initializing
2027 : : importlib requires the _imp module: this function fix the bootstrap issue.
2028 : : */
2029 : : static PyObject*
2030 : 25 : bootstrap_imp(PyThreadState *tstate)
2031 : : {
2032 : 25 : PyObject *name = PyUnicode_FromString("_imp");
2033 [ - + ]: 25 : if (name == NULL) {
2034 : 0 : return NULL;
2035 : : }
2036 : :
2037 : : // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2038 : : // an object with just a name attribute.
2039 : : //
2040 : : // _imp.__spec__ is overridden by importlib._bootstrap._instal() anyway.
2041 : 25 : PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2042 [ - + ]: 25 : if (attrs == NULL) {
2043 : 0 : goto error;
2044 : : }
2045 : 25 : PyObject *spec = _PyNamespace_New(attrs);
2046 : 25 : Py_DECREF(attrs);
2047 [ - + ]: 25 : if (spec == NULL) {
2048 : 0 : goto error;
2049 : : }
2050 : :
2051 : : // Create the _imp module from its definition.
2052 : 25 : PyObject *mod = create_builtin(tstate, name, spec);
2053 [ + - ]: 25 : Py_CLEAR(name);
2054 : 25 : Py_DECREF(spec);
2055 [ - + ]: 25 : if (mod == NULL) {
2056 : 0 : goto error;
2057 : : }
2058 : : assert(mod != Py_None); // not found
2059 : :
2060 : : // Execute the _imp module: call imp_module_exec().
2061 [ - + ]: 25 : if (exec_builtin_or_dynamic(mod) < 0) {
2062 : 0 : Py_DECREF(mod);
2063 : 0 : goto error;
2064 : : }
2065 : 25 : return mod;
2066 : :
2067 : 0 : error:
2068 : 0 : Py_XDECREF(name);
2069 : 0 : return NULL;
2070 : : }
2071 : :
2072 : : /* Global initializations. Can be undone by Py_FinalizeEx(). Don't
2073 : : call this twice without an intervening Py_FinalizeEx() call. When
2074 : : initializations fail, a fatal error is issued and the function does
2075 : : not return. On return, the first thread and interpreter state have
2076 : : been created.
2077 : :
2078 : : Locking: you must hold the interpreter lock while calling this.
2079 : : (If the lock has not yet been initialized, that's equivalent to
2080 : : having the lock, but you cannot use multiple threads.)
2081 : :
2082 : : */
2083 : : static int
2084 : 25 : init_importlib(PyThreadState *tstate, PyObject *sysmod)
2085 : : {
2086 : : assert(!_PyErr_Occurred(tstate));
2087 : :
2088 : 25 : PyInterpreterState *interp = tstate->interp;
2089 : 25 : int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
2090 : :
2091 : : // Import _importlib through its frozen version, _frozen_importlib.
2092 [ - + ]: 25 : if (verbose) {
2093 : 0 : PySys_FormatStderr("import _frozen_importlib # frozen\n");
2094 : : }
2095 [ - + ]: 25 : if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
2096 : 0 : return -1;
2097 : : }
2098 : 25 : PyObject *importlib = PyImport_AddModule("_frozen_importlib"); // borrowed
2099 [ - + ]: 25 : if (importlib == NULL) {
2100 : 0 : return -1;
2101 : : }
2102 : 25 : IMPORTLIB(interp) = Py_NewRef(importlib);
2103 : :
2104 : : // Import the _imp module
2105 [ - + ]: 25 : if (verbose) {
2106 : 0 : PySys_FormatStderr("import _imp # builtin\n");
2107 : : }
2108 : 25 : PyObject *imp_mod = bootstrap_imp(tstate);
2109 [ - + ]: 25 : if (imp_mod == NULL) {
2110 : 0 : return -1;
2111 : : }
2112 [ - + ]: 25 : if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
2113 : 0 : Py_DECREF(imp_mod);
2114 : 0 : return -1;
2115 : : }
2116 : :
2117 : : // Install importlib as the implementation of import
2118 : 25 : PyObject *value = PyObject_CallMethod(importlib, "_install",
2119 : : "OO", sysmod, imp_mod);
2120 : 25 : Py_DECREF(imp_mod);
2121 [ - + ]: 25 : if (value == NULL) {
2122 : 0 : return -1;
2123 : : }
2124 : 25 : Py_DECREF(value);
2125 : :
2126 : : assert(!_PyErr_Occurred(tstate));
2127 : 25 : return 0;
2128 : : }
2129 : :
2130 : :
2131 : : static int
2132 : 25 : init_importlib_external(PyInterpreterState *interp)
2133 : : {
2134 : : PyObject *value;
2135 : 25 : value = PyObject_CallMethod(IMPORTLIB(interp),
2136 : : "_install_external_importers", "");
2137 [ - + ]: 25 : if (value == NULL) {
2138 : 0 : return -1;
2139 : : }
2140 : 25 : Py_DECREF(value);
2141 : 25 : return 0;
2142 : : }
2143 : :
2144 : : PyObject *
2145 : 25 : _PyImport_GetImportlibLoader(PyInterpreterState *interp,
2146 : : const char *loader_name)
2147 : : {
2148 : 25 : return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
2149 : : }
2150 : :
2151 : : PyObject *
2152 : 22 : _PyImport_GetImportlibExternalLoader(PyInterpreterState *interp,
2153 : : const char *loader_name)
2154 : : {
2155 : 22 : PyObject *bootstrap = PyObject_GetAttrString(IMPORTLIB(interp),
2156 : : "_bootstrap_external");
2157 [ - + ]: 22 : if (bootstrap == NULL) {
2158 : 0 : return NULL;
2159 : : }
2160 : :
2161 : 22 : PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
2162 : 22 : Py_DECREF(bootstrap);
2163 : 22 : return loader_type;
2164 : : }
2165 : :
2166 : : PyObject *
2167 : 0 : _PyImport_BlessMyLoader(PyInterpreterState *interp, PyObject *module_globals)
2168 : : {
2169 : 0 : PyObject *external = PyObject_GetAttrString(IMPORTLIB(interp),
2170 : : "_bootstrap_external");
2171 [ # # ]: 0 : if (external == NULL) {
2172 : 0 : return NULL;
2173 : : }
2174 : :
2175 : 0 : PyObject *loader = PyObject_CallMethod(external, "_bless_my_loader",
2176 : : "O", module_globals, NULL);
2177 : 0 : Py_DECREF(external);
2178 : 0 : return loader;
2179 : : }
2180 : :
2181 : : PyObject *
2182 : 0 : _PyImport_ImportlibModuleRepr(PyInterpreterState *interp, PyObject *m)
2183 : : {
2184 : 0 : return PyObject_CallMethod(IMPORTLIB(interp), "_module_repr", "O", m);
2185 : : }
2186 : :
2187 : :
2188 : : /*******************/
2189 : :
2190 : : /* Return a finder object for a sys.path/pkg.__path__ item 'p',
2191 : : possibly by fetching it from the path_importer_cache dict. If it
2192 : : wasn't yet cached, traverse path_hooks until a hook is found
2193 : : that can handle the path item. Return None if no hook could;
2194 : : this tells our caller that the path based finder could not find
2195 : : a finder for this path item. Cache the result in
2196 : : path_importer_cache. */
2197 : :
2198 : : static PyObject *
2199 : 22 : get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
2200 : : PyObject *path_hooks, PyObject *p)
2201 : : {
2202 : : PyObject *importer;
2203 : : Py_ssize_t j, nhooks;
2204 : :
2205 : : /* These conditions are the caller's responsibility: */
2206 : : assert(PyList_Check(path_hooks));
2207 : : assert(PyDict_Check(path_importer_cache));
2208 : :
2209 : 22 : nhooks = PyList_Size(path_hooks);
2210 [ - + ]: 22 : if (nhooks < 0)
2211 : 0 : return NULL; /* Shouldn't happen */
2212 : :
2213 : 22 : importer = PyDict_GetItemWithError(path_importer_cache, p);
2214 [ + - - + ]: 22 : if (importer != NULL || _PyErr_Occurred(tstate)) {
2215 : 0 : return Py_XNewRef(importer);
2216 : : }
2217 : :
2218 : : /* set path_importer_cache[p] to None to avoid recursion */
2219 [ - + ]: 22 : if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
2220 : 0 : return NULL;
2221 : :
2222 [ + + ]: 66 : for (j = 0; j < nhooks; j++) {
2223 : 44 : PyObject *hook = PyList_GetItem(path_hooks, j);
2224 [ - + ]: 44 : if (hook == NULL)
2225 : 0 : return NULL;
2226 : 44 : importer = PyObject_CallOneArg(hook, p);
2227 [ - + ]: 44 : if (importer != NULL)
2228 : 0 : break;
2229 : :
2230 [ - + ]: 44 : if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
2231 : 0 : return NULL;
2232 : : }
2233 : 44 : _PyErr_Clear(tstate);
2234 : : }
2235 [ + - ]: 22 : if (importer == NULL) {
2236 : 22 : Py_RETURN_NONE;
2237 : : }
2238 [ # # ]: 0 : if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
2239 : 0 : Py_DECREF(importer);
2240 : 0 : return NULL;
2241 : : }
2242 : 0 : return importer;
2243 : : }
2244 : :
2245 : : PyObject *
2246 : 22 : PyImport_GetImporter(PyObject *path)
2247 : : {
2248 : 22 : PyThreadState *tstate = _PyThreadState_GET();
2249 : 22 : PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
2250 : 22 : PyObject *path_hooks = PySys_GetObject("path_hooks");
2251 [ + - - + ]: 22 : if (path_importer_cache == NULL || path_hooks == NULL) {
2252 : 0 : return NULL;
2253 : : }
2254 : 22 : return get_path_importer(tstate, path_importer_cache, path_hooks, path);
2255 : : }
2256 : :
2257 : :
2258 : : /*********************/
2259 : : /* importing modules */
2260 : : /*********************/
2261 : :
2262 : : int
2263 : 29 : _PyImport_InitDefaultImportFunc(PyInterpreterState *interp)
2264 : : {
2265 : : // Get the __import__ function
2266 : 29 : PyObject *import_func = _PyDict_GetItemStringWithError(interp->builtins,
2267 : : "__import__");
2268 [ - + ]: 29 : if (import_func == NULL) {
2269 : 0 : return -1;
2270 : : }
2271 : 29 : IMPORT_FUNC(interp) = Py_NewRef(import_func);
2272 : 29 : return 0;
2273 : : }
2274 : :
2275 : : int
2276 : 3157 : _PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
2277 : : {
2278 : 3157 : return func == IMPORT_FUNC(interp);
2279 : : }
2280 : :
2281 : :
2282 : : /* Import a module, either built-in, frozen, or external, and return
2283 : : its module object WITH INCREMENTED REFERENCE COUNT */
2284 : :
2285 : : PyObject *
2286 : 154 : PyImport_ImportModule(const char *name)
2287 : : {
2288 : : PyObject *pname;
2289 : : PyObject *result;
2290 : :
2291 : 154 : pname = PyUnicode_FromString(name);
2292 [ - + ]: 154 : if (pname == NULL)
2293 : 0 : return NULL;
2294 : 154 : result = PyImport_Import(pname);
2295 : 154 : Py_DECREF(pname);
2296 : 154 : return result;
2297 : : }
2298 : :
2299 : :
2300 : : /* Import a module without blocking
2301 : : *
2302 : : * At first it tries to fetch the module from sys.modules. If the module was
2303 : : * never loaded before it loads it with PyImport_ImportModule() unless another
2304 : : * thread holds the import lock. In the latter case the function raises an
2305 : : * ImportError instead of blocking.
2306 : : *
2307 : : * Returns the module object with incremented ref count.
2308 : : */
2309 : : PyObject *
2310 : 0 : PyImport_ImportModuleNoBlock(const char *name)
2311 : : {
2312 : 0 : return PyImport_ImportModule(name);
2313 : : }
2314 : :
2315 : :
2316 : : /* Remove importlib frames from the traceback,
2317 : : * except in Verbose mode. */
2318 : : static void
2319 : 44 : remove_importlib_frames(PyThreadState *tstate)
2320 : : {
2321 : 44 : const char *importlib_filename = "<frozen importlib._bootstrap>";
2322 : 44 : const char *external_filename = "<frozen importlib._bootstrap_external>";
2323 : 44 : const char *remove_frames = "_call_with_frames_removed";
2324 : 44 : int always_trim = 0;
2325 : 44 : int in_importlib = 0;
2326 : 44 : PyObject **prev_link, **outer_link = NULL;
2327 : 44 : PyObject *base_tb = NULL;
2328 : :
2329 : : /* Synopsis: if it's an ImportError, we trim all importlib chunks
2330 : : from the traceback. We always trim chunks
2331 : : which end with a call to "_call_with_frames_removed". */
2332 : :
2333 : 44 : PyObject *exc = _PyErr_GetRaisedException(tstate);
2334 [ + - - + ]: 44 : if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
2335 : 0 : goto done;
2336 : : }
2337 : :
2338 [ + - ]: 44 : if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
2339 : 44 : always_trim = 1;
2340 : : }
2341 : :
2342 : : assert(PyExceptionInstance_Check(exc));
2343 : 44 : base_tb = PyException_GetTraceback(exc);
2344 : 44 : prev_link = &base_tb;
2345 : 44 : PyObject *tb = base_tb;
2346 [ + + ]: 140 : while (tb != NULL) {
2347 : : assert(PyTraceBack_Check(tb));
2348 : 96 : PyTracebackObject *traceback = (PyTracebackObject *)tb;
2349 : 96 : PyObject *next = (PyObject *) traceback->tb_next;
2350 : 96 : PyFrameObject *frame = traceback->tb_frame;
2351 : 96 : PyCodeObject *code = PyFrame_GetCode(frame);
2352 : : int now_in_importlib;
2353 : :
2354 [ + + + + ]: 100 : now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
2355 : 4 : _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
2356 [ + + + + ]: 96 : if (now_in_importlib && !in_importlib) {
2357 : : /* This is the link to this chunk of importlib tracebacks */
2358 : 44 : outer_link = prev_link;
2359 : : }
2360 : 96 : in_importlib = now_in_importlib;
2361 : :
2362 [ + + - + ]: 96 : if (in_importlib &&
2363 [ # # ]: 0 : (always_trim ||
2364 : 0 : _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
2365 : 94 : Py_XSETREF(*outer_link, Py_XNewRef(next));
2366 : 94 : prev_link = outer_link;
2367 : : }
2368 : : else {
2369 : 2 : prev_link = (PyObject **) &traceback->tb_next;
2370 : : }
2371 : 96 : Py_DECREF(code);
2372 : 96 : tb = next;
2373 : : }
2374 [ + + ]: 44 : if (base_tb == NULL) {
2375 : 42 : base_tb = Py_None;
2376 : 42 : Py_INCREF(Py_None);
2377 : : }
2378 : 44 : PyException_SetTraceback(exc, base_tb);
2379 : 44 : done:
2380 : 44 : Py_XDECREF(base_tb);
2381 : 44 : _PyErr_SetRaisedException(tstate, exc);
2382 : 44 : }
2383 : :
2384 : :
2385 : : static PyObject *
2386 : 244 : resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
2387 : : {
2388 : : PyObject *abs_name;
2389 : 244 : PyObject *package = NULL;
2390 : : PyObject *spec;
2391 : : Py_ssize_t last_dot;
2392 : : PyObject *base;
2393 : : int level_up;
2394 : :
2395 [ - + ]: 244 : if (globals == NULL) {
2396 : 0 : _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
2397 : 0 : goto error;
2398 : : }
2399 [ - + ]: 244 : if (!PyDict_Check(globals)) {
2400 : 0 : _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
2401 : 0 : goto error;
2402 : : }
2403 : 244 : package = PyDict_GetItemWithError(globals, &_Py_ID(__package__));
2404 [ - + ]: 244 : if (package == Py_None) {
2405 : 0 : package = NULL;
2406 : : }
2407 [ - + - - ]: 244 : else if (package == NULL && _PyErr_Occurred(tstate)) {
2408 : 0 : goto error;
2409 : : }
2410 : 244 : spec = PyDict_GetItemWithError(globals, &_Py_ID(__spec__));
2411 [ - + - - ]: 244 : if (spec == NULL && _PyErr_Occurred(tstate)) {
2412 : 0 : goto error;
2413 : : }
2414 : :
2415 [ + - ]: 244 : if (package != NULL) {
2416 : 244 : Py_INCREF(package);
2417 [ - + ]: 244 : if (!PyUnicode_Check(package)) {
2418 : 0 : _PyErr_SetString(tstate, PyExc_TypeError,
2419 : : "package must be a string");
2420 : 0 : goto error;
2421 : : }
2422 [ + - + - ]: 244 : else if (spec != NULL && spec != Py_None) {
2423 : : int equal;
2424 : 244 : PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
2425 [ - + ]: 244 : if (parent == NULL) {
2426 : 0 : goto error;
2427 : : }
2428 : :
2429 : 244 : equal = PyObject_RichCompareBool(package, parent, Py_EQ);
2430 : 244 : Py_DECREF(parent);
2431 [ - + ]: 244 : if (equal < 0) {
2432 : 0 : goto error;
2433 : : }
2434 [ - + ]: 244 : else if (equal == 0) {
2435 [ # # ]: 0 : if (PyErr_WarnEx(PyExc_DeprecationWarning,
2436 : : "__package__ != __spec__.parent", 1) < 0) {
2437 : 0 : goto error;
2438 : : }
2439 : : }
2440 : : }
2441 : : }
2442 [ # # # # ]: 0 : else if (spec != NULL && spec != Py_None) {
2443 : 0 : package = PyObject_GetAttr(spec, &_Py_ID(parent));
2444 [ # # ]: 0 : if (package == NULL) {
2445 : 0 : goto error;
2446 : : }
2447 [ # # ]: 0 : else if (!PyUnicode_Check(package)) {
2448 : 0 : _PyErr_SetString(tstate, PyExc_TypeError,
2449 : : "__spec__.parent must be a string");
2450 : 0 : goto error;
2451 : : }
2452 : : }
2453 : : else {
2454 [ # # ]: 0 : if (PyErr_WarnEx(PyExc_ImportWarning,
2455 : : "can't resolve package from __spec__ or __package__, "
2456 : : "falling back on __name__ and __path__", 1) < 0) {
2457 : 0 : goto error;
2458 : : }
2459 : :
2460 : 0 : package = PyDict_GetItemWithError(globals, &_Py_ID(__name__));
2461 [ # # ]: 0 : if (package == NULL) {
2462 [ # # ]: 0 : if (!_PyErr_Occurred(tstate)) {
2463 : 0 : _PyErr_SetString(tstate, PyExc_KeyError,
2464 : : "'__name__' not in globals");
2465 : : }
2466 : 0 : goto error;
2467 : : }
2468 : :
2469 : 0 : Py_INCREF(package);
2470 [ # # ]: 0 : if (!PyUnicode_Check(package)) {
2471 : 0 : _PyErr_SetString(tstate, PyExc_TypeError,
2472 : : "__name__ must be a string");
2473 : 0 : goto error;
2474 : : }
2475 : :
2476 : 0 : int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
2477 [ # # ]: 0 : if (haspath < 0) {
2478 : 0 : goto error;
2479 : : }
2480 [ # # ]: 0 : if (!haspath) {
2481 : : Py_ssize_t dot;
2482 : :
2483 [ # # ]: 0 : if (PyUnicode_READY(package) < 0) {
2484 : 0 : goto error;
2485 : : }
2486 : :
2487 : 0 : dot = PyUnicode_FindChar(package, '.',
2488 : : 0, PyUnicode_GET_LENGTH(package), -1);
2489 [ # # ]: 0 : if (dot == -2) {
2490 : 0 : goto error;
2491 : : }
2492 [ # # ]: 0 : else if (dot == -1) {
2493 : 0 : goto no_parent_error;
2494 : : }
2495 : 0 : PyObject *substr = PyUnicode_Substring(package, 0, dot);
2496 [ # # ]: 0 : if (substr == NULL) {
2497 : 0 : goto error;
2498 : : }
2499 : 0 : Py_SETREF(package, substr);
2500 : : }
2501 : : }
2502 : :
2503 : 244 : last_dot = PyUnicode_GET_LENGTH(package);
2504 [ - + ]: 244 : if (last_dot == 0) {
2505 : 0 : goto no_parent_error;
2506 : : }
2507 : :
2508 [ - + ]: 244 : for (level_up = 1; level_up < level; level_up += 1) {
2509 : 0 : last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
2510 [ # # ]: 0 : if (last_dot == -2) {
2511 : 0 : goto error;
2512 : : }
2513 [ # # ]: 0 : else if (last_dot == -1) {
2514 : 0 : _PyErr_SetString(tstate, PyExc_ImportError,
2515 : : "attempted relative import beyond top-level "
2516 : : "package");
2517 : 0 : goto error;
2518 : : }
2519 : : }
2520 : :
2521 : 244 : base = PyUnicode_Substring(package, 0, last_dot);
2522 : 244 : Py_DECREF(package);
2523 [ + - + + ]: 244 : if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
2524 : 124 : return base;
2525 : : }
2526 : :
2527 : 120 : abs_name = PyUnicode_FromFormat("%U.%U", base, name);
2528 : 120 : Py_DECREF(base);
2529 : 120 : return abs_name;
2530 : :
2531 : 0 : no_parent_error:
2532 : 0 : _PyErr_SetString(tstate, PyExc_ImportError,
2533 : : "attempted relative import "
2534 : : "with no known parent package");
2535 : :
2536 : 0 : error:
2537 : 0 : Py_XDECREF(package);
2538 : 0 : return NULL;
2539 : : }
2540 : :
2541 : : static PyObject *
2542 : 936 : import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
2543 : : {
2544 : 936 : PyObject *mod = NULL;
2545 : 936 : PyInterpreterState *interp = tstate->interp;
2546 : 936 : int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
2547 : : #define import_level FIND_AND_LOAD(interp).import_level
2548 : : #define accumulated FIND_AND_LOAD(interp).accumulated
2549 : :
2550 : 936 : _PyTime_t t1 = 0, accumulated_copy = accumulated;
2551 : :
2552 : 936 : PyObject *sys_path = PySys_GetObject("path");
2553 : 936 : PyObject *sys_meta_path = PySys_GetObject("meta_path");
2554 : 936 : PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
2555 [ + - + - : 936 : if (_PySys_Audit(tstate, "import", "OOOOO",
+ - - + ]
2556 : : abs_name, Py_None, sys_path ? sys_path : Py_None,
2557 : : sys_meta_path ? sys_meta_path : Py_None,
2558 : : sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
2559 : 0 : return NULL;
2560 : : }
2561 : :
2562 : :
2563 : : /* XOptions is initialized after first some imports.
2564 : : * So we can't have negative cache before completed initialization.
2565 : : * Anyway, importlib._find_and_load is much slower than
2566 : : * _PyDict_GetItemIdWithError().
2567 : : */
2568 [ - + ]: 936 : if (import_time) {
2569 : : #define header FIND_AND_LOAD(interp).header
2570 [ # # ]: 0 : if (header) {
2571 : 0 : fputs("import time: self [us] | cumulative | imported package\n",
2572 : : stderr);
2573 : 0 : header = 0;
2574 : : }
2575 : : #undef header
2576 : :
2577 : 0 : import_level++;
2578 : 0 : t1 = _PyTime_GetPerfCounter();
2579 : 0 : accumulated = 0;
2580 : : }
2581 : :
2582 [ - + ]: 936 : if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
2583 : 0 : PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
2584 : :
2585 : 936 : mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
2586 : : abs_name, IMPORT_FUNC(interp), NULL);
2587 : :
2588 [ - + ]: 936 : if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
2589 : 0 : PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
2590 : : mod != NULL);
2591 : :
2592 [ - + ]: 936 : if (import_time) {
2593 : 0 : _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
2594 : :
2595 : 0 : import_level--;
2596 : 0 : fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
2597 : 0 : (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
2598 : 0 : (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
2599 : 0 : import_level*2, "", PyUnicode_AsUTF8(abs_name));
2600 : :
2601 : 0 : accumulated = accumulated_copy + cum;
2602 : : }
2603 : :
2604 : 936 : return mod;
2605 : : #undef import_level
2606 : : #undef accumulated
2607 : : }
2608 : :
2609 : : PyObject *
2610 : 4494 : PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
2611 : : PyObject *locals, PyObject *fromlist,
2612 : : int level)
2613 : : {
2614 : 4494 : PyThreadState *tstate = _PyThreadState_GET();
2615 : 4494 : PyObject *abs_name = NULL;
2616 : 4494 : PyObject *final_mod = NULL;
2617 : 4494 : PyObject *mod = NULL;
2618 : 4494 : PyObject *package = NULL;
2619 : 4494 : PyInterpreterState *interp = tstate->interp;
2620 : : int has_from;
2621 : :
2622 [ - + ]: 4494 : if (name == NULL) {
2623 : 0 : _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
2624 : 0 : goto error;
2625 : : }
2626 : :
2627 : : /* The below code is importlib.__import__() & _gcd_import(), ported to C
2628 : : for added performance. */
2629 : :
2630 [ - + ]: 4494 : if (!PyUnicode_Check(name)) {
2631 : 0 : _PyErr_SetString(tstate, PyExc_TypeError,
2632 : : "module name must be a string");
2633 : 0 : goto error;
2634 : : }
2635 [ - + ]: 4494 : if (PyUnicode_READY(name) < 0) {
2636 : 0 : goto error;
2637 : : }
2638 [ - + ]: 4494 : if (level < 0) {
2639 : 0 : _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
2640 : 0 : goto error;
2641 : : }
2642 : :
2643 [ + + ]: 4494 : if (level > 0) {
2644 : 244 : abs_name = resolve_name(tstate, name, globals, level);
2645 [ - + ]: 244 : if (abs_name == NULL)
2646 : 0 : goto error;
2647 : : }
2648 : : else { /* level == 0 */
2649 [ - + ]: 4250 : if (PyUnicode_GET_LENGTH(name) == 0) {
2650 : 0 : _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
2651 : 0 : goto error;
2652 : : }
2653 : 4250 : abs_name = Py_NewRef(name);
2654 : : }
2655 : :
2656 : 4494 : mod = import_get_module(tstate, abs_name);
2657 [ + + - + ]: 4494 : if (mod == NULL && _PyErr_Occurred(tstate)) {
2658 : 0 : goto error;
2659 : : }
2660 : :
2661 [ + + + - ]: 4494 : if (mod != NULL && mod != Py_None) {
2662 [ - + ]: 3558 : if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
2663 : 0 : goto error;
2664 : : }
2665 : : }
2666 : : else {
2667 : 936 : Py_XDECREF(mod);
2668 : 936 : mod = import_find_and_load(tstate, abs_name);
2669 [ + + ]: 936 : if (mod == NULL) {
2670 : 44 : goto error;
2671 : : }
2672 : : }
2673 : :
2674 : 4450 : has_from = 0;
2675 [ + + + + ]: 4450 : if (fromlist != NULL && fromlist != Py_None) {
2676 : 2112 : has_from = PyObject_IsTrue(fromlist);
2677 [ - + ]: 2112 : if (has_from < 0)
2678 : 0 : goto error;
2679 : : }
2680 [ + + ]: 4450 : if (!has_from) {
2681 : 3278 : Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2682 [ - + - - ]: 3376 : if (level == 0 || len > 0) {
2683 : : Py_ssize_t dot;
2684 : :
2685 : 3278 : dot = PyUnicode_FindChar(name, '.', 0, len, 1);
2686 [ - + ]: 3278 : if (dot == -2) {
2687 : 0 : goto error;
2688 : : }
2689 : :
2690 [ + + ]: 3278 : if (dot == -1) {
2691 : : /* No dot in module name, simple exit */
2692 : 3180 : final_mod = Py_NewRef(mod);
2693 : 3180 : goto error;
2694 : : }
2695 : :
2696 [ + - ]: 98 : if (level == 0) {
2697 : 98 : PyObject *front = PyUnicode_Substring(name, 0, dot);
2698 [ - + ]: 98 : if (front == NULL) {
2699 : 0 : goto error;
2700 : : }
2701 : :
2702 : 98 : final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
2703 : 98 : Py_DECREF(front);
2704 : : }
2705 : : else {
2706 : 0 : Py_ssize_t cut_off = len - dot;
2707 : 0 : Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
2708 : 0 : PyObject *to_return = PyUnicode_Substring(abs_name, 0,
2709 : : abs_name_len - cut_off);
2710 [ # # ]: 0 : if (to_return == NULL) {
2711 : 0 : goto error;
2712 : : }
2713 : :
2714 : 0 : final_mod = import_get_module(tstate, to_return);
2715 : 0 : Py_DECREF(to_return);
2716 [ # # ]: 0 : if (final_mod == NULL) {
2717 [ # # ]: 0 : if (!_PyErr_Occurred(tstate)) {
2718 : 0 : _PyErr_Format(tstate, PyExc_KeyError,
2719 : : "%R not in sys.modules as expected",
2720 : : to_return);
2721 : : }
2722 : 0 : goto error;
2723 : : }
2724 : : }
2725 : : }
2726 : : else {
2727 : 0 : final_mod = Py_NewRef(mod);
2728 : : }
2729 : : }
2730 : : else {
2731 : : PyObject *path;
2732 [ - + ]: 1172 : if (_PyObject_LookupAttr(mod, &_Py_ID(__path__), &path) < 0) {
2733 : 0 : goto error;
2734 : : }
2735 [ + + ]: 1172 : if (path) {
2736 : 165 : Py_DECREF(path);
2737 : 165 : final_mod = PyObject_CallMethodObjArgs(
2738 : : IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
2739 : : mod, fromlist, IMPORT_FUNC(interp), NULL);
2740 : : }
2741 : : else {
2742 : 1007 : final_mod = Py_NewRef(mod);
2743 : : }
2744 : : }
2745 : :
2746 : 4494 : error:
2747 : 4494 : Py_XDECREF(abs_name);
2748 : 4494 : Py_XDECREF(mod);
2749 : 4494 : Py_XDECREF(package);
2750 [ + + ]: 4494 : if (final_mod == NULL) {
2751 : 44 : remove_importlib_frames(tstate);
2752 : : }
2753 : 4494 : return final_mod;
2754 : : }
2755 : :
2756 : : PyObject *
2757 : 180 : PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
2758 : : PyObject *fromlist, int level)
2759 : : {
2760 : : PyObject *nameobj, *mod;
2761 : 180 : nameobj = PyUnicode_FromString(name);
2762 [ - + ]: 180 : if (nameobj == NULL)
2763 : 0 : return NULL;
2764 : 180 : mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
2765 : : fromlist, level);
2766 : 180 : Py_DECREF(nameobj);
2767 : 180 : return mod;
2768 : : }
2769 : :
2770 : :
2771 : : /* Re-import a module of any kind and return its module object, WITH
2772 : : INCREMENTED REFERENCE COUNT */
2773 : :
2774 : : PyObject *
2775 : 0 : PyImport_ReloadModule(PyObject *m)
2776 : : {
2777 : 0 : PyObject *reloaded_module = NULL;
2778 : 0 : PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
2779 [ # # ]: 0 : if (importlib == NULL) {
2780 [ # # ]: 0 : if (PyErr_Occurred()) {
2781 : 0 : return NULL;
2782 : : }
2783 : :
2784 : 0 : importlib = PyImport_ImportModule("importlib");
2785 [ # # ]: 0 : if (importlib == NULL) {
2786 : 0 : return NULL;
2787 : : }
2788 : : }
2789 : :
2790 : 0 : reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
2791 : 0 : Py_DECREF(importlib);
2792 : 0 : return reloaded_module;
2793 : : }
2794 : :
2795 : :
2796 : : /* Higher-level import emulator which emulates the "import" statement
2797 : : more accurately -- it invokes the __import__() function from the
2798 : : builtins of the current globals. This means that the import is
2799 : : done using whatever import hooks are installed in the current
2800 : : environment.
2801 : : A dummy list ["__doc__"] is passed as the 4th argument so that
2802 : : e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
2803 : : will return <module "gencache"> instead of <module "win32com">. */
2804 : :
2805 : : PyObject *
2806 : 940 : PyImport_Import(PyObject *module_name)
2807 : : {
2808 : 940 : PyThreadState *tstate = _PyThreadState_GET();
2809 : 940 : PyObject *globals = NULL;
2810 : 940 : PyObject *import = NULL;
2811 : 940 : PyObject *builtins = NULL;
2812 : 940 : PyObject *r = NULL;
2813 : :
2814 : 940 : PyObject *from_list = PyList_New(0);
2815 [ - + ]: 940 : if (from_list == NULL) {
2816 : 0 : goto err;
2817 : : }
2818 : :
2819 : : /* Get the builtins from current globals */
2820 : 940 : globals = PyEval_GetGlobals();
2821 [ + + ]: 940 : if (globals != NULL) {
2822 : 760 : Py_INCREF(globals);
2823 : 760 : builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
2824 [ - + ]: 760 : if (builtins == NULL)
2825 : 0 : goto err;
2826 : : }
2827 : : else {
2828 : : /* No globals -- use standard builtins, and fake globals */
2829 : 180 : builtins = PyImport_ImportModuleLevel("builtins",
2830 : : NULL, NULL, NULL, 0);
2831 [ - + ]: 180 : if (builtins == NULL) {
2832 : 0 : goto err;
2833 : : }
2834 : 180 : globals = Py_BuildValue("{OO}", &_Py_ID(__builtins__), builtins);
2835 [ - + ]: 180 : if (globals == NULL)
2836 : 0 : goto err;
2837 : : }
2838 : :
2839 : : /* Get the __import__ function from the builtins */
2840 [ + + ]: 940 : if (PyDict_Check(builtins)) {
2841 : 760 : import = PyObject_GetItem(builtins, &_Py_ID(__import__));
2842 [ - + ]: 760 : if (import == NULL) {
2843 : 0 : _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
2844 : : }
2845 : : }
2846 : : else
2847 : 180 : import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
2848 [ - + ]: 940 : if (import == NULL)
2849 : 0 : goto err;
2850 : :
2851 : : /* Call the __import__ function with the proper argument list
2852 : : Always use absolute import here.
2853 : : Calling for side-effect of import. */
2854 : 940 : r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2855 : : globals, from_list, 0, NULL);
2856 [ - + ]: 940 : if (r == NULL)
2857 : 0 : goto err;
2858 : 940 : Py_DECREF(r);
2859 : :
2860 : 940 : r = import_get_module(tstate, module_name);
2861 [ + - - - ]: 940 : if (r == NULL && !_PyErr_Occurred(tstate)) {
2862 : 0 : _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
2863 : : }
2864 : :
2865 : 940 : err:
2866 : 940 : Py_XDECREF(globals);
2867 : 940 : Py_XDECREF(builtins);
2868 : 940 : Py_XDECREF(import);
2869 : 940 : Py_XDECREF(from_list);
2870 : :
2871 : 940 : return r;
2872 : : }
2873 : :
2874 : :
2875 : : /*********************/
2876 : : /* runtime lifecycle */
2877 : : /*********************/
2878 : :
2879 : : PyStatus
2880 : 29 : _PyImport_Init(void)
2881 : : {
2882 [ - + ]: 29 : if (INITTAB != NULL) {
2883 : 0 : return _PyStatus_ERR("global import state already initialized");
2884 : : }
2885 : :
2886 : 29 : PyStatus status = _PyStatus_OK();
2887 : :
2888 : : /* Force default raw memory allocator to get a known allocator to be able
2889 : : to release the memory in _PyImport_Fini() */
2890 : : PyMemAllocatorEx old_alloc;
2891 : 29 : _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2892 : :
2893 [ + - ]: 29 : if (init_builtin_modules_table() != 0) {
2894 : 0 : status = PyStatus_NoMemory();
2895 : 0 : goto done;
2896 : : }
2897 : :
2898 : 29 : done:
2899 : 29 : PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2900 : 29 : return status;
2901 : : }
2902 : :
2903 : : void
2904 : 25 : _PyImport_Fini(void)
2905 : : {
2906 : : /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
2907 : 25 : _extensions_cache_clear_all();
2908 : :
2909 : : /* Use the same memory allocator as _PyImport_Init(). */
2910 : : PyMemAllocatorEx old_alloc;
2911 : 25 : _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2912 : :
2913 : : /* Free memory allocated by _PyImport_Init() */
2914 : 25 : fini_builtin_modules_table();
2915 : :
2916 : 25 : PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2917 : 25 : }
2918 : :
2919 : : void
2920 : 25 : _PyImport_Fini2(void)
2921 : : {
2922 : : /* Use the same memory allocator than PyImport_ExtendInittab(). */
2923 : : PyMemAllocatorEx old_alloc;
2924 : 25 : _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2925 : :
2926 : : // Reset PyImport_Inittab
2927 : 25 : PyImport_Inittab = _PyImport_Inittab;
2928 : :
2929 : : /* Free memory allocated by PyImport_ExtendInittab() */
2930 : 25 : PyMem_RawFree(inittab_copy);
2931 : 25 : inittab_copy = NULL;
2932 : :
2933 : 25 : PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2934 : 25 : }
2935 : :
2936 : :
2937 : : /*************************/
2938 : : /* interpreter lifecycle */
2939 : : /*************************/
2940 : :
2941 : : PyStatus
2942 : 29 : _PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
2943 : : {
2944 : : // XXX Initialize here: interp->modules and interp->import_func.
2945 : : // XXX Initialize here: sys.modules and sys.meta_path.
2946 : :
2947 [ + + ]: 29 : if (importlib) {
2948 : : /* This call sets up builtin and frozen import support */
2949 [ - + ]: 25 : if (init_importlib(tstate, sysmod) < 0) {
2950 : 0 : return _PyStatus_ERR("failed to initialize importlib");
2951 : : }
2952 : : }
2953 : :
2954 : 29 : return _PyStatus_OK();
2955 : : }
2956 : :
2957 : : /* In some corner cases it is important to be sure that the import
2958 : : machinery has been initialized (or not cleaned up yet). For
2959 : : example, see issue #4236 and PyModule_Create2(). */
2960 : :
2961 : : int
2962 : 46 : _PyImport_IsInitialized(PyInterpreterState *interp)
2963 : : {
2964 [ - + ]: 46 : if (MODULES(interp) == NULL)
2965 : 0 : return 0;
2966 : 46 : return 1;
2967 : : }
2968 : :
2969 : : /* Clear the direct per-interpreter import state, if not cleared already. */
2970 : : void
2971 : 50 : _PyImport_ClearCore(PyInterpreterState *interp)
2972 : : {
2973 : : /* interp->modules should have been cleaned up and cleared already
2974 : : by _PyImport_FiniCore(). */
2975 [ - + ]: 50 : Py_CLEAR(MODULES(interp));
2976 [ + + ]: 50 : Py_CLEAR(MODULES_BY_INDEX(interp));
2977 [ + + ]: 50 : Py_CLEAR(IMPORTLIB(interp));
2978 [ + + ]: 50 : Py_CLEAR(IMPORT_FUNC(interp));
2979 : 50 : }
2980 : :
2981 : : void
2982 : 25 : _PyImport_FiniCore(PyInterpreterState *interp)
2983 : : {
2984 : 25 : int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
2985 : :
2986 [ - + ]: 25 : if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
2987 : 0 : PyErr_WriteUnraisable(NULL);
2988 : : }
2989 : :
2990 : : // XXX Pull in most of finalize_modules() in pylifecycle.c.
2991 : :
2992 [ - + ]: 25 : if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
2993 : 0 : PyErr_WriteUnraisable(NULL);
2994 : : }
2995 : :
2996 [ + - ]: 25 : if (IMPORT_LOCK(interp) != NULL) {
2997 : 25 : PyThread_free_lock(IMPORT_LOCK(interp));
2998 : 25 : IMPORT_LOCK(interp) = NULL;
2999 : : }
3000 : :
3001 : 25 : _PyImport_ClearCore(interp);
3002 : 25 : }
3003 : :
3004 : : // XXX Add something like _PyImport_Disable() for use early in interp fini?
3005 : :
3006 : :
3007 : : /* "external" imports */
3008 : :
3009 : : static int
3010 : 25 : init_zipimport(PyThreadState *tstate, int verbose)
3011 : : {
3012 : 25 : PyObject *path_hooks = PySys_GetObject("path_hooks");
3013 [ - + ]: 25 : if (path_hooks == NULL) {
3014 : 0 : _PyErr_SetString(tstate, PyExc_RuntimeError,
3015 : : "unable to get sys.path_hooks");
3016 : 0 : return -1;
3017 : : }
3018 : :
3019 [ - + ]: 25 : if (verbose) {
3020 : 0 : PySys_WriteStderr("# installing zipimport hook\n");
3021 : : }
3022 : :
3023 : 25 : PyObject *zipimporter = _PyImport_GetModuleAttrString("zipimport", "zipimporter");
3024 [ - + ]: 25 : if (zipimporter == NULL) {
3025 : 0 : _PyErr_Clear(tstate); /* No zipimporter object -- okay */
3026 [ # # ]: 0 : if (verbose) {
3027 : 0 : PySys_WriteStderr("# can't import zipimport.zipimporter\n");
3028 : : }
3029 : : }
3030 : : else {
3031 : : /* sys.path_hooks.insert(0, zipimporter) */
3032 : 25 : int err = PyList_Insert(path_hooks, 0, zipimporter);
3033 : 25 : Py_DECREF(zipimporter);
3034 [ - + ]: 25 : if (err < 0) {
3035 : 0 : return -1;
3036 : : }
3037 [ - + ]: 25 : if (verbose) {
3038 : 0 : PySys_WriteStderr("# installed zipimport hook\n");
3039 : : }
3040 : : }
3041 : :
3042 : 25 : return 0;
3043 : : }
3044 : :
3045 : : PyStatus
3046 : 25 : _PyImport_InitExternal(PyThreadState *tstate)
3047 : : {
3048 : 25 : int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
3049 : :
3050 : : // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
3051 : :
3052 [ - + ]: 25 : if (init_importlib_external(tstate->interp) != 0) {
3053 : 0 : _PyErr_Print(tstate);
3054 : 0 : return _PyStatus_ERR("external importer setup failed");
3055 : : }
3056 : :
3057 [ - + ]: 25 : if (init_zipimport(tstate, verbose) != 0) {
3058 : 0 : PyErr_Print();
3059 : 0 : return _PyStatus_ERR("initializing zipimport failed");
3060 : : }
3061 : :
3062 : 25 : return _PyStatus_OK();
3063 : : }
3064 : :
3065 : : void
3066 : 25 : _PyImport_FiniExternal(PyInterpreterState *interp)
3067 : : {
3068 : 25 : int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3069 : :
3070 : : // XXX Uninstall importlib metapath importers here?
3071 : :
3072 [ - + ]: 25 : if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
3073 : 0 : PyErr_WriteUnraisable(NULL);
3074 : : }
3075 [ - + ]: 25 : if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
3076 : 0 : PyErr_WriteUnraisable(NULL);
3077 : : }
3078 : 25 : }
3079 : :
3080 : :
3081 : : /******************/
3082 : : /* module helpers */
3083 : : /******************/
3084 : :
3085 : : PyObject *
3086 : 786 : _PyImport_GetModuleAttr(PyObject *modname, PyObject *attrname)
3087 : : {
3088 : 786 : PyObject *mod = PyImport_Import(modname);
3089 [ - + ]: 786 : if (mod == NULL) {
3090 : 0 : return NULL;
3091 : : }
3092 : 786 : PyObject *result = PyObject_GetAttr(mod, attrname);
3093 : 786 : Py_DECREF(mod);
3094 : 786 : return result;
3095 : : }
3096 : :
3097 : : PyObject *
3098 : 786 : _PyImport_GetModuleAttrString(const char *modname, const char *attrname)
3099 : : {
3100 : 786 : PyObject *pmodname = PyUnicode_FromString(modname);
3101 [ - + ]: 786 : if (pmodname == NULL) {
3102 : 0 : return NULL;
3103 : : }
3104 : 786 : PyObject *pattrname = PyUnicode_FromString(attrname);
3105 [ - + ]: 786 : if (pattrname == NULL) {
3106 : 0 : Py_DECREF(pmodname);
3107 : 0 : return NULL;
3108 : : }
3109 : 786 : PyObject *result = _PyImport_GetModuleAttr(pmodname, pattrname);
3110 : 786 : Py_DECREF(pattrname);
3111 : 786 : Py_DECREF(pmodname);
3112 : 786 : return result;
3113 : : }
3114 : :
3115 : :
3116 : : /**************/
3117 : : /* the module */
3118 : : /**************/
3119 : :
3120 : : /*[clinic input]
3121 : : _imp.lock_held
3122 : :
3123 : : Return True if the import lock is currently held, else False.
3124 : :
3125 : : On platforms without threads, return False.
3126 : : [clinic start generated code]*/
3127 : :
3128 : : static PyObject *
3129 : 0 : _imp_lock_held_impl(PyObject *module)
3130 : : /*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
3131 : : {
3132 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
3133 : 0 : return PyBool_FromLong(
3134 : 0 : IMPORT_LOCK_THREAD(interp) != PYTHREAD_INVALID_THREAD_ID);
3135 : : }
3136 : :
3137 : : /*[clinic input]
3138 : : _imp.acquire_lock
3139 : :
3140 : : Acquires the interpreter's import lock for the current thread.
3141 : :
3142 : : This lock should be used by import hooks to ensure thread-safety when importing
3143 : : modules. On platforms without threads, this function does nothing.
3144 : : [clinic start generated code]*/
3145 : :
3146 : : static PyObject *
3147 : 4609 : _imp_acquire_lock_impl(PyObject *module)
3148 : : /*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
3149 : : {
3150 : 4609 : PyInterpreterState *interp = _PyInterpreterState_GET();
3151 : 4609 : _PyImport_AcquireLock(interp);
3152 : 4609 : Py_RETURN_NONE;
3153 : : }
3154 : :
3155 : : /*[clinic input]
3156 : : _imp.release_lock
3157 : :
3158 : : Release the interpreter's import lock.
3159 : :
3160 : : On platforms without threads, this function does nothing.
3161 : : [clinic start generated code]*/
3162 : :
3163 : : static PyObject *
3164 : 4609 : _imp_release_lock_impl(PyObject *module)
3165 : : /*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
3166 : : {
3167 : 4609 : PyInterpreterState *interp = _PyInterpreterState_GET();
3168 [ - + ]: 4609 : if (_PyImport_ReleaseLock(interp) < 0) {
3169 : 0 : PyErr_SetString(PyExc_RuntimeError,
3170 : : "not holding the import lock");
3171 : 0 : return NULL;
3172 : : }
3173 : 4609 : Py_RETURN_NONE;
3174 : : }
3175 : :
3176 : :
3177 : : /*[clinic input]
3178 : : _imp._fix_co_filename
3179 : :
3180 : : code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
3181 : : Code object to change.
3182 : :
3183 : : path: unicode
3184 : : File path to use.
3185 : : /
3186 : :
3187 : : Changes code.co_filename to specify the passed-in file path.
3188 : : [clinic start generated code]*/
3189 : :
3190 : : static PyObject *
3191 : 386 : _imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
3192 : : PyObject *path)
3193 : : /*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
3194 : :
3195 : : {
3196 : 386 : update_compiled_module(code, path);
3197 : :
3198 : 386 : Py_RETURN_NONE;
3199 : : }
3200 : :
3201 : :
3202 : : /*[clinic input]
3203 : : _imp.create_builtin
3204 : :
3205 : : spec: object
3206 : : /
3207 : :
3208 : : Create an extension module.
3209 : : [clinic start generated code]*/
3210 : :
3211 : : static PyObject *
3212 : 323 : _imp_create_builtin(PyObject *module, PyObject *spec)
3213 : : /*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
3214 : : {
3215 : 323 : PyThreadState *tstate = _PyThreadState_GET();
3216 : :
3217 : 323 : PyObject *name = PyObject_GetAttrString(spec, "name");
3218 [ - + ]: 323 : if (name == NULL) {
3219 : 0 : return NULL;
3220 : : }
3221 : :
3222 [ - + ]: 323 : if (!PyUnicode_Check(name)) {
3223 : 0 : PyErr_Format(PyExc_TypeError,
3224 : : "name must be string, not %.200s",
3225 : 0 : Py_TYPE(name)->tp_name);
3226 : 0 : Py_DECREF(name);
3227 : 0 : return NULL;
3228 : : }
3229 : :
3230 : 323 : PyObject *mod = create_builtin(tstate, name, spec);
3231 : 323 : Py_DECREF(name);
3232 : 323 : return mod;
3233 : : }
3234 : :
3235 : :
3236 : : /*[clinic input]
3237 : : _imp.extension_suffixes
3238 : :
3239 : : Returns the list of file suffixes used to identify extension modules.
3240 : : [clinic start generated code]*/
3241 : :
3242 : : static PyObject *
3243 : 50 : _imp_extension_suffixes_impl(PyObject *module)
3244 : : /*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
3245 : : {
3246 : : PyObject *list;
3247 : :
3248 : 50 : list = PyList_New(0);
3249 [ - + ]: 50 : if (list == NULL)
3250 : 0 : return NULL;
3251 : : #ifdef HAVE_DYNAMIC_LOADING
3252 : : const char *suffix;
3253 : 50 : unsigned int index = 0;
3254 : :
3255 [ + + ]: 200 : while ((suffix = _PyImport_DynLoadFiletab[index])) {
3256 : 150 : PyObject *item = PyUnicode_FromString(suffix);
3257 [ - + ]: 150 : if (item == NULL) {
3258 : 0 : Py_DECREF(list);
3259 : 0 : return NULL;
3260 : : }
3261 [ - + ]: 150 : if (PyList_Append(list, item) < 0) {
3262 : 0 : Py_DECREF(list);
3263 : 0 : Py_DECREF(item);
3264 : 0 : return NULL;
3265 : : }
3266 : 150 : Py_DECREF(item);
3267 : 150 : index += 1;
3268 : : }
3269 : : #endif
3270 : 50 : return list;
3271 : : }
3272 : :
3273 : : /*[clinic input]
3274 : : _imp.init_frozen
3275 : :
3276 : : name: unicode
3277 : : /
3278 : :
3279 : : Initializes a frozen module.
3280 : : [clinic start generated code]*/
3281 : :
3282 : : static PyObject *
3283 : 0 : _imp_init_frozen_impl(PyObject *module, PyObject *name)
3284 : : /*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
3285 : : {
3286 : 0 : PyThreadState *tstate = _PyThreadState_GET();
3287 : : int ret;
3288 : :
3289 : 0 : ret = PyImport_ImportFrozenModuleObject(name);
3290 [ # # ]: 0 : if (ret < 0)
3291 : 0 : return NULL;
3292 [ # # ]: 0 : if (ret == 0) {
3293 : 0 : Py_RETURN_NONE;
3294 : : }
3295 : 0 : return import_add_module(tstate, name);
3296 : : }
3297 : :
3298 : : /*[clinic input]
3299 : : _imp.find_frozen
3300 : :
3301 : : name: unicode
3302 : : /
3303 : : *
3304 : : withdata: bool = False
3305 : :
3306 : : Return info about the corresponding frozen module (if there is one) or None.
3307 : :
3308 : : The returned info (a 2-tuple):
3309 : :
3310 : : * data the raw marshalled bytes
3311 : : * is_package whether or not it is a package
3312 : : * origname the originally frozen module's name, or None if not
3313 : : a stdlib module (this will usually be the same as
3314 : : the module's current name)
3315 : : [clinic start generated code]*/
3316 : :
3317 : : static PyObject *
3318 : 720 : _imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
3319 : : /*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
3320 : : {
3321 : : struct frozen_info info;
3322 : 720 : frozen_status status = find_frozen(name, &info);
3323 [ + + - + ]: 720 : if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3324 : 623 : Py_RETURN_NONE;
3325 : : }
3326 [ - + ]: 97 : else if (status == FROZEN_BAD_NAME) {
3327 : 0 : Py_RETURN_NONE;
3328 : : }
3329 [ - + ]: 97 : else if (status != FROZEN_OKAY) {
3330 : 0 : set_frozen_error(status, name);
3331 : 0 : return NULL;
3332 : : }
3333 : :
3334 : 97 : PyObject *data = NULL;
3335 [ - + ]: 97 : if (withdata) {
3336 : 0 : data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
3337 [ # # ]: 0 : if (data == NULL) {
3338 : 0 : return NULL;
3339 : : }
3340 : : }
3341 : :
3342 : 97 : PyObject *origname = NULL;
3343 [ + - + - ]: 97 : if (info.origname != NULL && info.origname[0] != '\0') {
3344 : 97 : origname = PyUnicode_FromString(info.origname);
3345 [ - + ]: 97 : if (origname == NULL) {
3346 : 0 : Py_DECREF(data);
3347 : 0 : return NULL;
3348 : : }
3349 : : }
3350 : :
3351 [ + - - + ]: 194 : PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
3352 [ - + ]: 97 : info.is_package ? Py_True : Py_False,
3353 : : origname ? origname : Py_None);
3354 : 97 : Py_XDECREF(origname);
3355 : 97 : Py_XDECREF(data);
3356 : 97 : return result;
3357 : : }
3358 : :
3359 : : /*[clinic input]
3360 : : _imp.get_frozen_object
3361 : :
3362 : : name: unicode
3363 : : data as dataobj: object = None
3364 : : /
3365 : :
3366 : : Create a code object for a frozen module.
3367 : : [clinic start generated code]*/
3368 : :
3369 : : static PyObject *
3370 : 97 : _imp_get_frozen_object_impl(PyObject *module, PyObject *name,
3371 : : PyObject *dataobj)
3372 : : /*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
3373 : : {
3374 : 97 : struct frozen_info info = {0};
3375 : 97 : Py_buffer buf = {0};
3376 [ - + ]: 97 : if (PyObject_CheckBuffer(dataobj)) {
3377 [ # # ]: 0 : if (PyObject_GetBuffer(dataobj, &buf, PyBUF_READ) != 0) {
3378 : 0 : return NULL;
3379 : : }
3380 : 0 : info.data = (const char *)buf.buf;
3381 : 0 : info.size = buf.len;
3382 : : }
3383 [ - + ]: 97 : else if (dataobj != Py_None) {
3384 : 0 : _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
3385 : 0 : return NULL;
3386 : : }
3387 : : else {
3388 : 97 : frozen_status status = find_frozen(name, &info);
3389 [ - + ]: 97 : if (status != FROZEN_OKAY) {
3390 : 0 : set_frozen_error(status, name);
3391 : 0 : return NULL;
3392 : : }
3393 : : }
3394 : :
3395 [ - + ]: 97 : if (info.nameobj == NULL) {
3396 : 0 : info.nameobj = name;
3397 : : }
3398 [ + + - + ]: 97 : if (info.size == 0 && info.get_code == NULL) {
3399 : : /* Does not contain executable code. */
3400 : 0 : set_frozen_error(FROZEN_INVALID, name);
3401 : 0 : return NULL;
3402 : : }
3403 : :
3404 : 97 : PyObject *codeobj = unmarshal_frozen_code(&info);
3405 [ - + ]: 97 : if (dataobj != Py_None) {
3406 : 0 : PyBuffer_Release(&buf);
3407 : : }
3408 : 97 : return codeobj;
3409 : : }
3410 : :
3411 : : /*[clinic input]
3412 : : _imp.is_frozen_package
3413 : :
3414 : : name: unicode
3415 : : /
3416 : :
3417 : : Returns True if the module name is of a frozen package.
3418 : : [clinic start generated code]*/
3419 : :
3420 : : static PyObject *
3421 : 25 : _imp_is_frozen_package_impl(PyObject *module, PyObject *name)
3422 : : /*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
3423 : : {
3424 : : struct frozen_info info;
3425 : 25 : frozen_status status = find_frozen(name, &info);
3426 [ - + - - ]: 25 : if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
3427 : 0 : set_frozen_error(status, name);
3428 : 0 : return NULL;
3429 : : }
3430 : 25 : return PyBool_FromLong(info.is_package);
3431 : : }
3432 : :
3433 : : /*[clinic input]
3434 : : _imp.is_builtin
3435 : :
3436 : : name: unicode
3437 : : /
3438 : :
3439 : : Returns True if the module name corresponds to a built-in module.
3440 : : [clinic start generated code]*/
3441 : :
3442 : : static PyObject *
3443 : 875 : _imp_is_builtin_impl(PyObject *module, PyObject *name)
3444 : : /*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
3445 : : {
3446 : 875 : return PyLong_FromLong(is_builtin(name));
3447 : : }
3448 : :
3449 : : /*[clinic input]
3450 : : _imp.is_frozen
3451 : :
3452 : : name: unicode
3453 : : /
3454 : :
3455 : : Returns True if the module name corresponds to a frozen module.
3456 : : [clinic start generated code]*/
3457 : :
3458 : : static PyObject *
3459 : 25 : _imp_is_frozen_impl(PyObject *module, PyObject *name)
3460 : : /*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
3461 : : {
3462 : : struct frozen_info info;
3463 : 25 : frozen_status status = find_frozen(name, &info);
3464 [ - + ]: 25 : if (status != FROZEN_OKAY) {
3465 : 0 : Py_RETURN_FALSE;
3466 : : }
3467 : 25 : Py_RETURN_TRUE;
3468 : : }
3469 : :
3470 : : /*[clinic input]
3471 : : _imp._frozen_module_names
3472 : :
3473 : : Returns the list of available frozen modules.
3474 : : [clinic start generated code]*/
3475 : :
3476 : : static PyObject *
3477 : 0 : _imp__frozen_module_names_impl(PyObject *module)
3478 : : /*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
3479 : : {
3480 : 0 : return list_frozen_module_names();
3481 : : }
3482 : :
3483 : : /*[clinic input]
3484 : : _imp._override_frozen_modules_for_tests
3485 : :
3486 : : override: int
3487 : : /
3488 : :
3489 : : (internal-only) Override PyConfig.use_frozen_modules.
3490 : :
3491 : : (-1: "off", 1: "on", 0: no override)
3492 : : See frozen_modules() in Lib/test/support/import_helper.py.
3493 : : [clinic start generated code]*/
3494 : :
3495 : : static PyObject *
3496 : 0 : _imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
3497 : : /*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
3498 : : {
3499 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
3500 : 0 : OVERRIDE_FROZEN_MODULES(interp) = override;
3501 : 0 : Py_RETURN_NONE;
3502 : : }
3503 : :
3504 : : /*[clinic input]
3505 : : _imp._override_multi_interp_extensions_check
3506 : :
3507 : : override: int
3508 : : /
3509 : :
3510 : : (internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
3511 : :
3512 : : (-1: "never", 1: "always", 0: no override)
3513 : : [clinic start generated code]*/
3514 : :
3515 : : static PyObject *
3516 : 0 : _imp__override_multi_interp_extensions_check_impl(PyObject *module,
3517 : : int override)
3518 : : /*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
3519 : : {
3520 : 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
3521 [ # # ]: 0 : if (_Py_IsMainInterpreter(interp)) {
3522 : 0 : PyErr_SetString(PyExc_RuntimeError,
3523 : : "_imp._override_multi_interp_extensions_check() "
3524 : : "cannot be used in the main interpreter");
3525 : 0 : return NULL;
3526 : : }
3527 : 0 : int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
3528 : 0 : OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
3529 : 0 : return PyLong_FromLong(oldvalue);
3530 : : }
3531 : :
3532 : : #ifdef HAVE_DYNAMIC_LOADING
3533 : :
3534 : : /*[clinic input]
3535 : : _imp.create_dynamic
3536 : :
3537 : : spec: object
3538 : : file: object = NULL
3539 : : /
3540 : :
3541 : : Create an extension module.
3542 : : [clinic start generated code]*/
3543 : :
3544 : : static PyObject *
3545 : 115 : _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
3546 : : /*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
3547 : : {
3548 : : PyObject *mod, *name, *path;
3549 : : FILE *fp;
3550 : :
3551 : 115 : name = PyObject_GetAttrString(spec, "name");
3552 [ - + ]: 115 : if (name == NULL) {
3553 : 0 : return NULL;
3554 : : }
3555 : :
3556 : 115 : path = PyObject_GetAttrString(spec, "origin");
3557 [ - + ]: 115 : if (path == NULL) {
3558 : 0 : Py_DECREF(name);
3559 : 0 : return NULL;
3560 : : }
3561 : :
3562 : 115 : PyThreadState *tstate = _PyThreadState_GET();
3563 : 115 : mod = import_find_extension(tstate, name, path);
3564 [ + + ]: 115 : if (mod != NULL) {
3565 : 1 : const char *name_buf = PyUnicode_AsUTF8(name);
3566 : : assert(name_buf != NULL);
3567 [ - + ]: 1 : if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
3568 : 0 : Py_DECREF(mod);
3569 : 0 : mod = NULL;
3570 : : }
3571 : 1 : goto finally;
3572 : : }
3573 [ - + ]: 114 : else if (PyErr_Occurred()) {
3574 : 0 : goto finally;
3575 : : }
3576 : :
3577 [ - + ]: 114 : if (file != NULL) {
3578 : 0 : fp = _Py_fopen_obj(path, "r");
3579 [ # # ]: 0 : if (fp == NULL) {
3580 : 0 : goto finally;
3581 : : }
3582 : : }
3583 : : else
3584 : 114 : fp = NULL;
3585 : :
3586 : 114 : mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
3587 : :
3588 [ + - ]: 114 : if (fp)
3589 : 0 : fclose(fp);
3590 : :
3591 : 114 : finally:
3592 : 115 : Py_DECREF(name);
3593 : 115 : Py_DECREF(path);
3594 : 115 : return mod;
3595 : : }
3596 : :
3597 : : /*[clinic input]
3598 : : _imp.exec_dynamic -> int
3599 : :
3600 : : mod: object
3601 : : /
3602 : :
3603 : : Initialize an extension module.
3604 : : [clinic start generated code]*/
3605 : :
3606 : : static int
3607 : 115 : _imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
3608 : : /*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
3609 : : {
3610 : 115 : return exec_builtin_or_dynamic(mod);
3611 : : }
3612 : :
3613 : :
3614 : : #endif /* HAVE_DYNAMIC_LOADING */
3615 : :
3616 : : /*[clinic input]
3617 : : _imp.exec_builtin -> int
3618 : :
3619 : : mod: object
3620 : : /
3621 : :
3622 : : Initialize a built-in module.
3623 : : [clinic start generated code]*/
3624 : :
3625 : : static int
3626 : 323 : _imp_exec_builtin_impl(PyObject *module, PyObject *mod)
3627 : : /*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
3628 : : {
3629 : 323 : return exec_builtin_or_dynamic(mod);
3630 : : }
3631 : :
3632 : : /*[clinic input]
3633 : : _imp.source_hash
3634 : :
3635 : : key: long
3636 : : source: Py_buffer
3637 : : [clinic start generated code]*/
3638 : :
3639 : : static PyObject *
3640 : 0 : _imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
3641 : : /*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
3642 : : {
3643 : : union {
3644 : : uint64_t x;
3645 : : char data[sizeof(uint64_t)];
3646 : : } hash;
3647 : 0 : hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
3648 : : #if !PY_LITTLE_ENDIAN
3649 : : // Force to little-endian. There really ought to be a succinct standard way
3650 : : // to do this.
3651 : : for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
3652 : : char tmp = hash.data[i];
3653 : : hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
3654 : : hash.data[sizeof(hash.data) - i - 1] = tmp;
3655 : : }
3656 : : #endif
3657 : 0 : return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
3658 : : }
3659 : :
3660 : :
3661 : : PyDoc_STRVAR(doc_imp,
3662 : : "(Extremely) low-level import machinery bits as used by importlib and imp.");
3663 : :
3664 : : static PyMethodDef imp_methods[] = {
3665 : : _IMP_EXTENSION_SUFFIXES_METHODDEF
3666 : : _IMP_LOCK_HELD_METHODDEF
3667 : : _IMP_ACQUIRE_LOCK_METHODDEF
3668 : : _IMP_RELEASE_LOCK_METHODDEF
3669 : : _IMP_FIND_FROZEN_METHODDEF
3670 : : _IMP_GET_FROZEN_OBJECT_METHODDEF
3671 : : _IMP_IS_FROZEN_PACKAGE_METHODDEF
3672 : : _IMP_CREATE_BUILTIN_METHODDEF
3673 : : _IMP_INIT_FROZEN_METHODDEF
3674 : : _IMP_IS_BUILTIN_METHODDEF
3675 : : _IMP_IS_FROZEN_METHODDEF
3676 : : _IMP__FROZEN_MODULE_NAMES_METHODDEF
3677 : : _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
3678 : : _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
3679 : : _IMP_CREATE_DYNAMIC_METHODDEF
3680 : : _IMP_EXEC_DYNAMIC_METHODDEF
3681 : : _IMP_EXEC_BUILTIN_METHODDEF
3682 : : _IMP__FIX_CO_FILENAME_METHODDEF
3683 : : _IMP_SOURCE_HASH_METHODDEF
3684 : : {NULL, NULL} /* sentinel */
3685 : : };
3686 : :
3687 : :
3688 : : static int
3689 : 26 : imp_module_exec(PyObject *module)
3690 : : {
3691 : 26 : const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
3692 : 26 : PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
3693 [ - + ]: 26 : if (pyc_mode == NULL) {
3694 : 0 : return -1;
3695 : : }
3696 [ - + ]: 26 : if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
3697 : 0 : Py_DECREF(pyc_mode);
3698 : 0 : return -1;
3699 : : }
3700 : 26 : Py_DECREF(pyc_mode);
3701 : :
3702 : 26 : return 0;
3703 : : }
3704 : :
3705 : :
3706 : : static PyModuleDef_Slot imp_slots[] = {
3707 : : {Py_mod_exec, imp_module_exec},
3708 : : {0, NULL}
3709 : : };
3710 : :
3711 : : static struct PyModuleDef imp_module = {
3712 : : PyModuleDef_HEAD_INIT,
3713 : : .m_name = "_imp",
3714 : : .m_doc = doc_imp,
3715 : : .m_size = 0,
3716 : : .m_methods = imp_methods,
3717 : : .m_slots = imp_slots,
3718 : : };
3719 : :
3720 : : PyMODINIT_FUNC
3721 : 26 : PyInit__imp(void)
3722 : : {
3723 : 26 : return PyModuleDef_Init(&imp_module);
3724 : : }
3725 : :
3726 : :
3727 : : #ifdef __cplusplus
3728 : : }
3729 : : #endif
|