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" // _PyInterpreterState_ClearModules()
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 : /* Forward references */
28 : static PyObject *import_add_module(PyThreadState *tstate, PyObject *name);
29 :
30 : /* See _PyImport_FixupExtensionObject() below */
31 : static PyObject *extensions = NULL;
32 :
33 : /* This table is defined in config.c: */
34 : extern struct _inittab _PyImport_Inittab[];
35 :
36 : struct _inittab *PyImport_Inittab = _PyImport_Inittab;
37 : static struct _inittab *inittab_copy = NULL;
38 :
39 : /*[clinic input]
40 : module _imp
41 : [clinic start generated code]*/
42 : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
43 :
44 : #include "clinic/import.c.h"
45 :
46 : /* Initialize things */
47 :
48 : PyStatus
49 3130 : _PyImportZip_Init(PyThreadState *tstate)
50 : {
51 : PyObject *path_hooks;
52 3130 : int err = 0;
53 :
54 3130 : path_hooks = PySys_GetObject("path_hooks");
55 3130 : if (path_hooks == NULL) {
56 0 : _PyErr_SetString(tstate, PyExc_RuntimeError,
57 : "unable to get sys.path_hooks");
58 0 : goto error;
59 : }
60 :
61 3130 : int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
62 3130 : if (verbose) {
63 12 : PySys_WriteStderr("# installing zipimport hook\n");
64 : }
65 :
66 3130 : PyObject *zipimporter = _PyImport_GetModuleAttrString("zipimport", "zipimporter");
67 3130 : if (zipimporter == NULL) {
68 0 : _PyErr_Clear(tstate); /* No zipimporter object -- okay */
69 0 : if (verbose) {
70 0 : PySys_WriteStderr("# can't import zipimport.zipimporter\n");
71 : }
72 : }
73 : else {
74 : /* sys.path_hooks.insert(0, zipimporter) */
75 3130 : err = PyList_Insert(path_hooks, 0, zipimporter);
76 3130 : Py_DECREF(zipimporter);
77 3130 : if (err < 0) {
78 0 : goto error;
79 : }
80 3130 : if (verbose) {
81 12 : PySys_WriteStderr("# installed zipimport hook\n");
82 : }
83 : }
84 :
85 3130 : return _PyStatus_OK();
86 :
87 0 : error:
88 0 : PyErr_Print();
89 0 : return _PyStatus_ERR("initializing zipimport failed");
90 : }
91 :
92 : /* Locking primitives to prevent parallel imports of the same module
93 : in different threads to return with a partially loaded module.
94 : These calls are serialized by the global interpreter lock. */
95 :
96 : static PyThread_type_lock import_lock = NULL;
97 : static unsigned long import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
98 : static int import_lock_level = 0;
99 :
100 : void
101 1500040 : _PyImport_AcquireLock(void)
102 : {
103 1500040 : unsigned long me = PyThread_get_thread_ident();
104 1500040 : if (me == PYTHREAD_INVALID_THREAD_ID)
105 0 : return; /* Too bad */
106 1500040 : if (import_lock == NULL) {
107 2959 : import_lock = PyThread_allocate_lock();
108 2959 : if (import_lock == NULL)
109 0 : return; /* Nothing much we can do. */
110 : }
111 1500040 : if (import_lock_thread == me) {
112 1483 : import_lock_level++;
113 1483 : return;
114 : }
115 2997050 : if (import_lock_thread != PYTHREAD_INVALID_THREAD_ID ||
116 1498480 : !PyThread_acquire_lock(import_lock, 0))
117 : {
118 162 : PyThreadState *tstate = PyEval_SaveThread();
119 162 : PyThread_acquire_lock(import_lock, WAIT_LOCK);
120 162 : PyEval_RestoreThread(tstate);
121 : }
122 1498560 : assert(import_lock_level == 0);
123 1498560 : import_lock_thread = me;
124 1498560 : import_lock_level = 1;
125 : }
126 :
127 : int
128 1500040 : _PyImport_ReleaseLock(void)
129 : {
130 1500040 : unsigned long me = PyThread_get_thread_ident();
131 1500040 : if (me == PYTHREAD_INVALID_THREAD_ID || import_lock == NULL)
132 0 : return 0; /* Too bad */
133 1500040 : if (import_lock_thread != me)
134 1 : return -1;
135 1500040 : import_lock_level--;
136 1500040 : assert(import_lock_level >= 0);
137 1500040 : if (import_lock_level == 0) {
138 1498550 : import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
139 1498550 : PyThread_release_lock(import_lock);
140 : }
141 1500040 : return 1;
142 : }
143 :
144 : #ifdef HAVE_FORK
145 : /* This function is called from PyOS_AfterFork_Child() to ensure that newly
146 : created child processes do not share locks with the parent.
147 : We now acquire the import lock around fork() calls but on some platforms
148 : (Solaris 9 and earlier? see isue7242) that still left us with problems. */
149 : PyStatus
150 8 : _PyImport_ReInitLock(void)
151 : {
152 8 : if (import_lock != NULL) {
153 8 : if (_PyThread_at_fork_reinit(&import_lock) < 0) {
154 0 : return _PyStatus_ERR("failed to create a new lock");
155 : }
156 : }
157 :
158 8 : if (import_lock_level > 1) {
159 : /* Forked as a side effect of import */
160 0 : unsigned long me = PyThread_get_thread_ident();
161 0 : PyThread_acquire_lock(import_lock, WAIT_LOCK);
162 0 : import_lock_thread = me;
163 0 : import_lock_level--;
164 : } else {
165 8 : import_lock_thread = PYTHREAD_INVALID_THREAD_ID;
166 8 : import_lock_level = 0;
167 : }
168 8 : return _PyStatus_OK();
169 : }
170 : #endif
171 :
172 : /*[clinic input]
173 : _imp.lock_held
174 :
175 : Return True if the import lock is currently held, else False.
176 :
177 : On platforms without threads, return False.
178 : [clinic start generated code]*/
179 :
180 : static PyObject *
181 71 : _imp_lock_held_impl(PyObject *module)
182 : /*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
183 : {
184 71 : return PyBool_FromLong(import_lock_thread != PYTHREAD_INVALID_THREAD_ID);
185 : }
186 :
187 : /*[clinic input]
188 : _imp.acquire_lock
189 :
190 : Acquires the interpreter's import lock for the current thread.
191 :
192 : This lock should be used by import hooks to ensure thread-safety when importing
193 : modules. On platforms without threads, this function does nothing.
194 : [clinic start generated code]*/
195 :
196 : static PyObject *
197 1498360 : _imp_acquire_lock_impl(PyObject *module)
198 : /*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
199 : {
200 1498360 : _PyImport_AcquireLock();
201 1498360 : Py_RETURN_NONE;
202 : }
203 :
204 : /*[clinic input]
205 : _imp.release_lock
206 :
207 : Release the interpreter's import lock.
208 :
209 : On platforms without threads, this function does nothing.
210 : [clinic start generated code]*/
211 :
212 : static PyObject *
213 1498360 : _imp_release_lock_impl(PyObject *module)
214 : /*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
215 : {
216 1498360 : if (_PyImport_ReleaseLock() < 0) {
217 1 : PyErr_SetString(PyExc_RuntimeError,
218 : "not holding the import lock");
219 1 : return NULL;
220 : }
221 1498360 : Py_RETURN_NONE;
222 : }
223 :
224 : void
225 2952 : _PyImport_Fini(void)
226 : {
227 2952 : Py_CLEAR(extensions);
228 2952 : if (import_lock != NULL) {
229 2952 : PyThread_free_lock(import_lock);
230 2952 : import_lock = NULL;
231 : }
232 2952 : }
233 :
234 : void
235 2167 : _PyImport_Fini2(void)
236 : {
237 : /* Use the same memory allocator than PyImport_ExtendInittab(). */
238 : PyMemAllocatorEx old_alloc;
239 2167 : _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
240 :
241 : // Reset PyImport_Inittab
242 2167 : PyImport_Inittab = _PyImport_Inittab;
243 :
244 : /* Free memory allocated by PyImport_ExtendInittab() */
245 2167 : PyMem_RawFree(inittab_copy);
246 2167 : inittab_copy = NULL;
247 :
248 2167 : PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
249 2167 : }
250 :
251 : /* Helper for sys */
252 :
253 : PyObject *
254 3847 : PyImport_GetModuleDict(void)
255 : {
256 3847 : PyInterpreterState *interp = _PyInterpreterState_GET();
257 3847 : if (interp->modules == NULL) {
258 0 : Py_FatalError("interpreter has no modules dictionary");
259 : }
260 3847 : return interp->modules;
261 : }
262 :
263 : /* In some corner cases it is important to be sure that the import
264 : machinery has been initialized (or not cleaned up yet). For
265 : example, see issue #4236 and PyModule_Create2(). */
266 :
267 : int
268 7004 : _PyImport_IsInitialized(PyInterpreterState *interp)
269 : {
270 7004 : if (interp->modules == NULL)
271 0 : return 0;
272 7004 : return 1;
273 : }
274 :
275 : PyObject *
276 73 : _PyImport_GetModuleId(_Py_Identifier *nameid)
277 : {
278 73 : PyObject *name = _PyUnicode_FromId(nameid); /* borrowed */
279 73 : if (name == NULL) {
280 0 : return NULL;
281 : }
282 73 : return PyImport_GetModule(name);
283 : }
284 :
285 : int
286 76 : _PyImport_SetModule(PyObject *name, PyObject *m)
287 : {
288 76 : PyInterpreterState *interp = _PyInterpreterState_GET();
289 76 : PyObject *modules = interp->modules;
290 76 : return PyObject_SetItem(modules, name, m);
291 : }
292 :
293 : int
294 3130 : _PyImport_SetModuleString(const char *name, PyObject *m)
295 : {
296 3130 : PyInterpreterState *interp = _PyInterpreterState_GET();
297 3130 : PyObject *modules = interp->modules;
298 3130 : return PyMapping_SetItemString(modules, name, m);
299 : }
300 :
301 : static PyObject *
302 2921510 : import_get_module(PyThreadState *tstate, PyObject *name)
303 : {
304 2921510 : PyObject *modules = tstate->interp->modules;
305 2921510 : if (modules == NULL) {
306 0 : _PyErr_SetString(tstate, PyExc_RuntimeError,
307 : "unable to get sys.modules");
308 0 : return NULL;
309 : }
310 :
311 : PyObject *m;
312 2921510 : Py_INCREF(modules);
313 2921510 : if (PyDict_CheckExact(modules)) {
314 2921510 : m = PyDict_GetItemWithError(modules, name); /* borrowed */
315 2921510 : Py_XINCREF(m);
316 : }
317 : else {
318 0 : m = PyObject_GetItem(modules, name);
319 0 : if (m == NULL && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
320 0 : _PyErr_Clear(tstate);
321 : }
322 : }
323 2921510 : Py_DECREF(modules);
324 2921510 : return m;
325 : }
326 :
327 :
328 : static int
329 2014400 : import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
330 : {
331 : PyObject *spec;
332 :
333 : /* Optimization: only call _bootstrap._lock_unlock_module() if
334 : __spec__._initializing is true.
335 : NOTE: because of this, initializing must be set *before*
336 : stuffing the new module in sys.modules.
337 : */
338 2014400 : spec = PyObject_GetAttr(mod, &_Py_ID(__spec__));
339 2014400 : int busy = _PyModuleSpec_IsInitializing(spec);
340 2014400 : Py_XDECREF(spec);
341 2014400 : if (busy) {
342 : /* Wait until module is done importing. */
343 78662 : PyObject *value = _PyObject_CallMethodOneArg(
344 : interp->importlib, &_Py_ID(_lock_unlock_module), name);
345 78662 : if (value == NULL) {
346 0 : return -1;
347 : }
348 78662 : Py_DECREF(value);
349 : }
350 2014400 : return 0;
351 : }
352 :
353 :
354 : /* Helper for pythonrun.c -- return magic number and tag. */
355 :
356 : long
357 338 : PyImport_GetMagicNumber(void)
358 : {
359 : long res;
360 338 : PyInterpreterState *interp = _PyInterpreterState_GET();
361 : PyObject *external, *pyc_magic;
362 :
363 338 : external = PyObject_GetAttrString(interp->importlib, "_bootstrap_external");
364 338 : if (external == NULL)
365 0 : return -1;
366 338 : pyc_magic = PyObject_GetAttrString(external, "_RAW_MAGIC_NUMBER");
367 338 : Py_DECREF(external);
368 338 : if (pyc_magic == NULL)
369 0 : return -1;
370 338 : res = PyLong_AsLong(pyc_magic);
371 338 : Py_DECREF(pyc_magic);
372 338 : return res;
373 : }
374 :
375 :
376 : extern const char * _PySys_ImplCacheTag;
377 :
378 : const char *
379 0 : PyImport_GetMagicTag(void)
380 : {
381 0 : return _PySys_ImplCacheTag;
382 : }
383 :
384 :
385 : /* Magic for extension modules (built-in as well as dynamically
386 : loaded). To prevent initializing an extension module more than
387 : once, we keep a static dictionary 'extensions' keyed by the tuple
388 : (module name, module name) (for built-in modules) or by
389 : (filename, module name) (for dynamically loaded modules), containing these
390 : modules. A copy of the module's dictionary is stored by calling
391 : _PyImport_FixupExtensionObject() immediately after the module initialization
392 : function succeeds. A copy can be retrieved from there by calling
393 : import_find_extension().
394 :
395 : Modules which do support multiple initialization set their m_size
396 : field to a non-negative number (indicating the size of the
397 : module-specific state). They are still recorded in the extensions
398 : dictionary, to avoid loading shared libraries twice.
399 : */
400 :
401 : int
402 13091 : _PyImport_FixupExtensionObject(PyObject *mod, PyObject *name,
403 : PyObject *filename, PyObject *modules)
404 : {
405 13091 : if (mod == NULL || !PyModule_Check(mod)) {
406 0 : PyErr_BadInternalCall();
407 0 : return -1;
408 : }
409 :
410 13091 : struct PyModuleDef *def = PyModule_GetDef(mod);
411 13091 : if (!def) {
412 0 : PyErr_BadInternalCall();
413 0 : return -1;
414 : }
415 :
416 13091 : PyThreadState *tstate = _PyThreadState_GET();
417 13091 : if (PyObject_SetItem(modules, name, mod) < 0) {
418 0 : return -1;
419 : }
420 13091 : if (_PyState_AddModule(tstate, mod, def) < 0) {
421 0 : PyMapping_DelItem(modules, name);
422 0 : return -1;
423 : }
424 :
425 : // bpo-44050: Extensions and def->m_base.m_copy can be updated
426 : // when the extension module doesn't support sub-interpreters.
427 13091 : if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
428 13091 : if (def->m_size == -1) {
429 9263 : if (def->m_base.m_copy) {
430 : /* Somebody already imported the module,
431 : likely under a different name.
432 : XXX this should really not happen. */
433 115 : Py_CLEAR(def->m_base.m_copy);
434 : }
435 9263 : PyObject *dict = PyModule_GetDict(mod);
436 9263 : if (dict == NULL) {
437 0 : return -1;
438 : }
439 9263 : def->m_base.m_copy = PyDict_Copy(dict);
440 9263 : if (def->m_base.m_copy == NULL) {
441 0 : return -1;
442 : }
443 : }
444 :
445 13091 : if (extensions == NULL) {
446 2963 : extensions = PyDict_New();
447 2963 : if (extensions == NULL) {
448 0 : return -1;
449 : }
450 : }
451 :
452 13091 : PyObject *key = PyTuple_Pack(2, filename, name);
453 13091 : if (key == NULL) {
454 0 : return -1;
455 : }
456 13091 : int res = PyDict_SetItem(extensions, key, (PyObject *)def);
457 13091 : Py_DECREF(key);
458 13091 : if (res < 0) {
459 0 : return -1;
460 : }
461 : }
462 :
463 13091 : return 0;
464 : }
465 :
466 : int
467 6268 : _PyImport_FixupBuiltin(PyObject *mod, const char *name, PyObject *modules)
468 : {
469 : int res;
470 : PyObject *nameobj;
471 6268 : nameobj = PyUnicode_InternFromString(name);
472 6268 : if (nameobj == NULL)
473 0 : return -1;
474 6268 : res = _PyImport_FixupExtensionObject(mod, nameobj, nameobj, modules);
475 6268 : Py_DECREF(nameobj);
476 6268 : return res;
477 : }
478 :
479 : static PyObject *
480 86266 : import_find_extension(PyThreadState *tstate, PyObject *name,
481 : PyObject *filename)
482 : {
483 86266 : if (extensions == NULL) {
484 0 : return NULL;
485 : }
486 :
487 86266 : PyObject *key = PyTuple_Pack(2, filename, name);
488 86266 : if (key == NULL) {
489 0 : return NULL;
490 : }
491 86266 : PyModuleDef* def = (PyModuleDef *)PyDict_GetItemWithError(extensions, key);
492 86266 : Py_DECREF(key);
493 86266 : if (def == NULL) {
494 86033 : return NULL;
495 : }
496 :
497 : PyObject *mod, *mdict;
498 233 : PyObject *modules = tstate->interp->modules;
499 :
500 233 : if (def->m_size == -1) {
501 : /* Module does not support repeated initialization */
502 51 : if (def->m_base.m_copy == NULL)
503 0 : return NULL;
504 51 : mod = import_add_module(tstate, name);
505 51 : if (mod == NULL)
506 0 : return NULL;
507 51 : mdict = PyModule_GetDict(mod);
508 51 : if (mdict == NULL) {
509 0 : Py_DECREF(mod);
510 0 : return NULL;
511 : }
512 51 : if (PyDict_Update(mdict, def->m_base.m_copy)) {
513 0 : Py_DECREF(mod);
514 0 : return NULL;
515 : }
516 : }
517 : else {
518 182 : if (def->m_base.m_init == NULL)
519 0 : return NULL;
520 182 : mod = _PyImport_InitFunc_TrampolineCall(def->m_base.m_init);
521 182 : if (mod == NULL)
522 0 : return NULL;
523 182 : if (PyObject_SetItem(modules, name, mod) == -1) {
524 0 : Py_DECREF(mod);
525 0 : return NULL;
526 : }
527 : }
528 233 : if (_PyState_AddModule(tstate, mod, def) < 0) {
529 0 : PyMapping_DelItem(modules, name);
530 0 : Py_DECREF(mod);
531 0 : return NULL;
532 : }
533 :
534 233 : int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
535 233 : if (verbose) {
536 0 : PySys_FormatStderr("import %U # previously loaded (%R)\n",
537 : name, filename);
538 : }
539 233 : return mod;
540 : }
541 :
542 :
543 : /* Get the module object corresponding to a module name.
544 : First check the modules dictionary if there's one there,
545 : if not, create a new one and insert it in the modules dictionary. */
546 :
547 : static PyObject *
548 11549 : import_add_module(PyThreadState *tstate, PyObject *name)
549 : {
550 11549 : PyObject *modules = tstate->interp->modules;
551 11549 : if (modules == NULL) {
552 0 : _PyErr_SetString(tstate, PyExc_RuntimeError,
553 : "no import module dictionary");
554 0 : return NULL;
555 : }
556 :
557 : PyObject *m;
558 11549 : if (PyDict_CheckExact(modules)) {
559 11549 : m = PyDict_GetItemWithError(modules, name);
560 11549 : Py_XINCREF(m);
561 : }
562 : else {
563 0 : m = PyObject_GetItem(modules, name);
564 : // For backward-compatibility we copy the behavior
565 : // of PyDict_GetItemWithError().
566 0 : if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
567 0 : _PyErr_Clear(tstate);
568 : }
569 : }
570 11549 : if (_PyErr_Occurred(tstate)) {
571 0 : return NULL;
572 : }
573 11549 : if (m != NULL && PyModule_Check(m)) {
574 5242 : return m;
575 : }
576 6307 : Py_XDECREF(m);
577 6307 : m = PyModule_NewObject(name);
578 6307 : if (m == NULL)
579 0 : return NULL;
580 6307 : if (PyObject_SetItem(modules, name, m) != 0) {
581 0 : Py_DECREF(m);
582 0 : return NULL;
583 : }
584 :
585 6307 : return m;
586 : }
587 :
588 : PyObject *
589 8367 : PyImport_AddModuleObject(PyObject *name)
590 : {
591 8367 : PyThreadState *tstate = _PyThreadState_GET();
592 8367 : PyObject *mod = import_add_module(tstate, name);
593 8367 : if (mod) {
594 8367 : PyObject *ref = PyWeakref_NewRef(mod, NULL);
595 8367 : Py_DECREF(mod);
596 8367 : if (ref == NULL) {
597 0 : return NULL;
598 : }
599 8367 : mod = PyWeakref_GetObject(ref);
600 8367 : Py_DECREF(ref);
601 : }
602 8367 : return mod; /* borrowed reference */
603 : }
604 :
605 :
606 : PyObject *
607 8345 : PyImport_AddModule(const char *name)
608 : {
609 8345 : PyObject *nameobj = PyUnicode_FromString(name);
610 8345 : if (nameobj == NULL) {
611 0 : return NULL;
612 : }
613 8345 : PyObject *module = PyImport_AddModuleObject(nameobj);
614 8345 : Py_DECREF(nameobj);
615 8345 : return module;
616 : }
617 :
618 :
619 : /* Remove name from sys.modules, if it's there.
620 : * Can be called with an exception raised.
621 : * If fail to remove name a new exception will be chained with the old
622 : * exception, otherwise the old exception is preserved.
623 : */
624 : static void
625 0 : remove_module(PyThreadState *tstate, PyObject *name)
626 : {
627 : PyObject *type, *value, *traceback;
628 0 : _PyErr_Fetch(tstate, &type, &value, &traceback);
629 :
630 0 : PyObject *modules = tstate->interp->modules;
631 0 : if (PyDict_CheckExact(modules)) {
632 0 : PyObject *mod = _PyDict_Pop(modules, name, Py_None);
633 0 : Py_XDECREF(mod);
634 : }
635 0 : else if (PyMapping_DelItem(modules, name) < 0) {
636 0 : if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
637 0 : _PyErr_Clear(tstate);
638 : }
639 : }
640 :
641 0 : _PyErr_ChainExceptions(type, value, traceback);
642 0 : }
643 :
644 :
645 : /* Execute a code object in a module and return the module object
646 : * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
647 : * removed from sys.modules, to avoid leaving damaged module objects
648 : * in sys.modules. The caller may wish to restore the original
649 : * module object (if any) in this case; PyImport_ReloadModule is an
650 : * example.
651 : *
652 : * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
653 : * interface. The other two exist primarily for backward compatibility.
654 : */
655 : PyObject *
656 0 : PyImport_ExecCodeModule(const char *name, PyObject *co)
657 : {
658 0 : return PyImport_ExecCodeModuleWithPathnames(
659 : name, co, (char *)NULL, (char *)NULL);
660 : }
661 :
662 : PyObject *
663 0 : PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
664 : {
665 0 : return PyImport_ExecCodeModuleWithPathnames(
666 : name, co, pathname, (char *)NULL);
667 : }
668 :
669 : PyObject *
670 0 : PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
671 : const char *pathname,
672 : const char *cpathname)
673 : {
674 0 : PyObject *m = NULL;
675 0 : PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
676 :
677 0 : nameobj = PyUnicode_FromString(name);
678 0 : if (nameobj == NULL)
679 0 : return NULL;
680 :
681 0 : if (cpathname != NULL) {
682 0 : cpathobj = PyUnicode_DecodeFSDefault(cpathname);
683 0 : if (cpathobj == NULL)
684 0 : goto error;
685 : }
686 : else
687 0 : cpathobj = NULL;
688 :
689 0 : if (pathname != NULL) {
690 0 : pathobj = PyUnicode_DecodeFSDefault(pathname);
691 0 : if (pathobj == NULL)
692 0 : goto error;
693 : }
694 0 : else if (cpathobj != NULL) {
695 0 : PyInterpreterState *interp = _PyInterpreterState_GET();
696 :
697 0 : if (interp == NULL) {
698 0 : Py_FatalError("no current interpreter");
699 : }
700 :
701 0 : external= PyObject_GetAttrString(interp->importlib,
702 : "_bootstrap_external");
703 0 : if (external != NULL) {
704 0 : pathobj = _PyObject_CallMethodOneArg(
705 : external, &_Py_ID(_get_sourcefile), cpathobj);
706 0 : Py_DECREF(external);
707 : }
708 0 : if (pathobj == NULL)
709 0 : PyErr_Clear();
710 : }
711 : else
712 0 : pathobj = NULL;
713 :
714 0 : m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
715 0 : error:
716 0 : Py_DECREF(nameobj);
717 0 : Py_XDECREF(pathobj);
718 0 : Py_XDECREF(cpathobj);
719 0 : return m;
720 : }
721 :
722 : static PyObject *
723 3131 : module_dict_for_exec(PyThreadState *tstate, PyObject *name)
724 : {
725 : PyObject *m, *d;
726 :
727 3131 : m = import_add_module(tstate, name);
728 3131 : if (m == NULL)
729 0 : return NULL;
730 : /* If the module is being reloaded, we get the old module back
731 : and re-use its dict to exec the new code. */
732 3131 : d = PyModule_GetDict(m);
733 3131 : int r = PyDict_Contains(d, &_Py_ID(__builtins__));
734 3131 : if (r == 0) {
735 3130 : r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
736 : }
737 3131 : if (r < 0) {
738 0 : remove_module(tstate, name);
739 0 : Py_DECREF(m);
740 0 : return NULL;
741 : }
742 :
743 3131 : Py_INCREF(d);
744 3131 : Py_DECREF(m);
745 3131 : return d;
746 : }
747 :
748 : static PyObject *
749 3131 : exec_code_in_module(PyThreadState *tstate, PyObject *name,
750 : PyObject *module_dict, PyObject *code_object)
751 : {
752 : PyObject *v, *m;
753 :
754 3131 : v = PyEval_EvalCode(code_object, module_dict, module_dict);
755 3131 : if (v == NULL) {
756 0 : remove_module(tstate, name);
757 0 : return NULL;
758 : }
759 3131 : Py_DECREF(v);
760 :
761 3131 : m = import_get_module(tstate, name);
762 3131 : if (m == NULL && !_PyErr_Occurred(tstate)) {
763 0 : _PyErr_Format(tstate, PyExc_ImportError,
764 : "Loaded module %R not found in sys.modules",
765 : name);
766 : }
767 :
768 3131 : return m;
769 : }
770 :
771 : PyObject*
772 0 : PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
773 : PyObject *cpathname)
774 : {
775 0 : PyThreadState *tstate = _PyThreadState_GET();
776 : PyObject *d, *external, *res;
777 :
778 0 : d = module_dict_for_exec(tstate, name);
779 0 : if (d == NULL) {
780 0 : return NULL;
781 : }
782 :
783 0 : if (pathname == NULL) {
784 0 : pathname = ((PyCodeObject *)co)->co_filename;
785 : }
786 0 : external = PyObject_GetAttrString(tstate->interp->importlib,
787 : "_bootstrap_external");
788 0 : if (external == NULL) {
789 0 : Py_DECREF(d);
790 0 : return NULL;
791 : }
792 0 : res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module),
793 : d, name, pathname, cpathname, NULL);
794 0 : Py_DECREF(external);
795 0 : if (res != NULL) {
796 0 : Py_DECREF(res);
797 0 : res = exec_code_in_module(tstate, name, d, co);
798 : }
799 0 : Py_DECREF(d);
800 0 : return res;
801 : }
802 :
803 :
804 : static void
805 4 : update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
806 : {
807 : PyObject *constants, *tmp;
808 : Py_ssize_t i, n;
809 :
810 4 : if (PyUnicode_Compare(co->co_filename, oldname))
811 0 : return;
812 :
813 4 : Py_INCREF(newname);
814 4 : Py_XSETREF(co->co_filename, newname);
815 :
816 4 : constants = co->co_consts;
817 4 : n = PyTuple_GET_SIZE(constants);
818 13 : for (i = 0; i < n; i++) {
819 9 : tmp = PyTuple_GET_ITEM(constants, i);
820 9 : if (PyCode_Check(tmp))
821 1 : update_code_filenames((PyCodeObject *)tmp,
822 : oldname, newname);
823 : }
824 : }
825 :
826 : static void
827 201625 : update_compiled_module(PyCodeObject *co, PyObject *newname)
828 : {
829 : PyObject *oldname;
830 :
831 201625 : if (PyUnicode_Compare(co->co_filename, newname) == 0)
832 201622 : return;
833 :
834 3 : oldname = co->co_filename;
835 3 : Py_INCREF(oldname);
836 3 : update_code_filenames(co, oldname, newname);
837 3 : Py_DECREF(oldname);
838 : }
839 :
840 : /*[clinic input]
841 : _imp._fix_co_filename
842 :
843 : code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
844 : Code object to change.
845 :
846 : path: unicode
847 : File path to use.
848 : /
849 :
850 : Changes code.co_filename to specify the passed-in file path.
851 : [clinic start generated code]*/
852 :
853 : static PyObject *
854 201625 : _imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
855 : PyObject *path)
856 : /*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
857 :
858 : {
859 201625 : update_compiled_module(code, path);
860 :
861 201625 : Py_RETURN_NONE;
862 : }
863 :
864 :
865 : /* Helper to test for built-in module */
866 :
867 : static int
868 232387 : is_builtin(PyObject *name)
869 : {
870 : int i;
871 6433450 : for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
872 6254840 : if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
873 53776 : if (PyImport_Inittab[i].initfunc == NULL)
874 8 : return -1;
875 : else
876 53768 : return 1;
877 : }
878 : }
879 178611 : return 0;
880 : }
881 :
882 :
883 : /* Return a finder object for a sys.path/pkg.__path__ item 'p',
884 : possibly by fetching it from the path_importer_cache dict. If it
885 : wasn't yet cached, traverse path_hooks until a hook is found
886 : that can handle the path item. Return None if no hook could;
887 : this tells our caller that the path based finder could not find
888 : a finder for this path item. Cache the result in
889 : path_importer_cache. */
890 :
891 : static PyObject *
892 366 : get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
893 : PyObject *path_hooks, PyObject *p)
894 : {
895 : PyObject *importer;
896 : Py_ssize_t j, nhooks;
897 :
898 : /* These conditions are the caller's responsibility: */
899 366 : assert(PyList_Check(path_hooks));
900 366 : assert(PyDict_Check(path_importer_cache));
901 :
902 366 : nhooks = PyList_Size(path_hooks);
903 366 : if (nhooks < 0)
904 0 : return NULL; /* Shouldn't happen */
905 :
906 366 : importer = PyDict_GetItemWithError(path_importer_cache, p);
907 366 : if (importer != NULL || _PyErr_Occurred(tstate)) {
908 0 : Py_XINCREF(importer);
909 0 : return importer;
910 : }
911 :
912 : /* set path_importer_cache[p] to None to avoid recursion */
913 366 : if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
914 0 : return NULL;
915 :
916 1060 : for (j = 0; j < nhooks; j++) {
917 719 : PyObject *hook = PyList_GetItem(path_hooks, j);
918 719 : if (hook == NULL)
919 0 : return NULL;
920 719 : importer = PyObject_CallOneArg(hook, p);
921 719 : if (importer != NULL)
922 25 : break;
923 :
924 694 : if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
925 0 : return NULL;
926 : }
927 694 : _PyErr_Clear(tstate);
928 : }
929 366 : if (importer == NULL) {
930 341 : Py_RETURN_NONE;
931 : }
932 25 : if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
933 0 : Py_DECREF(importer);
934 0 : return NULL;
935 : }
936 25 : return importer;
937 : }
938 :
939 : PyObject *
940 366 : PyImport_GetImporter(PyObject *path)
941 : {
942 366 : PyThreadState *tstate = _PyThreadState_GET();
943 366 : PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
944 366 : PyObject *path_hooks = PySys_GetObject("path_hooks");
945 366 : if (path_importer_cache == NULL || path_hooks == NULL) {
946 0 : return NULL;
947 : }
948 366 : return get_path_importer(tstate, path_importer_cache, path_hooks, path);
949 : }
950 :
951 : #if defined(__EMSCRIPTEN__) && defined(PY_CALL_TRAMPOLINE)
952 : #include <emscripten.h>
953 : EM_JS(PyObject*, _PyImport_InitFunc_TrampolineCall, (PyModInitFunction func), {
954 : return wasmTable.get(func)();
955 : });
956 : #endif // __EMSCRIPTEN__ && PY_CALL_TRAMPOLINE
957 :
958 : static PyObject*
959 56800 : create_builtin(PyThreadState *tstate, PyObject *name, PyObject *spec)
960 : {
961 56800 : PyObject *mod = import_find_extension(tstate, name, name);
962 56800 : if (mod || _PyErr_Occurred(tstate)) {
963 171 : return mod;
964 : }
965 :
966 56629 : PyObject *modules = tstate->interp->modules;
967 789738 : for (struct _inittab *p = PyImport_Inittab; p->name != NULL; p++) {
968 789738 : if (_PyUnicode_EqualToASCIIString(name, p->name)) {
969 56629 : if (p->initfunc == NULL) {
970 : /* Cannot re-init internal module ("sys" or "builtins") */
971 0 : return PyImport_AddModuleObject(name);
972 : }
973 56629 : mod = _PyImport_InitFunc_TrampolineCall(*p->initfunc);
974 56629 : if (mod == NULL) {
975 0 : return NULL;
976 : }
977 :
978 56629 : if (PyObject_TypeCheck(mod, &PyModuleDef_Type)) {
979 53653 : return PyModule_FromDefAndSpec((PyModuleDef*)mod, spec);
980 : }
981 : else {
982 : /* Remember pointer to module init function. */
983 2976 : PyModuleDef *def = PyModule_GetDef(mod);
984 2976 : if (def == NULL) {
985 0 : return NULL;
986 : }
987 :
988 2976 : def->m_base.m_init = p->initfunc;
989 2976 : if (_PyImport_FixupExtensionObject(mod, name, name,
990 : modules) < 0) {
991 0 : return NULL;
992 : }
993 2976 : return mod;
994 : }
995 : }
996 : }
997 :
998 : // not found
999 0 : Py_RETURN_NONE;
1000 : }
1001 :
1002 :
1003 :
1004 : /*[clinic input]
1005 : _imp.create_builtin
1006 :
1007 : spec: object
1008 : /
1009 :
1010 : Create an extension module.
1011 : [clinic start generated code]*/
1012 :
1013 : static PyObject *
1014 53670 : _imp_create_builtin(PyObject *module, PyObject *spec)
1015 : /*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
1016 : {
1017 53670 : PyThreadState *tstate = _PyThreadState_GET();
1018 :
1019 53670 : PyObject *name = PyObject_GetAttrString(spec, "name");
1020 53670 : if (name == NULL) {
1021 0 : return NULL;
1022 : }
1023 :
1024 53670 : PyObject *mod = create_builtin(tstate, name, spec);
1025 53670 : Py_DECREF(name);
1026 53670 : return mod;
1027 : }
1028 :
1029 :
1030 : /* Return true if the name is an alias. In that case, "alias" is set
1031 : to the original module name. If it is an alias but the original
1032 : module isn't known then "alias" is set to NULL while true is returned. */
1033 : static bool
1034 22314 : resolve_module_alias(const char *name, const struct _module_alias *aliases,
1035 : const char **alias)
1036 : {
1037 : const struct _module_alias *entry;
1038 88399 : for (entry = aliases; ; entry++) {
1039 88399 : if (entry->name == NULL) {
1040 : /* It isn't an alias. */
1041 6636 : return false;
1042 : }
1043 81763 : if (strcmp(name, entry->name) == 0) {
1044 15678 : if (alias != NULL) {
1045 15678 : *alias = entry->orig;
1046 : }
1047 15678 : return true;
1048 : }
1049 : }
1050 : }
1051 :
1052 :
1053 : /* Frozen modules */
1054 :
1055 : static bool
1056 260448 : use_frozen(void)
1057 : {
1058 260448 : PyInterpreterState *interp = _PyInterpreterState_GET();
1059 260448 : int override = interp->override_frozen_modules;
1060 260448 : if (override > 0) {
1061 247 : return true;
1062 : }
1063 260201 : else if (override < 0) {
1064 8616 : return false;
1065 : }
1066 : else {
1067 251585 : return interp->config.use_frozen_modules;
1068 : }
1069 : }
1070 :
1071 : static PyObject *
1072 1 : list_frozen_module_names(void)
1073 : {
1074 1 : PyObject *names = PyList_New(0);
1075 1 : if (names == NULL) {
1076 0 : return NULL;
1077 : }
1078 1 : bool enabled = use_frozen();
1079 : const struct _frozen *p;
1080 : #define ADD_MODULE(name) \
1081 : do { \
1082 : PyObject *nameobj = PyUnicode_FromString(name); \
1083 : if (nameobj == NULL) { \
1084 : goto error; \
1085 : } \
1086 : int res = PyList_Append(names, nameobj); \
1087 : Py_DECREF(nameobj); \
1088 : if (res != 0) { \
1089 : goto error; \
1090 : } \
1091 : } while(0)
1092 : // We always use the bootstrap modules.
1093 4 : for (p = _PyImport_FrozenBootstrap; ; p++) {
1094 4 : if (p->name == NULL) {
1095 1 : break;
1096 : }
1097 3 : ADD_MODULE(p->name);
1098 : }
1099 : // Frozen stdlib modules may be disabled.
1100 16 : for (p = _PyImport_FrozenStdlib; ; p++) {
1101 16 : if (p->name == NULL) {
1102 1 : break;
1103 : }
1104 15 : if (enabled) {
1105 15 : ADD_MODULE(p->name);
1106 : }
1107 : }
1108 12 : for (p = _PyImport_FrozenTest; ; p++) {
1109 12 : if (p->name == NULL) {
1110 1 : break;
1111 : }
1112 11 : if (enabled) {
1113 11 : ADD_MODULE(p->name);
1114 : }
1115 : }
1116 : #undef ADD_MODULE
1117 : // Add any custom modules.
1118 1 : if (PyImport_FrozenModules != NULL) {
1119 0 : for (p = PyImport_FrozenModules; ; p++) {
1120 0 : if (p->name == NULL) {
1121 0 : break;
1122 : }
1123 0 : PyObject *nameobj = PyUnicode_FromString(p->name);
1124 0 : if (nameobj == NULL) {
1125 0 : goto error;
1126 : }
1127 0 : int found = PySequence_Contains(names, nameobj);
1128 0 : if (found < 0) {
1129 0 : Py_DECREF(nameobj);
1130 0 : goto error;
1131 : }
1132 0 : else if (found) {
1133 0 : Py_DECREF(nameobj);
1134 : }
1135 : else {
1136 0 : int res = PyList_Append(names, nameobj);
1137 0 : Py_DECREF(nameobj);
1138 0 : if (res != 0) {
1139 0 : goto error;
1140 : }
1141 : }
1142 : }
1143 : }
1144 1 : return names;
1145 :
1146 0 : error:
1147 0 : Py_DECREF(names);
1148 0 : return NULL;
1149 : }
1150 :
1151 : typedef enum {
1152 : FROZEN_OKAY,
1153 : FROZEN_BAD_NAME, // The given module name wasn't valid.
1154 : FROZEN_NOT_FOUND, // It wasn't in PyImport_FrozenModules.
1155 : FROZEN_DISABLED, // -X frozen_modules=off (and not essential)
1156 : FROZEN_EXCLUDED, /* The PyImport_FrozenModules entry has NULL "code"
1157 : (module is present but marked as unimportable, stops search). */
1158 : FROZEN_INVALID, /* The PyImport_FrozenModules entry is bogus
1159 : (eg. does not contain executable code). */
1160 : } frozen_status;
1161 :
1162 : static inline void
1163 2 : set_frozen_error(frozen_status status, PyObject *modname)
1164 : {
1165 2 : const char *err = NULL;
1166 2 : switch (status) {
1167 2 : case FROZEN_BAD_NAME:
1168 : case FROZEN_NOT_FOUND:
1169 2 : err = "No such frozen object named %R";
1170 2 : break;
1171 0 : case FROZEN_DISABLED:
1172 0 : err = "Frozen modules are disabled and the frozen object named %R is not essential";
1173 0 : break;
1174 0 : case FROZEN_EXCLUDED:
1175 0 : err = "Excluded frozen object named %R";
1176 0 : break;
1177 0 : case FROZEN_INVALID:
1178 0 : err = "Frozen object named %R is invalid";
1179 0 : break;
1180 0 : case FROZEN_OKAY:
1181 : // There was no error.
1182 0 : break;
1183 0 : default:
1184 0 : Py_UNREACHABLE();
1185 : }
1186 2 : if (err != NULL) {
1187 2 : PyObject *msg = PyUnicode_FromFormat(err, modname);
1188 2 : if (msg == NULL) {
1189 0 : PyErr_Clear();
1190 : }
1191 2 : PyErr_SetImportError(msg, modname, NULL);
1192 2 : Py_XDECREF(msg);
1193 : }
1194 2 : }
1195 :
1196 : static const struct _frozen *
1197 282373 : look_up_frozen(const char *name)
1198 : {
1199 : const struct _frozen *p;
1200 : // We always use the bootstrap modules.
1201 1082160 : for (p = _PyImport_FrozenBootstrap; ; p++) {
1202 1082160 : if (p->name == NULL) {
1203 : // We hit the end-of-list sentinel value.
1204 260448 : break;
1205 : }
1206 821715 : if (strcmp(name, p->name) == 0) {
1207 21925 : return p;
1208 : }
1209 : }
1210 : // Prefer custom modules, if any. Frozen stdlib modules can be
1211 : // disabled here by setting "code" to NULL in the array entry.
1212 260448 : if (PyImport_FrozenModules != NULL) {
1213 33 : for (p = PyImport_FrozenModules; ; p++) {
1214 33 : if (p->name == NULL) {
1215 16 : break;
1216 : }
1217 17 : if (strcmp(name, p->name) == 0) {
1218 1 : return p;
1219 : }
1220 : }
1221 : }
1222 : // Frozen stdlib modules may be disabled.
1223 260447 : if (use_frozen()) {
1224 6471 : for (p = _PyImport_FrozenStdlib; ; p++) {
1225 6471 : if (p->name == NULL) {
1226 342 : break;
1227 : }
1228 6129 : if (strcmp(name, p->name) == 0) {
1229 161 : return p;
1230 : }
1231 : }
1232 2326 : for (p = _PyImport_FrozenTest; ; p++) {
1233 2326 : if (p->name == NULL) {
1234 115 : break;
1235 : }
1236 2211 : if (strcmp(name, p->name) == 0) {
1237 227 : return p;
1238 : }
1239 : }
1240 : }
1241 260059 : return NULL;
1242 : }
1243 :
1244 : struct frozen_info {
1245 : PyObject *nameobj;
1246 : const char *data;
1247 : PyObject *(*get_code)(void);
1248 : Py_ssize_t size;
1249 : bool is_package;
1250 : bool is_alias;
1251 : const char *origname;
1252 : };
1253 :
1254 : static frozen_status
1255 282374 : find_frozen(PyObject *nameobj, struct frozen_info *info)
1256 : {
1257 282374 : if (info != NULL) {
1258 282374 : memset(info, 0, sizeof(*info));
1259 : }
1260 :
1261 282374 : if (nameobj == NULL || nameobj == Py_None) {
1262 0 : return FROZEN_BAD_NAME;
1263 : }
1264 282374 : const char *name = PyUnicode_AsUTF8(nameobj);
1265 282374 : if (name == NULL) {
1266 : // Note that this function previously used
1267 : // _PyUnicode_EqualToASCIIString(). We clear the error here
1268 : // (instead of propagating it) to match the earlier behavior
1269 : // more closely.
1270 1 : PyErr_Clear();
1271 1 : return FROZEN_BAD_NAME;
1272 : }
1273 :
1274 282373 : const struct _frozen *p = look_up_frozen(name);
1275 282373 : if (p == NULL) {
1276 260059 : return FROZEN_NOT_FOUND;
1277 : }
1278 22314 : if (info != NULL) {
1279 22314 : info->nameobj = nameobj; // borrowed
1280 22314 : info->data = (const char *)p->code;
1281 22314 : info->get_code = p->get_code;
1282 22314 : info->size = p->size;
1283 22314 : info->is_package = p->is_package;
1284 22314 : if (p->size < 0) {
1285 : // backward compatibility with negative size values
1286 0 : info->size = -(p->size);
1287 0 : info->is_package = true;
1288 : }
1289 22314 : info->origname = name;
1290 22314 : info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
1291 : &info->origname);
1292 : }
1293 22314 : if (p->code == NULL && p->size == 0 && p->get_code != NULL) {
1294 : /* It is only deepfrozen. */
1295 22208 : return FROZEN_OKAY;
1296 : }
1297 106 : if (p->code == NULL) {
1298 : /* It is frozen but marked as un-importable. */
1299 0 : return FROZEN_EXCLUDED;
1300 : }
1301 106 : if (p->code[0] == '\0' || p->size == 0) {
1302 : /* Does not contain executable code. */
1303 0 : return FROZEN_INVALID;
1304 : }
1305 106 : return FROZEN_OKAY;
1306 : }
1307 :
1308 : static PyObject *
1309 9485 : unmarshal_frozen_code(struct frozen_info *info)
1310 : {
1311 9485 : if (info->get_code) {
1312 9442 : PyObject *code = info->get_code();
1313 9442 : assert(code != NULL);
1314 9442 : return code;
1315 : }
1316 43 : PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
1317 43 : if (co == NULL) {
1318 : /* Does not contain executable code. */
1319 0 : set_frozen_error(FROZEN_INVALID, info->nameobj);
1320 0 : return NULL;
1321 : }
1322 43 : if (!PyCode_Check(co)) {
1323 : // We stick with TypeError for backward compatibility.
1324 0 : PyErr_Format(PyExc_TypeError,
1325 : "frozen object %R is not a code object",
1326 : info->nameobj);
1327 0 : Py_DECREF(co);
1328 0 : return NULL;
1329 : }
1330 43 : return co;
1331 : }
1332 :
1333 :
1334 : /* Initialize a frozen module.
1335 : Return 1 for success, 0 if the module is not found, and -1 with
1336 : an exception set if the initialization failed.
1337 : This function is also used from frozenmain.c */
1338 :
1339 : int
1340 3131 : PyImport_ImportFrozenModuleObject(PyObject *name)
1341 : {
1342 3131 : PyThreadState *tstate = _PyThreadState_GET();
1343 3131 : PyObject *co, *m, *d = NULL;
1344 : int err;
1345 :
1346 : struct frozen_info info;
1347 3131 : frozen_status status = find_frozen(name, &info);
1348 3131 : if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
1349 0 : return 0;
1350 : }
1351 3131 : else if (status == FROZEN_BAD_NAME) {
1352 0 : return 0;
1353 : }
1354 3131 : else if (status != FROZEN_OKAY) {
1355 0 : set_frozen_error(status, name);
1356 0 : return -1;
1357 : }
1358 3131 : co = unmarshal_frozen_code(&info);
1359 3131 : if (co == NULL) {
1360 0 : return -1;
1361 : }
1362 3131 : if (info.is_package) {
1363 : /* Set __path__ to the empty list */
1364 : PyObject *l;
1365 0 : m = import_add_module(tstate, name);
1366 0 : if (m == NULL)
1367 0 : goto err_return;
1368 0 : d = PyModule_GetDict(m);
1369 0 : l = PyList_New(0);
1370 0 : if (l == NULL) {
1371 0 : Py_DECREF(m);
1372 0 : goto err_return;
1373 : }
1374 0 : err = PyDict_SetItemString(d, "__path__", l);
1375 0 : Py_DECREF(l);
1376 0 : Py_DECREF(m);
1377 0 : if (err != 0)
1378 0 : goto err_return;
1379 : }
1380 3131 : d = module_dict_for_exec(tstate, name);
1381 3131 : if (d == NULL) {
1382 0 : goto err_return;
1383 : }
1384 3131 : m = exec_code_in_module(tstate, name, d, co);
1385 3131 : if (m == NULL) {
1386 0 : goto err_return;
1387 : }
1388 3131 : Py_DECREF(m);
1389 : /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
1390 : PyObject *origname;
1391 3131 : if (info.origname) {
1392 3131 : origname = PyUnicode_FromString(info.origname);
1393 3131 : if (origname == NULL) {
1394 0 : goto err_return;
1395 : }
1396 : }
1397 : else {
1398 0 : Py_INCREF(Py_None);
1399 0 : origname = Py_None;
1400 : }
1401 3131 : err = PyDict_SetItemString(d, "__origname__", origname);
1402 3131 : Py_DECREF(origname);
1403 3131 : if (err != 0) {
1404 0 : goto err_return;
1405 : }
1406 3131 : Py_DECREF(d);
1407 3131 : Py_DECREF(co);
1408 3131 : return 1;
1409 :
1410 0 : err_return:
1411 0 : Py_XDECREF(d);
1412 0 : Py_DECREF(co);
1413 0 : return -1;
1414 : }
1415 :
1416 : int
1417 3131 : PyImport_ImportFrozenModule(const char *name)
1418 : {
1419 : PyObject *nameobj;
1420 : int ret;
1421 3131 : nameobj = PyUnicode_InternFromString(name);
1422 3131 : if (nameobj == NULL)
1423 0 : return -1;
1424 3131 : ret = PyImport_ImportFrozenModuleObject(nameobj);
1425 3131 : Py_DECREF(nameobj);
1426 3131 : return ret;
1427 : }
1428 :
1429 :
1430 : /* Import a module, either built-in, frozen, or external, and return
1431 : its module object WITH INCREMENTED REFERENCE COUNT */
1432 :
1433 : PyObject *
1434 26484 : PyImport_ImportModule(const char *name)
1435 : {
1436 : PyObject *pname;
1437 : PyObject *result;
1438 :
1439 26484 : pname = PyUnicode_FromString(name);
1440 26484 : if (pname == NULL)
1441 0 : return NULL;
1442 26484 : result = PyImport_Import(pname);
1443 26484 : Py_DECREF(pname);
1444 26484 : return result;
1445 : }
1446 :
1447 :
1448 : /* Import a module without blocking
1449 : *
1450 : * At first it tries to fetch the module from sys.modules. If the module was
1451 : * never loaded before it loads it with PyImport_ImportModule() unless another
1452 : * thread holds the import lock. In the latter case the function raises an
1453 : * ImportError instead of blocking.
1454 : *
1455 : * Returns the module object with incremented ref count.
1456 : */
1457 : PyObject *
1458 0 : PyImport_ImportModuleNoBlock(const char *name)
1459 : {
1460 0 : return PyImport_ImportModule(name);
1461 : }
1462 :
1463 :
1464 : /* Remove importlib frames from the traceback,
1465 : * except in Verbose mode. */
1466 : static void
1467 19135 : remove_importlib_frames(PyThreadState *tstate)
1468 : {
1469 19135 : const char *importlib_filename = "<frozen importlib._bootstrap>";
1470 19135 : const char *external_filename = "<frozen importlib._bootstrap_external>";
1471 19135 : const char *remove_frames = "_call_with_frames_removed";
1472 19135 : int always_trim = 0;
1473 19135 : int in_importlib = 0;
1474 : PyObject *exception, *value, *base_tb, *tb;
1475 19135 : PyObject **prev_link, **outer_link = NULL;
1476 :
1477 : /* Synopsis: if it's an ImportError, we trim all importlib chunks
1478 : from the traceback. We always trim chunks
1479 : which end with a call to "_call_with_frames_removed". */
1480 :
1481 19135 : _PyErr_Fetch(tstate, &exception, &value, &base_tb);
1482 19135 : if (!exception || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
1483 23 : goto done;
1484 : }
1485 :
1486 19112 : if (PyType_IsSubtype((PyTypeObject *) exception,
1487 : (PyTypeObject *) PyExc_ImportError))
1488 19007 : always_trim = 1;
1489 :
1490 19112 : prev_link = &base_tb;
1491 19112 : tb = base_tb;
1492 61907 : while (tb != NULL) {
1493 42795 : PyTracebackObject *traceback = (PyTracebackObject *)tb;
1494 42795 : PyObject *next = (PyObject *) traceback->tb_next;
1495 42795 : PyFrameObject *frame = traceback->tb_frame;
1496 42795 : PyCodeObject *code = PyFrame_GetCode(frame);
1497 : int now_in_importlib;
1498 :
1499 42795 : assert(PyTraceBack_Check(tb));
1500 43108 : now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
1501 313 : _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
1502 42795 : if (now_in_importlib && !in_importlib) {
1503 : /* This is the link to this chunk of importlib tracebacks */
1504 19082 : outer_link = prev_link;
1505 : }
1506 42795 : in_importlib = now_in_importlib;
1507 :
1508 42795 : if (in_importlib &&
1509 391 : (always_trim ||
1510 391 : _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
1511 42345 : Py_XINCREF(next);
1512 42345 : Py_XSETREF(*outer_link, next);
1513 42345 : prev_link = outer_link;
1514 : }
1515 : else {
1516 450 : prev_link = (PyObject **) &traceback->tb_next;
1517 : }
1518 42795 : Py_DECREF(code);
1519 42795 : tb = next;
1520 : }
1521 19112 : done:
1522 19135 : _PyErr_Restore(tstate, exception, value, base_tb);
1523 19135 : }
1524 :
1525 :
1526 : static PyObject *
1527 163953 : resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
1528 : {
1529 : PyObject *abs_name;
1530 163953 : PyObject *package = NULL;
1531 : PyObject *spec;
1532 : Py_ssize_t last_dot;
1533 : PyObject *base;
1534 : int level_up;
1535 :
1536 163953 : if (globals == NULL) {
1537 1 : _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
1538 1 : goto error;
1539 : }
1540 163952 : if (!PyDict_Check(globals)) {
1541 0 : _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
1542 0 : goto error;
1543 : }
1544 163952 : package = PyDict_GetItemWithError(globals, &_Py_ID(__package__));
1545 163952 : if (package == Py_None) {
1546 4 : package = NULL;
1547 : }
1548 163948 : else if (package == NULL && _PyErr_Occurred(tstate)) {
1549 0 : goto error;
1550 : }
1551 163952 : spec = PyDict_GetItemWithError(globals, &_Py_ID(__spec__));
1552 163952 : if (spec == NULL && _PyErr_Occurred(tstate)) {
1553 0 : goto error;
1554 : }
1555 :
1556 163952 : if (package != NULL) {
1557 163934 : Py_INCREF(package);
1558 163934 : if (!PyUnicode_Check(package)) {
1559 3 : _PyErr_SetString(tstate, PyExc_TypeError,
1560 : "package must be a string");
1561 3 : goto error;
1562 : }
1563 163931 : else if (spec != NULL && spec != Py_None) {
1564 : int equal;
1565 163911 : PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
1566 163911 : if (parent == NULL) {
1567 0 : goto error;
1568 : }
1569 :
1570 163911 : equal = PyObject_RichCompareBool(package, parent, Py_EQ);
1571 163911 : Py_DECREF(parent);
1572 163911 : if (equal < 0) {
1573 0 : goto error;
1574 : }
1575 163911 : else if (equal == 0) {
1576 2 : if (PyErr_WarnEx(PyExc_ImportWarning,
1577 : "__package__ != __spec__.parent", 1) < 0) {
1578 0 : goto error;
1579 : }
1580 : }
1581 : }
1582 : }
1583 18 : else if (spec != NULL && spec != Py_None) {
1584 2 : package = PyObject_GetAttr(spec, &_Py_ID(parent));
1585 2 : if (package == NULL) {
1586 0 : goto error;
1587 : }
1588 2 : else if (!PyUnicode_Check(package)) {
1589 0 : _PyErr_SetString(tstate, PyExc_TypeError,
1590 : "__spec__.parent must be a string");
1591 0 : goto error;
1592 : }
1593 : }
1594 : else {
1595 16 : if (PyErr_WarnEx(PyExc_ImportWarning,
1596 : "can't resolve package from __spec__ or __package__, "
1597 : "falling back on __name__ and __path__", 1) < 0) {
1598 0 : goto error;
1599 : }
1600 :
1601 16 : package = PyDict_GetItemWithError(globals, &_Py_ID(__name__));
1602 16 : if (package == NULL) {
1603 0 : if (!_PyErr_Occurred(tstate)) {
1604 0 : _PyErr_SetString(tstate, PyExc_KeyError,
1605 : "'__name__' not in globals");
1606 : }
1607 0 : goto error;
1608 : }
1609 :
1610 16 : Py_INCREF(package);
1611 16 : if (!PyUnicode_Check(package)) {
1612 0 : _PyErr_SetString(tstate, PyExc_TypeError,
1613 : "__name__ must be a string");
1614 0 : goto error;
1615 : }
1616 :
1617 16 : int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
1618 16 : if (haspath < 0) {
1619 0 : goto error;
1620 : }
1621 16 : if (!haspath) {
1622 : Py_ssize_t dot;
1623 :
1624 6 : if (PyUnicode_READY(package) < 0) {
1625 0 : goto error;
1626 : }
1627 :
1628 6 : dot = PyUnicode_FindChar(package, '.',
1629 : 0, PyUnicode_GET_LENGTH(package), -1);
1630 6 : if (dot == -2) {
1631 0 : goto error;
1632 : }
1633 6 : else if (dot == -1) {
1634 2 : goto no_parent_error;
1635 : }
1636 4 : PyObject *substr = PyUnicode_Substring(package, 0, dot);
1637 4 : if (substr == NULL) {
1638 0 : goto error;
1639 : }
1640 4 : Py_SETREF(package, substr);
1641 : }
1642 : }
1643 :
1644 163947 : last_dot = PyUnicode_GET_LENGTH(package);
1645 163947 : if (last_dot == 0) {
1646 3 : goto no_parent_error;
1647 : }
1648 :
1649 164663 : for (level_up = 1; level_up < level; level_up += 1) {
1650 723 : last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
1651 723 : if (last_dot == -2) {
1652 0 : goto error;
1653 : }
1654 723 : else if (last_dot == -1) {
1655 4 : _PyErr_SetString(tstate, PyExc_ImportError,
1656 : "attempted relative import beyond top-level "
1657 : "package");
1658 4 : goto error;
1659 : }
1660 : }
1661 :
1662 163940 : base = PyUnicode_Substring(package, 0, last_dot);
1663 163940 : Py_DECREF(package);
1664 163940 : if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
1665 66085 : return base;
1666 : }
1667 :
1668 97855 : abs_name = PyUnicode_FromFormat("%U.%U", base, name);
1669 97855 : Py_DECREF(base);
1670 97855 : return abs_name;
1671 :
1672 5 : no_parent_error:
1673 5 : _PyErr_SetString(tstate, PyExc_ImportError,
1674 : "attempted relative import "
1675 : "with no known parent package");
1676 :
1677 13 : error:
1678 13 : Py_XDECREF(package);
1679 13 : return NULL;
1680 : }
1681 :
1682 : static PyObject *
1683 302363 : import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
1684 : {
1685 302363 : PyObject *mod = NULL;
1686 302363 : PyInterpreterState *interp = tstate->interp;
1687 302363 : int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
1688 : static int import_level;
1689 : static _PyTime_t accumulated;
1690 :
1691 302363 : _PyTime_t t1 = 0, accumulated_copy = accumulated;
1692 :
1693 302363 : PyObject *sys_path = PySys_GetObject("path");
1694 302363 : PyObject *sys_meta_path = PySys_GetObject("meta_path");
1695 302363 : PyObject *sys_path_hooks = PySys_GetObject("path_hooks");
1696 302363 : if (_PySys_Audit(tstate, "import", "OOOOO",
1697 : abs_name, Py_None, sys_path ? sys_path : Py_None,
1698 : sys_meta_path ? sys_meta_path : Py_None,
1699 : sys_path_hooks ? sys_path_hooks : Py_None) < 0) {
1700 0 : return NULL;
1701 : }
1702 :
1703 :
1704 : /* XOptions is initialized after first some imports.
1705 : * So we can't have negative cache before completed initialization.
1706 : * Anyway, importlib._find_and_load is much slower than
1707 : * _PyDict_GetItemIdWithError().
1708 : */
1709 302363 : if (import_time) {
1710 : static int header = 1;
1711 247 : if (header) {
1712 4 : fputs("import time: self [us] | cumulative | imported package\n",
1713 : stderr);
1714 4 : header = 0;
1715 : }
1716 :
1717 247 : import_level++;
1718 247 : t1 = _PyTime_GetPerfCounter();
1719 247 : accumulated = 0;
1720 : }
1721 :
1722 302363 : if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
1723 0 : PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
1724 :
1725 302363 : mod = PyObject_CallMethodObjArgs(interp->importlib, &_Py_ID(_find_and_load),
1726 : abs_name, interp->import_func, NULL);
1727 :
1728 302363 : if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
1729 0 : PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
1730 : mod != NULL);
1731 :
1732 302363 : if (import_time) {
1733 247 : _PyTime_t cum = _PyTime_GetPerfCounter() - t1;
1734 :
1735 247 : import_level--;
1736 494 : fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
1737 247 : (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
1738 247 : (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
1739 : import_level*2, "", PyUnicode_AsUTF8(abs_name));
1740 :
1741 247 : accumulated = accumulated_copy + cum;
1742 : }
1743 :
1744 302363 : return mod;
1745 : }
1746 :
1747 : PyObject *
1748 93242 : PyImport_GetModule(PyObject *name)
1749 : {
1750 93242 : PyThreadState *tstate = _PyThreadState_GET();
1751 : PyObject *mod;
1752 :
1753 93242 : mod = import_get_module(tstate, name);
1754 93242 : if (mod != NULL && mod != Py_None) {
1755 86629 : if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
1756 0 : Py_DECREF(mod);
1757 0 : remove_importlib_frames(tstate);
1758 0 : return NULL;
1759 : }
1760 : }
1761 93242 : return mod;
1762 : }
1763 :
1764 : PyObject *
1765 2230170 : PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
1766 : PyObject *locals, PyObject *fromlist,
1767 : int level)
1768 : {
1769 2230170 : PyThreadState *tstate = _PyThreadState_GET();
1770 2230170 : PyObject *abs_name = NULL;
1771 2230170 : PyObject *final_mod = NULL;
1772 2230170 : PyObject *mod = NULL;
1773 2230170 : PyObject *package = NULL;
1774 2230170 : PyInterpreterState *interp = tstate->interp;
1775 : int has_from;
1776 :
1777 2230170 : if (name == NULL) {
1778 0 : _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
1779 0 : goto error;
1780 : }
1781 :
1782 : /* The below code is importlib.__import__() & _gcd_import(), ported to C
1783 : for added performance. */
1784 :
1785 2230170 : if (!PyUnicode_Check(name)) {
1786 3 : _PyErr_SetString(tstate, PyExc_TypeError,
1787 : "module name must be a string");
1788 3 : goto error;
1789 : }
1790 2230160 : if (PyUnicode_READY(name) < 0) {
1791 0 : goto error;
1792 : }
1793 2230160 : if (level < 0) {
1794 2 : _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
1795 2 : goto error;
1796 : }
1797 :
1798 2230160 : if (level > 0) {
1799 163953 : abs_name = resolve_name(tstate, name, globals, level);
1800 163953 : if (abs_name == NULL)
1801 13 : goto error;
1802 : }
1803 : else { /* level == 0 */
1804 2066210 : if (PyUnicode_GET_LENGTH(name) == 0) {
1805 12 : _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
1806 12 : goto error;
1807 : }
1808 2066200 : abs_name = name;
1809 2066200 : Py_INCREF(abs_name);
1810 : }
1811 :
1812 2230140 : mod = import_get_module(tstate, abs_name);
1813 2230140 : if (mod == NULL && _PyErr_Occurred(tstate)) {
1814 0 : goto error;
1815 : }
1816 :
1817 2230140 : if (mod != NULL && mod != Py_None) {
1818 1927770 : if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
1819 0 : goto error;
1820 : }
1821 : }
1822 : else {
1823 302363 : Py_XDECREF(mod);
1824 302363 : mod = import_find_and_load(tstate, abs_name);
1825 302363 : if (mod == NULL) {
1826 19085 : goto error;
1827 : }
1828 : }
1829 :
1830 2211050 : has_from = 0;
1831 2211050 : if (fromlist != NULL && fromlist != Py_None) {
1832 1147340 : has_from = PyObject_IsTrue(fromlist);
1833 1147340 : if (has_from < 0)
1834 0 : goto error;
1835 : }
1836 2211050 : if (!has_from) {
1837 1658710 : Py_ssize_t len = PyUnicode_GET_LENGTH(name);
1838 1754700 : if (level == 0 || len > 0) {
1839 : Py_ssize_t dot;
1840 :
1841 1658710 : dot = PyUnicode_FindChar(name, '.', 0, len, 1);
1842 1658710 : if (dot == -2) {
1843 0 : goto error;
1844 : }
1845 :
1846 1658710 : if (dot == -1) {
1847 : /* No dot in module name, simple exit */
1848 1562720 : final_mod = mod;
1849 1562720 : Py_INCREF(mod);
1850 1562720 : goto error;
1851 : }
1852 :
1853 95990 : if (level == 0) {
1854 95990 : PyObject *front = PyUnicode_Substring(name, 0, dot);
1855 95990 : if (front == NULL) {
1856 0 : goto error;
1857 : }
1858 :
1859 95990 : final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
1860 95990 : Py_DECREF(front);
1861 : }
1862 : else {
1863 0 : Py_ssize_t cut_off = len - dot;
1864 0 : Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
1865 0 : PyObject *to_return = PyUnicode_Substring(abs_name, 0,
1866 : abs_name_len - cut_off);
1867 0 : if (to_return == NULL) {
1868 0 : goto error;
1869 : }
1870 :
1871 0 : final_mod = import_get_module(tstate, to_return);
1872 0 : Py_DECREF(to_return);
1873 0 : if (final_mod == NULL) {
1874 0 : if (!_PyErr_Occurred(tstate)) {
1875 0 : _PyErr_Format(tstate, PyExc_KeyError,
1876 : "%R not in sys.modules as expected",
1877 : to_return);
1878 : }
1879 0 : goto error;
1880 : }
1881 : }
1882 : }
1883 : else {
1884 0 : final_mod = mod;
1885 0 : Py_INCREF(mod);
1886 : }
1887 : }
1888 : else {
1889 : PyObject *path;
1890 552339 : if (_PyObject_LookupAttr(mod, &_Py_ID(__path__), &path) < 0) {
1891 0 : goto error;
1892 : }
1893 552339 : if (path) {
1894 109124 : Py_DECREF(path);
1895 109124 : final_mod = PyObject_CallMethodObjArgs(
1896 : interp->importlib, &_Py_ID(_handle_fromlist),
1897 : mod, fromlist, interp->import_func, NULL);
1898 : }
1899 : else {
1900 443215 : final_mod = mod;
1901 443215 : Py_INCREF(mod);
1902 : }
1903 : }
1904 :
1905 2230170 : error:
1906 2230170 : Py_XDECREF(abs_name);
1907 2230170 : Py_XDECREF(mod);
1908 2230170 : Py_XDECREF(package);
1909 2230170 : if (final_mod == NULL) {
1910 19135 : remove_importlib_frames(tstate);
1911 : }
1912 2230170 : return final_mod;
1913 : }
1914 :
1915 : PyObject *
1916 28068 : PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
1917 : PyObject *fromlist, int level)
1918 : {
1919 : PyObject *nameobj, *mod;
1920 28068 : nameobj = PyUnicode_FromString(name);
1921 28068 : if (nameobj == NULL)
1922 0 : return NULL;
1923 28068 : mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
1924 : fromlist, level);
1925 28068 : Py_DECREF(nameobj);
1926 28068 : return mod;
1927 : }
1928 :
1929 :
1930 : /* Re-import a module of any kind and return its module object, WITH
1931 : INCREMENTED REFERENCE COUNT */
1932 :
1933 : PyObject *
1934 0 : PyImport_ReloadModule(PyObject *m)
1935 : {
1936 0 : PyObject *reloaded_module = NULL;
1937 0 : PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
1938 0 : if (importlib == NULL) {
1939 0 : if (PyErr_Occurred()) {
1940 0 : return NULL;
1941 : }
1942 :
1943 0 : importlib = PyImport_ImportModule("importlib");
1944 0 : if (importlib == NULL) {
1945 0 : return NULL;
1946 : }
1947 : }
1948 :
1949 0 : reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
1950 0 : Py_DECREF(importlib);
1951 0 : return reloaded_module;
1952 : }
1953 :
1954 :
1955 : /* Higher-level import emulator which emulates the "import" statement
1956 : more accurately -- it invokes the __import__() function from the
1957 : builtins of the current globals. This means that the import is
1958 : done using whatever import hooks are installed in the current
1959 : environment.
1960 : A dummy list ["__doc__"] is passed as the 4th argument so that
1961 : e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
1962 : will return <module "gencache"> instead of <module "win32com">. */
1963 :
1964 : PyObject *
1965 595016 : PyImport_Import(PyObject *module_name)
1966 : {
1967 595016 : PyThreadState *tstate = _PyThreadState_GET();
1968 595016 : PyObject *globals = NULL;
1969 595016 : PyObject *import = NULL;
1970 595016 : PyObject *builtins = NULL;
1971 595016 : PyObject *r = NULL;
1972 :
1973 595016 : PyObject *from_list = PyList_New(0);
1974 595016 : if (from_list == NULL) {
1975 0 : goto err;
1976 : }
1977 :
1978 : /* Get the builtins from current globals */
1979 595016 : globals = PyEval_GetGlobals();
1980 595016 : if (globals != NULL) {
1981 566948 : Py_INCREF(globals);
1982 566948 : builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
1983 566948 : if (builtins == NULL)
1984 0 : goto err;
1985 : }
1986 : else {
1987 : /* No globals -- use standard builtins, and fake globals */
1988 28068 : builtins = PyImport_ImportModuleLevel("builtins",
1989 : NULL, NULL, NULL, 0);
1990 28068 : if (builtins == NULL) {
1991 6 : goto err;
1992 : }
1993 28062 : globals = Py_BuildValue("{OO}", &_Py_ID(__builtins__), builtins);
1994 28062 : if (globals == NULL)
1995 0 : goto err;
1996 : }
1997 :
1998 : /* Get the __import__ function from the builtins */
1999 595010 : if (PyDict_Check(builtins)) {
2000 565795 : import = PyObject_GetItem(builtins, &_Py_ID(__import__));
2001 565795 : if (import == NULL) {
2002 0 : _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
2003 : }
2004 : }
2005 : else
2006 29215 : import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
2007 595010 : if (import == NULL)
2008 0 : goto err;
2009 :
2010 : /* Call the __import__ function with the proper argument list
2011 : Always use absolute import here.
2012 : Calling for side-effect of import. */
2013 595010 : r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2014 : globals, from_list, 0, NULL);
2015 595010 : if (r == NULL)
2016 10 : goto err;
2017 595000 : Py_DECREF(r);
2018 :
2019 595000 : r = import_get_module(tstate, module_name);
2020 595000 : if (r == NULL && !_PyErr_Occurred(tstate)) {
2021 0 : _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
2022 : }
2023 :
2024 595000 : err:
2025 595016 : Py_XDECREF(globals);
2026 595016 : Py_XDECREF(builtins);
2027 595016 : Py_XDECREF(import);
2028 595016 : Py_XDECREF(from_list);
2029 :
2030 595016 : return r;
2031 : }
2032 :
2033 : /*[clinic input]
2034 : _imp.extension_suffixes
2035 :
2036 : Returns the list of file suffixes used to identify extension modules.
2037 : [clinic start generated code]*/
2038 :
2039 : static PyObject *
2040 6387 : _imp_extension_suffixes_impl(PyObject *module)
2041 : /*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
2042 : {
2043 : PyObject *list;
2044 :
2045 6387 : list = PyList_New(0);
2046 6387 : if (list == NULL)
2047 0 : return NULL;
2048 : #ifdef HAVE_DYNAMIC_LOADING
2049 : const char *suffix;
2050 6387 : unsigned int index = 0;
2051 :
2052 31935 : while ((suffix = _PyImport_DynLoadFiletab[index])) {
2053 25548 : PyObject *item = PyUnicode_FromString(suffix);
2054 25548 : if (item == NULL) {
2055 0 : Py_DECREF(list);
2056 0 : return NULL;
2057 : }
2058 25548 : if (PyList_Append(list, item) < 0) {
2059 0 : Py_DECREF(list);
2060 0 : Py_DECREF(item);
2061 0 : return NULL;
2062 : }
2063 25548 : Py_DECREF(item);
2064 25548 : index += 1;
2065 : }
2066 : #endif
2067 6387 : return list;
2068 : }
2069 :
2070 : /*[clinic input]
2071 : _imp.init_frozen
2072 :
2073 : name: unicode
2074 : /
2075 :
2076 : Initializes a frozen module.
2077 : [clinic start generated code]*/
2078 :
2079 : static PyObject *
2080 0 : _imp_init_frozen_impl(PyObject *module, PyObject *name)
2081 : /*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
2082 : {
2083 0 : PyThreadState *tstate = _PyThreadState_GET();
2084 : int ret;
2085 :
2086 0 : ret = PyImport_ImportFrozenModuleObject(name);
2087 0 : if (ret < 0)
2088 0 : return NULL;
2089 0 : if (ret == 0) {
2090 0 : Py_RETURN_NONE;
2091 : }
2092 0 : return import_add_module(tstate, name);
2093 : }
2094 :
2095 : /*[clinic input]
2096 : _imp.find_frozen
2097 :
2098 : name: unicode
2099 : /
2100 : *
2101 : withdata: bool = False
2102 :
2103 : Return info about the corresponding frozen module (if there is one) or None.
2104 :
2105 : The returned info (a 2-tuple):
2106 :
2107 : * data the raw marshalled bytes
2108 : * is_package whether or not it is a package
2109 : * origname the originally frozen module's name, or None if not
2110 : a stdlib module (this will usually be the same as
2111 : the module's current name)
2112 : [clinic start generated code]*/
2113 :
2114 : static PyObject *
2115 258254 : _imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
2116 : /*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
2117 : {
2118 : struct frozen_info info;
2119 258254 : frozen_status status = find_frozen(name, &info);
2120 258254 : if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
2121 251805 : Py_RETURN_NONE;
2122 : }
2123 6449 : else if (status == FROZEN_BAD_NAME) {
2124 1 : Py_RETURN_NONE;
2125 : }
2126 6448 : else if (status != FROZEN_OKAY) {
2127 0 : set_frozen_error(status, name);
2128 0 : return NULL;
2129 : }
2130 :
2131 6448 : PyObject *data = NULL;
2132 6448 : if (withdata) {
2133 0 : data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
2134 0 : if (data == NULL) {
2135 0 : return NULL;
2136 : }
2137 : }
2138 :
2139 6448 : PyObject *origname = NULL;
2140 6448 : if (info.origname != NULL && info.origname[0] != '\0') {
2141 6445 : origname = PyUnicode_FromString(info.origname);
2142 6445 : if (origname == NULL) {
2143 0 : Py_DECREF(data);
2144 0 : return NULL;
2145 : }
2146 : }
2147 :
2148 12896 : PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
2149 6448 : info.is_package ? Py_True : Py_False,
2150 : origname ? origname : Py_None);
2151 6448 : Py_XDECREF(origname);
2152 6448 : Py_XDECREF(data);
2153 6448 : return result;
2154 : }
2155 :
2156 : /*[clinic input]
2157 : _imp.get_frozen_object
2158 :
2159 : name: unicode
2160 : data as dataobj: object = None
2161 : /
2162 :
2163 : Create a code object for a frozen module.
2164 : [clinic start generated code]*/
2165 :
2166 : static PyObject *
2167 6356 : _imp_get_frozen_object_impl(PyObject *module, PyObject *name,
2168 : PyObject *dataobj)
2169 : /*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
2170 : {
2171 6356 : struct frozen_info info = {0};
2172 6356 : Py_buffer buf = {0};
2173 6356 : if (PyObject_CheckBuffer(dataobj)) {
2174 0 : if (PyObject_GetBuffer(dataobj, &buf, PyBUF_READ) != 0) {
2175 0 : return NULL;
2176 : }
2177 0 : info.data = (const char *)buf.buf;
2178 0 : info.size = buf.len;
2179 : }
2180 6356 : else if (dataobj != Py_None) {
2181 0 : _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
2182 0 : return NULL;
2183 : }
2184 : else {
2185 6356 : frozen_status status = find_frozen(name, &info);
2186 6356 : if (status != FROZEN_OKAY) {
2187 2 : set_frozen_error(status, name);
2188 2 : return NULL;
2189 : }
2190 : }
2191 :
2192 6354 : if (info.nameobj == NULL) {
2193 0 : info.nameobj = name;
2194 : }
2195 6354 : if (info.size == 0 && info.get_code == NULL) {
2196 : /* Does not contain executable code. */
2197 0 : set_frozen_error(FROZEN_INVALID, name);
2198 0 : return NULL;
2199 : }
2200 :
2201 6354 : PyObject *codeobj = unmarshal_frozen_code(&info);
2202 6354 : if (dataobj != Py_None) {
2203 0 : PyBuffer_Release(&buf);
2204 : }
2205 6354 : return codeobj;
2206 : }
2207 :
2208 : /*[clinic input]
2209 : _imp.is_frozen_package
2210 :
2211 : name: unicode
2212 : /
2213 :
2214 : Returns True if the module name is of a frozen package.
2215 : [clinic start generated code]*/
2216 :
2217 : static PyObject *
2218 3170 : _imp_is_frozen_package_impl(PyObject *module, PyObject *name)
2219 : /*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
2220 : {
2221 : struct frozen_info info;
2222 3170 : frozen_status status = find_frozen(name, &info);
2223 3170 : if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
2224 0 : set_frozen_error(status, name);
2225 0 : return NULL;
2226 : }
2227 3170 : return PyBool_FromLong(info.is_package);
2228 : }
2229 :
2230 : /*[clinic input]
2231 : _imp.is_builtin
2232 :
2233 : name: unicode
2234 : /
2235 :
2236 : Returns True if the module name corresponds to a built-in module.
2237 : [clinic start generated code]*/
2238 :
2239 : static PyObject *
2240 232387 : _imp_is_builtin_impl(PyObject *module, PyObject *name)
2241 : /*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
2242 : {
2243 232387 : return PyLong_FromLong(is_builtin(name));
2244 : }
2245 :
2246 : /*[clinic input]
2247 : _imp.is_frozen
2248 :
2249 : name: unicode
2250 : /
2251 :
2252 : Returns True if the module name corresponds to a frozen module.
2253 : [clinic start generated code]*/
2254 :
2255 : static PyObject *
2256 11463 : _imp_is_frozen_impl(PyObject *module, PyObject *name)
2257 : /*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
2258 : {
2259 : struct frozen_info info;
2260 11463 : frozen_status status = find_frozen(name, &info);
2261 11463 : if (status != FROZEN_OKAY) {
2262 8252 : Py_RETURN_FALSE;
2263 : }
2264 3211 : Py_RETURN_TRUE;
2265 : }
2266 :
2267 : /*[clinic input]
2268 : _imp._frozen_module_names
2269 :
2270 : Returns the list of available frozen modules.
2271 : [clinic start generated code]*/
2272 :
2273 : static PyObject *
2274 1 : _imp__frozen_module_names_impl(PyObject *module)
2275 : /*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
2276 : {
2277 1 : return list_frozen_module_names();
2278 : }
2279 :
2280 : /*[clinic input]
2281 : _imp._override_frozen_modules_for_tests
2282 :
2283 : override: int
2284 : /
2285 :
2286 : (internal-only) Override PyConfig.use_frozen_modules.
2287 :
2288 : (-1: "off", 1: "on", 0: no override)
2289 : See frozen_modules() in Lib/test/support/import_helper.py.
2290 : [clinic start generated code]*/
2291 :
2292 : static PyObject *
2293 772 : _imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
2294 : /*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
2295 : {
2296 772 : PyInterpreterState *interp = _PyInterpreterState_GET();
2297 772 : interp->override_frozen_modules = override;
2298 772 : Py_RETURN_NONE;
2299 : }
2300 :
2301 : /* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
2302 : static int
2303 86202 : exec_builtin_or_dynamic(PyObject *mod) {
2304 : PyModuleDef *def;
2305 : void *state;
2306 :
2307 86202 : if (!PyModule_Check(mod)) {
2308 4 : return 0;
2309 : }
2310 :
2311 86198 : def = PyModule_GetDef(mod);
2312 86198 : if (def == NULL) {
2313 51 : return 0;
2314 : }
2315 :
2316 86147 : state = PyModule_GetState(mod);
2317 86147 : if (state) {
2318 : /* Already initialized; skip reload */
2319 4001 : return 0;
2320 : }
2321 :
2322 82146 : return PyModule_ExecDef(mod, def);
2323 : }
2324 :
2325 : #ifdef HAVE_DYNAMIC_LOADING
2326 :
2327 : /*[clinic input]
2328 : _imp.create_dynamic
2329 :
2330 : spec: object
2331 : file: object = NULL
2332 : /
2333 :
2334 : Create an extension module.
2335 : [clinic start generated code]*/
2336 :
2337 : static PyObject *
2338 29466 : _imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
2339 : /*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
2340 : {
2341 : PyObject *mod, *name, *path;
2342 : FILE *fp;
2343 :
2344 29466 : name = PyObject_GetAttrString(spec, "name");
2345 29466 : if (name == NULL) {
2346 0 : return NULL;
2347 : }
2348 :
2349 29466 : path = PyObject_GetAttrString(spec, "origin");
2350 29466 : if (path == NULL) {
2351 0 : Py_DECREF(name);
2352 0 : return NULL;
2353 : }
2354 :
2355 29466 : PyThreadState *tstate = _PyThreadState_GET();
2356 29466 : mod = import_find_extension(tstate, name, path);
2357 29466 : if (mod != NULL || PyErr_Occurred()) {
2358 62 : Py_DECREF(name);
2359 62 : Py_DECREF(path);
2360 62 : return mod;
2361 : }
2362 :
2363 29404 : if (file != NULL) {
2364 0 : fp = _Py_fopen_obj(path, "r");
2365 0 : if (fp == NULL) {
2366 0 : Py_DECREF(name);
2367 0 : Py_DECREF(path);
2368 0 : return NULL;
2369 : }
2370 : }
2371 : else
2372 29404 : fp = NULL;
2373 :
2374 29404 : mod = _PyImport_LoadDynamicModuleWithSpec(spec, fp);
2375 :
2376 29404 : Py_DECREF(name);
2377 29404 : Py_DECREF(path);
2378 29404 : if (fp)
2379 0 : fclose(fp);
2380 29404 : return mod;
2381 : }
2382 :
2383 : /*[clinic input]
2384 : _imp.exec_dynamic -> int
2385 :
2386 : mod: object
2387 : /
2388 :
2389 : Initialize an extension module.
2390 : [clinic start generated code]*/
2391 :
2392 : static int
2393 29394 : _imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
2394 : /*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
2395 : {
2396 29394 : return exec_builtin_or_dynamic(mod);
2397 : }
2398 :
2399 :
2400 : #endif /* HAVE_DYNAMIC_LOADING */
2401 :
2402 : /*[clinic input]
2403 : _imp.exec_builtin -> int
2404 :
2405 : mod: object
2406 : /
2407 :
2408 : Initialize a built-in module.
2409 : [clinic start generated code]*/
2410 :
2411 : static int
2412 53678 : _imp_exec_builtin_impl(PyObject *module, PyObject *mod)
2413 : /*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
2414 : {
2415 53678 : return exec_builtin_or_dynamic(mod);
2416 : }
2417 :
2418 : /*[clinic input]
2419 : _imp.source_hash
2420 :
2421 : key: long
2422 : source: Py_buffer
2423 : [clinic start generated code]*/
2424 :
2425 : static PyObject *
2426 665 : _imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
2427 : /*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
2428 : {
2429 : union {
2430 : uint64_t x;
2431 : char data[sizeof(uint64_t)];
2432 : } hash;
2433 665 : hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
2434 : #if !PY_LITTLE_ENDIAN
2435 : // Force to little-endian. There really ought to be a succinct standard way
2436 : // to do this.
2437 : for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
2438 : char tmp = hash.data[i];
2439 : hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
2440 : hash.data[sizeof(hash.data) - i - 1] = tmp;
2441 : }
2442 : #endif
2443 665 : return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
2444 : }
2445 :
2446 :
2447 : PyDoc_STRVAR(doc_imp,
2448 : "(Extremely) low-level import machinery bits as used by importlib and imp.");
2449 :
2450 : static PyMethodDef imp_methods[] = {
2451 : _IMP_EXTENSION_SUFFIXES_METHODDEF
2452 : _IMP_LOCK_HELD_METHODDEF
2453 : _IMP_ACQUIRE_LOCK_METHODDEF
2454 : _IMP_RELEASE_LOCK_METHODDEF
2455 : _IMP_FIND_FROZEN_METHODDEF
2456 : _IMP_GET_FROZEN_OBJECT_METHODDEF
2457 : _IMP_IS_FROZEN_PACKAGE_METHODDEF
2458 : _IMP_CREATE_BUILTIN_METHODDEF
2459 : _IMP_INIT_FROZEN_METHODDEF
2460 : _IMP_IS_BUILTIN_METHODDEF
2461 : _IMP_IS_FROZEN_METHODDEF
2462 : _IMP__FROZEN_MODULE_NAMES_METHODDEF
2463 : _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
2464 : _IMP_CREATE_DYNAMIC_METHODDEF
2465 : _IMP_EXEC_DYNAMIC_METHODDEF
2466 : _IMP_EXEC_BUILTIN_METHODDEF
2467 : _IMP__FIX_CO_FILENAME_METHODDEF
2468 : _IMP_SOURCE_HASH_METHODDEF
2469 : {NULL, NULL} /* sentinel */
2470 : };
2471 :
2472 :
2473 : static int
2474 3130 : imp_module_exec(PyObject *module)
2475 : {
2476 3130 : const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
2477 3130 : PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
2478 3130 : if (pyc_mode == NULL) {
2479 0 : return -1;
2480 : }
2481 3130 : if (PyModule_AddObjectRef(module, "check_hash_based_pycs", pyc_mode) < 0) {
2482 0 : Py_DECREF(pyc_mode);
2483 0 : return -1;
2484 : }
2485 3130 : Py_DECREF(pyc_mode);
2486 :
2487 3130 : return 0;
2488 : }
2489 :
2490 :
2491 : static PyModuleDef_Slot imp_slots[] = {
2492 : {Py_mod_exec, imp_module_exec},
2493 : {0, NULL}
2494 : };
2495 :
2496 : static struct PyModuleDef imp_module = {
2497 : PyModuleDef_HEAD_INIT,
2498 : .m_name = "_imp",
2499 : .m_doc = doc_imp,
2500 : .m_size = 0,
2501 : .m_methods = imp_methods,
2502 : .m_slots = imp_slots,
2503 : };
2504 :
2505 : PyMODINIT_FUNC
2506 3130 : PyInit__imp(void)
2507 : {
2508 3130 : return PyModuleDef_Init(&imp_module);
2509 : }
2510 :
2511 :
2512 : // Import the _imp extension by calling manually _imp.create_builtin() and
2513 : // _imp.exec_builtin() since importlib is not initialized yet. Initializing
2514 : // importlib requires the _imp module: this function fix the bootstrap issue.
2515 : PyObject*
2516 3130 : _PyImport_BootstrapImp(PyThreadState *tstate)
2517 : {
2518 3130 : PyObject *name = PyUnicode_FromString("_imp");
2519 3130 : if (name == NULL) {
2520 0 : return NULL;
2521 : }
2522 :
2523 : // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
2524 : // an object with just a name attribute.
2525 : //
2526 : // _imp.__spec__ is overridden by importlib._bootstrap._instal() anyway.
2527 3130 : PyObject *attrs = Py_BuildValue("{sO}", "name", name);
2528 3130 : if (attrs == NULL) {
2529 0 : goto error;
2530 : }
2531 3130 : PyObject *spec = _PyNamespace_New(attrs);
2532 3130 : Py_DECREF(attrs);
2533 3130 : if (spec == NULL) {
2534 0 : goto error;
2535 : }
2536 :
2537 : // Create the _imp module from its definition.
2538 3130 : PyObject *mod = create_builtin(tstate, name, spec);
2539 3130 : Py_CLEAR(name);
2540 3130 : Py_DECREF(spec);
2541 3130 : if (mod == NULL) {
2542 0 : goto error;
2543 : }
2544 3130 : assert(mod != Py_None); // not found
2545 :
2546 : // Execute the _imp module: call imp_module_exec().
2547 3130 : if (exec_builtin_or_dynamic(mod) < 0) {
2548 0 : Py_DECREF(mod);
2549 0 : goto error;
2550 : }
2551 3130 : return mod;
2552 :
2553 0 : error:
2554 0 : Py_XDECREF(name);
2555 0 : return NULL;
2556 : }
2557 :
2558 :
2559 : /* API for embedding applications that want to add their own entries
2560 : to the table of built-in modules. This should normally be called
2561 : *before* Py_Initialize(). When the table resize fails, -1 is
2562 : returned and the existing table is unchanged.
2563 :
2564 : After a similar function by Just van Rossum. */
2565 :
2566 : int
2567 4 : PyImport_ExtendInittab(struct _inittab *newtab)
2568 : {
2569 : struct _inittab *p;
2570 : size_t i, n;
2571 4 : int res = 0;
2572 :
2573 : /* Count the number of entries in both tables */
2574 8 : for (n = 0; newtab[n].name != NULL; n++)
2575 : ;
2576 4 : if (n == 0)
2577 0 : return 0; /* Nothing to do */
2578 128 : for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2579 : ;
2580 :
2581 : /* Force default raw memory allocator to get a known allocator to be able
2582 : to release the memory in _PyImport_Fini2() */
2583 : PyMemAllocatorEx old_alloc;
2584 4 : _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2585 :
2586 : /* Allocate new memory for the combined table */
2587 4 : p = NULL;
2588 4 : if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
2589 4 : size_t size = sizeof(struct _inittab) * (i + n + 1);
2590 4 : p = PyMem_RawRealloc(inittab_copy, size);
2591 : }
2592 4 : if (p == NULL) {
2593 0 : res = -1;
2594 0 : goto done;
2595 : }
2596 :
2597 : /* Copy the tables into the new memory at the first call
2598 : to PyImport_ExtendInittab(). */
2599 4 : if (inittab_copy != PyImport_Inittab) {
2600 4 : memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2601 : }
2602 4 : memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2603 4 : PyImport_Inittab = inittab_copy = p;
2604 :
2605 4 : done:
2606 4 : PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2607 4 : return res;
2608 : }
2609 :
2610 : /* Shorthand to add a single entry given a name and a function */
2611 :
2612 : int
2613 4 : PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
2614 : {
2615 : struct _inittab newtab[2];
2616 :
2617 4 : memset(newtab, '\0', sizeof newtab);
2618 :
2619 4 : newtab[0].name = name;
2620 4 : newtab[0].initfunc = initfunc;
2621 :
2622 4 : return PyImport_ExtendInittab(newtab);
2623 : }
2624 :
2625 :
2626 : PyObject *
2627 278433 : _PyImport_GetModuleAttr(PyObject *modname, PyObject *attrname)
2628 : {
2629 278433 : PyObject *mod = PyImport_Import(modname);
2630 278433 : if (mod == NULL) {
2631 0 : return NULL;
2632 : }
2633 278433 : PyObject *result = PyObject_GetAttr(mod, attrname);
2634 278433 : Py_DECREF(mod);
2635 278433 : return result;
2636 : }
2637 :
2638 : PyObject *
2639 278433 : _PyImport_GetModuleAttrString(const char *modname, const char *attrname)
2640 : {
2641 278433 : PyObject *pmodname = PyUnicode_FromString(modname);
2642 278433 : if (pmodname == NULL) {
2643 0 : return NULL;
2644 : }
2645 278433 : PyObject *pattrname = PyUnicode_FromString(attrname);
2646 278433 : if (pattrname == NULL) {
2647 0 : Py_DECREF(pmodname);
2648 0 : return NULL;
2649 : }
2650 278433 : PyObject *result = _PyImport_GetModuleAttr(pmodname, pattrname);
2651 278433 : Py_DECREF(pattrname);
2652 278433 : Py_DECREF(pmodname);
2653 278433 : return result;
2654 : }
2655 :
2656 : #ifdef __cplusplus
2657 : }
2658 : #endif
|