Skip to content

Commit

Permalink
Fix segfaults caused by modifying existing shared library
Browse files Browse the repository at this point in the history
When the built shared library is copied to the correct location, it
actually *modifies* any existing shared library, which causes any
running process using it to segfault.

To fix this, we first delete any existing shared library (which is safe
to do) and then copy the newly built shared library to the correct
location as a new file.

Related to PyO3#257
  • Loading branch information
erikjohnston committed Sep 29, 2022
1 parent 96684af commit d0ab8ee
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions setuptools_rust/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,26 @@ def install_extension(
os.makedirs(os.path.dirname(ext_path), exist_ok=True)

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.
#
# This is because shared libraries are memory mapped into processes
# that use it, so modifying the shared library file (which is what
# `shutil.copyfile` 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

shutil.copyfile(dylib_path, ext_path)

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

0 comments on commit d0ab8ee

Please sign in to comment.