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

feat: set default rpath for binaries #531

Merged
merged 1 commit into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
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
59 changes: 57 additions & 2 deletions src/linux/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ pub enum RelinkError {

#[error("failed to parse elf file: {0}")]
ParseElfError(#[from] goblin::error::Error),

#[error("rpath not found in dynamic section")]
RpathNotFound,
}

impl SharedObject {
Expand Down Expand Up @@ -88,19 +91,26 @@ impl SharedObject {
&self,
prefix: &Path,
encoded_prefix: &Path,
custom_rpaths: &[String],
rpath_allowlist: &[GlobMatcher],
) -> Result<(), RelinkError> {
if !self.has_dynamic {
tracing::debug!("{} is not dynamically linked", self.path.display());
return Ok(());
}

let rpaths = self
let mut rpaths = self
.rpaths
.iter()
.flat_map(|r| r.split(':'))
.map(PathBuf::from)
.collect::<Vec<_>>();
rpaths.extend(
custom_rpaths
.iter()
.map(|v| encoded_prefix.join(v))
.collect::<Vec<PathBuf>>(),
);

let runpaths = self
.runpaths
Expand Down Expand Up @@ -242,6 +252,16 @@ fn relink(elf_path: &Path, new_rpath: &[PathBuf]) -> Result<(), RelinkError> {
.iter()
.any(|entry| entry.d_tag == goblin::elf::dynamic::DT_RPATH);

let has_runpath = dynamic
.dyns
.iter()
.any(|entry| entry.d_tag == goblin::elf::dynamic::DT_RUNPATH);

// fallback to patchelf if there is no rpath found
if !has_rpath && !has_runpath {
return Err(RelinkError::RpathNotFound);
}

let mut data_mut = data.make_mut().expect("Failed to make data mutable");

let overwrite_strtab =
Expand Down Expand Up @@ -301,7 +321,7 @@ fn relink(elf_path: &Path, new_rpath: &[PathBuf]) -> Result<(), RelinkError> {
.iter()
.find(|header| header.p_type == goblin::elf::program_header::PT_DYNAMIC)
.map(|header| header.p_offset)
.ok_or(RelinkError::PatchElfFailed)? as usize;
.ok_or(RelinkError::BuiltinRelinkFailed)? as usize;
let ctx = ctx(&object);
for d in new_dynamic {
data_mut.pwrite_with::<goblin::elf::dynamic::Dyn>(d, offset, ctx)?;
Expand Down Expand Up @@ -348,6 +368,7 @@ mod test {
object.relink(
&prefix,
encoded_prefix,
&[],
&[Glob::new("/usr/lib/custom**").unwrap().compile_matcher()],
)?;
let object = SharedObject::new(&binary_path)?;
Expand All @@ -367,6 +388,40 @@ mod test {
Ok(())
}

// rpath: none
// encoded prefix: "/rattler-build_zlink/host_env_placehold"
// binary path: test-data/binary_files/tmp/zlink
// prefix: "test-data/binary_files"
// new rpath: $ORIGIN/../lib
#[test]
#[cfg(target_os = "linux")]
fn relink_add_rpath() -> Result<(), RelinkError> {
// copy binary to a temporary directory
let prefix = Path::new(env!("CARGO_MANIFEST_DIR")).join("test-data/binary_files");
let tmp_dir = tempdir_in(&prefix)?.into_path();
let binary_path = tmp_dir.join("zlink-no-rpath");
fs::copy(prefix.join("zlink-no-rpath"), &binary_path)?;

let encoded_prefix = Path::new("/rattler-build_zlink/host_env_placehold");
let object = SharedObject::new(&binary_path)?;
object.relink(&prefix, encoded_prefix, &[String::from("lib/")], &[])?;
let object = SharedObject::new(&binary_path)?;
assert_eq!(
vec!["$ORIGIN/../lib"],
object
.rpaths
.iter()
.flat_map(|r| r.split(':'))
.collect::<Vec<&str>>()
);

// manually clean up temporary directory because it was
// persisted to disk by calling `into_path`
fs::remove_dir_all(tmp_dir)?;

Ok(())
}

#[test]
fn relink_builtin() -> Result<(), RelinkError> {
// copy binary to a temporary directory
Expand Down
4 changes: 4 additions & 0 deletions src/packaging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,10 @@ pub fn package_conda(
tmp_dir_path,
prefix,
&output.build_configuration.target_platform,
&dynamic_linking
.as_ref()
.map(|v| v.rpaths())
.unwrap_or_default(),
&rpath_allowlist,
)?;
}
Expand Down
3 changes: 2 additions & 1 deletion src/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub fn relink(
prefix: &Path,
encoded_prefix: &Path,
target_platform: &Platform,
rpaths: &[String],
rpath_allowlist: &[GlobMatcher],
) -> Result<(), RelinkError> {
for p in paths {
Expand All @@ -75,7 +76,7 @@ pub fn relink(
if target_platform.is_linux() {
if SharedObject::test_file(p)? {
let so = SharedObject::new(p)?;
so.relink(prefix, encoded_prefix, rpath_allowlist)?;
so.relink(prefix, encoded_prefix, rpaths, rpath_allowlist)?;
}
} else if target_platform.is_osx() && Dylib::test_file(p)? {
let dylib = Dylib::new(p)?;
Expand Down
15 changes: 15 additions & 0 deletions src/recipe/parser/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ impl TryConvertNode<Build> for RenderedMappingNode {
/// Settings for shared libraries and executables.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct DynamicLinking {
/// List of rpaths to use (linux only).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) rpaths: Vec<String>,
/// Allow runpath / rpath to point to these locations outside of the environment.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) rpath_allowlist: Vec<String>,
Expand All @@ -156,6 +159,15 @@ pub struct DynamicLinking {
}

impl DynamicLinking {
/// Get the rpaths.
pub fn rpaths(&self) -> Vec<String> {
if self.rpaths.is_empty() {
vec![String::from("lib/")]
} else {
self.rpaths.clone()
}
}

/// Get the rpath allow list.
pub fn rpath_allowlist(&self) -> Result<Vec<GlobMatcher>, globset::Error> {
let mut matchers = Vec::new();
Expand Down Expand Up @@ -187,6 +199,9 @@ impl TryConvertNode<DynamicLinking> for RenderedMappingNode {
for (key, value) in self.iter() {
let key_str = key.as_str();
match key_str {
"rpaths" => {
dynamic_linking.rpaths = value.try_convert(key_str)?;
}
"rpath_allowlist" => {
dynamic_linking.rpath_allowlist = value.try_convert(key_str)?;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ Recipe {
},
dynamic_linking: Some(
DynamicLinking {
rpaths: [],
rpath_allowlist: [
"/usr/lib/**",
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ Recipe {
},
dynamic_linking: Some(
DynamicLinking {
rpaths: [],
rpath_allowlist: [
"/usr/lib/**",
],
Expand Down
Binary file added test-data/binary_files/zlink-no-rpath
Binary file not shown.