gh-101758: Clean Up Uses of Import State (gh-101919)

This change is almost entirely moving code around and hiding import state behind internal API.  We introduce no changes to behavior, nor to non-internal API.  (Since there was already going to be a lot of churn, I took this as an opportunity to re-organize import.c into topically-grouped sections of code.)  The motivation is to simplify a number of upcoming changes.

Specific changes:

* move existing import-related code to import.c, wherever possible
* add internal API for interacting with import state (both global and per-interpreter)
* use only API outside of import.c (to limit churn there when changing the location, etc.)
* consolidate the import-related state of PyInterpreterState into a single struct field (this changes layout slightly)
* add macros for import state in import.c (to simplify changing the location)
* group code in import.c into sections
*remove _PyState_AddModule()

https://github.com/python/cpython/issues/101758
This commit is contained in:
Eric Snow 2023-02-15 15:32:31 -07:00 committed by GitHub
parent c1ce0d178f
commit b2fc549278
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 1496 additions and 1092 deletions

View file

@ -99,7 +99,7 @@ _PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp)
#endif
PyObject *name_unicode = NULL, *name = NULL, *path = NULL, *m = NULL;
const char *name_buf, *hook_prefix;
const char *oldcontext;
const char *oldcontext, *newcontext;
dl_funcptr exportfunc;
PyModuleDef *def;
PyModInitFunction p0;
@ -113,6 +113,10 @@ _PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp)
"spec.name must be a string");
goto error;
}
newcontext = PyUnicode_AsUTF8(name_unicode);
if (newcontext == NULL) {
goto error;
}
name = get_encoded_name(name_unicode, &hook_prefix);
if (name == NULL) {
@ -160,16 +164,9 @@ _PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp)
p0 = (PyModInitFunction)exportfunc;
/* Package context is needed for single-phase init */
#define _Py_PackageContext (_PyRuntime.imports.pkgcontext)
oldcontext = _Py_PackageContext;
_Py_PackageContext = PyUnicode_AsUTF8(name_unicode);
if (_Py_PackageContext == NULL) {
_Py_PackageContext = oldcontext;
goto error;
}
oldcontext = _PyImport_SwapPackageContext(newcontext);
m = _PyImport_InitFunc_TrampolineCall(p0);
_Py_PackageContext = oldcontext;
#undef _Py_PackageContext
_PyImport_SwapPackageContext(oldcontext);
if (m == NULL) {
if (!PyErr_Occurred()) {