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 theoretical lockfile data race. #1087

Merged
merged 2 commits into from
Feb 7, 2025
Merged
Changes from all commits
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
24 changes: 12 additions & 12 deletions src/executor/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,13 @@ impl AotContractExecutor {
})
.collect::<Result<BTreeMap<_, _>>>()?;

// Build the shared library.
// Build the shared library into a temporary path.
let temp_path = NamedTempFile::new()?
.into_temp_path()
.keep()
.to_native_assert_error("can only fail on windows")?;
let object_data = crate::module_to_object(&module, opt_level)?;
crate::object_to_shared_lib(&object_data, &output_path)?;
crate::object_to_shared_lib(&object_data, &temp_path)?;

// Write the contract info.
fs::write(
Expand All @@ -269,6 +273,10 @@ impl AotContractExecutor {
})?,
)?;

// Atomically move the built shared library to the correct path. This will avoid data races
// when loading contracts.
fs::rename(temp_path, &output_path)?;

drop(lock_file);
Self::from_path(output_path)
}
Expand All @@ -280,10 +288,9 @@ impl AotContractExecutor {
/// again.
pub fn from_path(path: impl Into<PathBuf>) -> Result<Option<Self>> {
let path = path.into();
if LockFile::exists(&path)? {
return Ok(None);
}

// Note: Library should load first, otherwise there could theoretically be a race condition.
// See the `new_into` function's code for details.
let library = Arc::new(unsafe { Library::new(&path)? });
let contract_info =
serde_json::from_str(&fs::read_to_string(path.with_extension("json"))?)?;
Expand Down Expand Up @@ -630,13 +637,6 @@ impl LockFile {
Err(e) => Err(e),
}
}

pub fn exists(path: impl Into<PathBuf>) -> io::Result<bool> {
let path: PathBuf = path.into();
let path = path.with_extension("lock");

fs::exists(path)
}
}

impl Drop for LockFile {
Expand Down
Loading