New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Crash when modifying sys.modules during import #59783
Comments
In a submodule of a package, replacing the parent package in sys.modules during import of the package (meaning the only reference to it is in sys.modules) and then importing itself (or something from itself) crashes the interpreter: centurion: It seems the crash is not entirely deterministic, as we've had the original code this was reduced from run in Python 2.4 and 2.6 for years, and only discovered the crash when switching to 2.7. However, running the reduced testcase crashes for me in all of Python 2.7, 2.6, 2.4 and 2.2, in debug builds and opt builds. Given the nature of the bug I expect debug builds to crash reliably. I haven't found the actual source of the problem, but what seems to happen is that the import mechanism has a borrowed reference to the 'sa' module around, assuming it'll stay alive while the submodules are imported because it's also stored in sys.modules. This assumption is incorrect. However, changing the import in sa/init.py into an absolute or explicit relative import seems to fix the problem, which means this probably won't affect Python 3. |
If I remember correctly there were non-trivial improvements made to the way modules are finalized in 2.7 compared to earlier versions. That could be what exposed the bug. The pre-2.7 code might have been leaving another reference alive because of your more complex real world example, whereas the simplified example doesn't. |
Here's the deal. import_module_level() gets called for v1 from sa (where "globals" comes from). In that function it first calls get_parent(), which returns a borrowed reference to the sa module object. Then that parent object is passed to load_next() where the actual load of v1 will take place (and the segfault happens). The problem is that get_parent() returns a borrowed reference. When the sa module is replaced in sys.modules, the old sa module is decref'ed. That's fine except load_next is using that same module as the parent. Enter segfault, stage left. Here's a quick patch that fixes the failure (along with a test). |
Eric has commit rights now so he can commit his own fix. =) |
New changeset 2d6dd8402d77 by Eric Snow in branch '2.7': |
New changeset 731e5617cc8d by Gregory P. Smith in branch '2.7': |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: