Skip to content
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

Fix segfaults caused by modifying existing shared library #295

Merged
merged 5 commits into from
Oct 4, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use os.replace
  • Loading branch information
erikjohnston committed Sep 29, 2022
commit 78b615f56ee1796714bd982d520847d76bc80a7e
29 changes: 10 additions & 19 deletions setuptools_rust/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,26 +346,17 @@ def install_extension(

log.info("Copying rust artifact from %s to %s", dylib_path, ext_path)

# We delete any existing library file before copying to avoid
# causing running processes that use it from segfaulting.
# We want to atomically replace any existing library file. We can't
# just copy the new library directly on top of the old one as that
# causes the existing library to be modified (rather the replaced).
# This means that any process that currently uses the shared library
# will see it modified and likely segfault.
#
# This is because shared libraries are memory mapped into processes
# that use it, so modifying the shared library file (which is what
# copying the file does) means the next time a process calls into
# the shared library they get the updated library rather than the
# original one, causing confusion and segfaults.
#
# Deleting a memory mapped file, on the other hand, is correctly
# handled by the OS, i.e. a copy is kept around until the running
# process exits. Thus, deleting the existing library file and *then*
# copying the new one won't change the existing memory mapped file,
# and so is safe to do.
try:
os.remove(ext_path)
except FileNotFoundError:
pass

os.rename(dylib_path, ext_path)
# We first copy the file to the same directory, as `os.rename`
# doesn't work across file system boundaries.
temp_ext_path = ext_path + "~"
adamreichold marked this conversation as resolved.
Show resolved Hide resolved
shutil.copyfile(dylib_path, temp_ext_path)
os.rename(temp_ext_path, ext_path)
erikjohnston marked this conversation as resolved.
Show resolved Hide resolved

if sys.platform != "win32" and not debug_build:
args = []
Expand Down