use std::borrow::Cow;
use std::collections::BTreeSet;
use std::io::Read;
use std::path::Path;
pub const ANN_SDK_PREFIX: &str = "eu.pulseengine.varve.sdk.prefix";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemberBody {
Dir,
File { mode: u32, bytes: Vec<u8> },
Symlink { target: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Member {
pub path: String,
pub body: MemberBody,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SdkExportReport {
pub dirs: usize,
pub files: usize,
pub symlinks: usize,
pub patched_fields: usize,
pub substitutions: usize,
pub relocated_symlinks: usize,
}
#[derive(Debug, thiserror::Error)]
pub enum SdkExportError {
#[error("io error at {path}")]
Io {
path: String,
#[source]
source: std::io::Error,
},
#[error("the sdk payload is not a readable tar archive: {0}")]
Archive(String),
#[error(
"the sdk declares no build-time prefix ({ANN_SDK_PREFIX}) — without it there is no \
relocation budget and no path to patch; re-deposit the sdk with the prefix it was \
built for"
)]
NoBuiltPrefix,
#[error(
"the export destination must be an absolute path, got {0:?} — the destination is \
PATCHED INTO the SDK's binaries, and a relative path there would resolve against \
whatever directory the compiler happens to run in"
)]
DestinationNotAbsolute(String),
#[error(
"cannot relocate this sdk to {dest}: the destination is {dest_len} characters and the \
sdk was built for {built_prefix} ({budget}). An SDK's interpreter path is patched IN \
PLACE into a fixed-size field, so it can only ever move to a path NO LONGER than the \
one it was built with. Choose a destination of at most {budget} characters."
)]
DestinationTooLong {
dest: String,
dest_len: usize,
built_prefix: String,
budget: usize,
},
#[error(
"{member}: the path field at offset {offset} needs {needed} bytes but the field holds \
{capacity} — this is `relocate_sdk.py`'s own limit (len(new) >= field size), reached \
after the destination-length check passed, so the sdk's fields are tighter than its \
build prefix implies"
)]
FieldTooSmall {
member: String,
offset: usize,
needed: usize,
capacity: usize,
},
#[error(
"{member}: the loader's SYSDIRS table (.sysdirs) names the sdk's build prefix but its \
length array (.sysdirslen) was not found, so moving to a path of a different length \
would leave ld.so stepping through the table by the old lengths — refusing rather than \
produce a loader that opens empty file names"
)]
SysdirsWithoutLengths { member: String },
#[error(
"{member}: .sysdirs holds {paths} path(s) but .sysdirslen has room for {slots} length(s) \
— the two tables disagree, so neither can be rewritten safely"
)]
SysdirsLengthsDisagree {
member: String,
paths: usize,
slots: usize,
},
#[error("sdk member {member:?} is not a usable path ({why}) — refusing to lay the tree down")]
UnsafeMember { member: String, why: String },
#[error(
"two members of this sdk both land on {path} — one would overwrite the other, and the \
survivor would carry the wrong bytes under the right name"
)]
Collision { path: String },
#[error(
"sdk member {member:?} would be written THROUGH the symlink {link:?} — a link out of \
the export followed by a write through it places bytes anywhere on the filesystem"
)]
WriteThroughSymlink { member: String, link: String },
#[error(
"sdk symlink {member:?} points at {target:?}, which is outside both the sdk and the \
export — a relocated SDK is self-contained, and a link to the host is neither \
verified nor reproducible"
)]
SymlinkEscapes { member: String, target: String },
#[error("this platform cannot create the symlink {member:?} an sdk tree requires")]
SymlinksUnsupported { member: String },
}
fn normalise_prefix(p: &str) -> &str {
let t = p.trim_end_matches('/');
if t.is_empty() { p } else { t }
}
pub fn check_destination_fits(built_prefix: &str, dest: &str) -> Result<(), SdkExportError> {
let built = normalise_prefix(built_prefix);
if built.is_empty() {
return Err(SdkExportError::NoBuiltPrefix);
}
if !dest.starts_with('/') {
return Err(SdkExportError::DestinationNotAbsolute(dest.to_string()));
}
let dest_n = normalise_prefix(dest);
if dest_n.len() > built.len() {
return Err(SdkExportError::DestinationTooLong {
dest: dest_n.to_string(),
dest_len: dest_n.len(),
built_prefix: built.to_string(),
budget: built.len(),
});
}
Ok(())
}
fn find_sub(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
(from..=haystack.len() - needle.len()).find(|&i| &haystack[i..i + needle.len()] == needle)
}
fn replace_all(hay: &[u8], from: &[u8], to: &[u8]) -> (Vec<u8>, usize) {
let mut out = Vec::with_capacity(hay.len());
let mut rest = hay;
let mut count = 0;
while let Some(at) = find_sub(rest, from, 0) {
let Some(tail) = rest.get(at..).and_then(|t| t.get(from.len()..)) else {
break;
};
out.extend_from_slice(&rest[..at]);
out.extend_from_slice(to);
rest = tail;
count += 1;
}
out.extend_from_slice(rest);
(out, count)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Relocation {
pub bytes: Vec<u8>,
pub fields: usize,
pub substitutions: usize,
}
fn is_binary(bytes: &[u8]) -> bool {
bytes.contains(&0)
}
pub fn relocate_bytes(
member: &str,
bytes: &[u8],
built_prefix: &str,
dest_prefix: &str,
) -> Result<Relocation, SdkExportError> {
let built = normalise_prefix(built_prefix).as_bytes();
let dest = normalise_prefix(dest_prefix).as_bytes();
if !is_binary(bytes) {
let (out, substitutions) = replace_all(bytes, built, dest);
return Ok(Relocation {
bytes: out,
fields: 0,
substitutions,
});
}
let mut out = bytes.to_vec();
let sysdirs = relocate_sysdirs(member, &mut out, built, dest)?;
let mut fields = sysdirs.as_ref().map_or(0, |(_, n)| *n);
let mut cursor = 0;
while let Some(hit) = find_sub(&out, built, cursor) {
if hit < cursor {
break;
}
if let Some((range, _)) = &sysdirs
&& range.contains(&hit)
{
cursor = range.end;
continue;
}
let start = out[..hit]
.iter()
.rposition(|b| *b == 0)
.map(|p| p + 1)
.unwrap_or(0);
let Some(end) = out[hit..].iter().position(|b| *b == 0).map(|p| hit + p) else {
break;
};
let pad_end = end + out[end..].iter().take_while(|b| **b == 0).count();
let capacity = pad_end - start;
let (new, _) = replace_all(&out[start..end], built, dest);
if new.len() >= capacity {
return Err(SdkExportError::FieldTooSmall {
member: member.to_string(),
offset: start,
needed: new.len() + 1,
capacity,
});
}
out[start..start + new.len()].copy_from_slice(&new);
for b in &mut out[start + new.len()..pad_end] {
*b = 0;
}
fields += 1;
cursor = pad_end;
}
Ok(Relocation {
bytes: out,
fields,
substitutions: 0,
})
}
fn elf_section(bytes: &[u8], name: &[u8]) -> Option<(usize, usize, bool, bool)> {
if bytes.get(..4)? != b"\x7fELF" {
return None;
}
let class64 = match *bytes.get(4)? {
1 => false,
2 => true,
_ => return None,
};
let little = match *bytes.get(5)? {
1 => true,
2 => false,
_ => return None,
};
let rd = |at: usize, n: usize| -> Option<usize> {
let field = bytes.get(at..at.checked_add(n)?)?;
let mut buf = [0u8; 8];
let v = if little {
buf[..n].copy_from_slice(field);
u64::from_le_bytes(buf)
} else {
buf[8 - n..].copy_from_slice(field);
u64::from_be_bytes(buf)
};
usize::try_from(v).ok()
};
let word = if class64 { 8 } else { 4 };
let (shoff, shentsize, shnum, shstrndx) = if class64 {
(rd(0x28, 8)?, rd(0x3A, 2)?, rd(0x3C, 2)?, rd(0x3E, 2)?)
} else {
(rd(0x20, 4)?, rd(0x2E, 2)?, rd(0x30, 2)?, rd(0x32, 2)?)
};
let header = |i: usize| -> Option<(usize, usize, usize)> {
let base = shoff.checked_add(i.checked_mul(shentsize)?)?;
let off_at = base.checked_add(8 + 2 * word)?;
Some((
rd(base, 4)?,
rd(off_at, word)?,
rd(off_at.checked_add(word)?, word)?,
))
};
let (_, str_off, str_size) = header(shstrndx)?;
let strtab = bytes.get(str_off..str_off.checked_add(str_size)?)?;
(0..shnum).find_map(|i| {
let (name_at, off, size) = header(i)?;
let tail = strtab.get(name_at..)?;
let this = tail.split(|b| *b == 0).next()?;
(this == name && bytes.get(off..off.checked_add(size)?).is_some())
.then_some((off, size, class64, little))
})
}
fn relocate_sysdirs(
member: &str,
out: &mut [u8],
built: &[u8],
dest: &[u8],
) -> Result<Option<(std::ops::Range<usize>, usize)>, SdkExportError> {
let Some((off, size, class64, little)) = elf_section(out, b".sysdirs") else {
return Ok(None);
};
let table = &out[off..off + size];
if find_sub(table, built, 0).is_none() {
return Ok(None);
}
let Some((len_off, len_size, _, _)) = elf_section(out, b".sysdirslen") else {
if built.len() == dest.len() {
return Ok(None);
}
return Err(SdkExportError::SysdirsWithoutLengths {
member: member.to_string(),
});
};
let paths: Vec<Vec<u8>> = table
.split(|b| *b == 0)
.take_while(|p| !p.is_empty())
.map(|p| replace_all(p, built, dest).0)
.collect();
let width = if class64 { 8 } else { 4 };
let slots = len_size / width;
if paths.len() != slots {
return Err(SdkExportError::SysdirsLengthsDisagree {
member: member.to_string(),
paths: paths.len(),
slots,
});
}
let mut packed = Vec::with_capacity(size);
for p in &paths {
packed.extend_from_slice(p);
packed.push(0);
}
if packed.len() > size {
return Err(SdkExportError::FieldTooSmall {
member: member.to_string(),
offset: off,
needed: packed.len(),
capacity: size,
});
}
packed.resize(size, 0);
out[off..off + size].copy_from_slice(&packed);
let slots_bytes = &mut out[len_off..len_off + slots * width];
for (slot, p) in slots_bytes.chunks_exact_mut(width).zip(&paths) {
let len = p.len() as u64;
match (class64, little) {
(true, true) => slot.copy_from_slice(&len.to_le_bytes()),
(true, false) => slot.copy_from_slice(&len.to_be_bytes()),
(false, true) => slot.copy_from_slice(&(len as u32).to_le_bytes()),
(false, false) => slot.copy_from_slice(&(len as u32).to_be_bytes()),
}
}
Ok(Some((off..off + size, paths.len())))
}
fn component_fault(value: &str) -> Option<String> {
if value.is_empty() {
return Some("an empty path component".into());
}
if value == "." || value == ".." {
return Some("a relative path element".into());
}
if let Some(c) = value
.chars()
.find(|c| matches!(c, '/' | '\\' | '\0') || c.is_control())
{
return Some(format!("contains {c:?}"));
}
None
}
pub(crate) fn names_archive_root(raw: &str) -> bool {
let mut p = raw.trim_end_matches('/');
while let Some(rest) = p.strip_prefix("./") {
p = rest.trim_start_matches('/');
}
p == "."
}
pub(crate) fn safe_member_path(raw: &str) -> Result<String, SdkExportError> {
let unsafe_member = |why: &str| SdkExportError::UnsafeMember {
member: raw.to_string(),
why: why.to_string(),
};
if raw.starts_with('/') {
return Err(unsafe_member(
"absolute — it would place bytes outside the export",
));
}
let trimmed = raw.trim_end_matches('/');
let mut trimmed = trimmed;
while let Some(rest) = trimmed.strip_prefix("./") {
trimmed = rest;
}
if trimmed.is_empty() {
return Err(unsafe_member("empty"));
}
for component in trimmed.split('/') {
if let Some(why) = component_fault(component) {
return Err(unsafe_member(&why));
}
}
Ok(trimmed.to_string())
}
fn decompress(archive: &[u8]) -> Result<Cow<'_, [u8]>, SdkExportError> {
if archive.starts_with(&[0x1f, 0x8b]) {
let mut out = Vec::new();
flate2::read::GzDecoder::new(archive)
.read_to_end(&mut out)
.map_err(|e| SdkExportError::Archive(e.to_string()))?;
return Ok(Cow::Owned(out));
}
if archive.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
let mut out = Vec::new();
let mut input = std::io::BufReader::new(archive);
lzma_rs::xz_decompress(&mut input, &mut out)
.map_err(|e| SdkExportError::Archive(format!("xz: {e}")))?;
return Ok(Cow::Owned(out));
}
if archive.starts_with(b"BZh") {
return Err(SdkExportError::Archive(
"this payload is bzip2-compressed, which varve cannot decode. It was \
deposited and its bytes verify; what is missing is a decoder. \
Re-deposit the sdk as .tar.gz or .tar.xz, or file for bzip2 support."
.into(),
));
}
Ok(Cow::Borrowed(archive))
}
pub fn read_members(archive: &[u8]) -> Result<Vec<Member>, SdkExportError> {
let raw = decompress(archive)?;
let mut tar = tar::Archive::new(raw.as_ref());
let entries = tar
.entries()
.map_err(|e| SdkExportError::Archive(e.to_string()))?;
let mut members = Vec::new();
for entry in entries {
let mut entry = entry.map_err(|e| SdkExportError::Archive(e.to_string()))?;
let raw_path = entry
.path()
.map_err(|e| SdkExportError::Archive(e.to_string()))?
.to_string_lossy()
.into_owned();
let header = entry.header().clone();
let body = match header.entry_type() {
tar::EntryType::Directory => MemberBody::Dir,
tar::EntryType::Symlink | tar::EntryType::Link => {
let target = entry
.link_name()
.map_err(|e| SdkExportError::Archive(e.to_string()))?
.map(|t| t.to_string_lossy().into_owned())
.unwrap_or_default();
MemberBody::Symlink { target }
}
_ => {
let mut bytes = Vec::new();
entry
.read_to_end(&mut bytes)
.map_err(|e| SdkExportError::Archive(e.to_string()))?;
let mode = header.mode().unwrap_or(0o644);
MemberBody::File { mode, bytes }
}
};
members.push(Member {
path: raw_path,
body,
});
}
Ok(members)
}
fn resolve_link_target(
member: &str,
target: &str,
built_prefix: &str,
dest_prefix: &str,
) -> Result<(String, bool), SdkExportError> {
let escapes = || SdkExportError::SymlinkEscapes {
member: member.to_string(),
target: target.to_string(),
};
if target.is_empty() {
return Err(escapes());
}
if target.starts_with('/') {
let built = normalise_prefix(built_prefix);
let dest = normalise_prefix(dest_prefix);
if target == built {
return Ok((dest.to_string(), true));
}
if let Some(rest) = target.strip_prefix(&format!("{built}/")) {
let mut depth: isize = 0;
for component in rest.split('/') {
match component {
"" | "." => {}
".." => {
depth -= 1;
if depth < 0 {
return Err(escapes());
}
}
_ => depth += 1,
}
}
return Ok((format!("{dest}/{rest}"), true));
}
return Err(escapes());
}
let mut stack: Vec<&str> = member.split('/').collect();
stack.pop(); for component in target.split('/') {
match component {
"" | "." => {}
".." => {
if stack.pop().is_none() {
return Err(escapes());
}
}
other => stack.push(other),
}
}
Ok((target.to_string(), false))
}
pub fn export_sdk(
archive: &[u8],
built_prefix: &str,
out: &Path,
) -> Result<SdkExportReport, SdkExportError> {
let dest = out.to_string_lossy().into_owned();
check_destination_fits(built_prefix, &dest)?;
let members = read_members(archive)?;
export_members(&members, built_prefix, out)
}
pub fn export_members(
members: &[Member],
built_prefix: &str,
out: &Path,
) -> Result<SdkExportReport, SdkExportError> {
let dest = out.to_string_lossy().into_owned();
check_destination_fits(built_prefix, &dest)?;
let mut placed: BTreeSet<String> = BTreeSet::new();
let mut links: BTreeSet<String> = BTreeSet::new();
let mut planned: Vec<(String, &Member)> = Vec::with_capacity(members.len());
for m in members {
if matches!(m.body, MemberBody::Dir) && names_archive_root(&m.path) {
continue;
}
let path = safe_member_path(&m.path)?;
if !placed.insert(path.clone()) {
return Err(SdkExportError::Collision { path });
}
if let MemberBody::Symlink { .. } = m.body {
links.insert(path.clone());
}
planned.push((path, m));
}
for (path, _) in &planned {
let mut prefix = String::new();
for component in path.split('/') {
if !prefix.is_empty() {
prefix.push('/');
}
prefix.push_str(component);
if prefix.len() < path.len() && links.contains(&prefix) {
return Err(SdkExportError::WriteThroughSymlink {
member: path.clone(),
link: prefix,
});
}
}
}
let mut resolved_links: Vec<(&str, String, bool)> = Vec::new();
for (path, m) in &planned {
if let MemberBody::Symlink { target } = &m.body {
let (t, relocated) = resolve_link_target(path, target, built_prefix, &dest)?;
resolved_links.push((path, t, relocated));
}
}
let mut relocated_files: Vec<(&str, Relocation, u32)> = Vec::new();
for (path, m) in &planned {
if let MemberBody::File { mode, bytes } = &m.body {
let r = relocate_bytes(path, bytes, built_prefix, &dest)?;
relocated_files.push((path, r, *mode));
}
}
let io = |path: &Path, source: std::io::Error| SdkExportError::Io {
path: path.display().to_string(),
source,
};
let mut report = SdkExportReport::default();
std::fs::create_dir_all(out).map_err(|e| io(out, e))?;
for (rel, m) in &planned {
if matches!(m.body, MemberBody::Dir) {
let path = out.join(rel);
std::fs::create_dir_all(&path).map_err(|e| io(&path, e))?;
report.dirs += 1;
}
}
for (rel, relocation, mode) in &relocated_files {
let path = out.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
}
std::fs::write(&path, &relocation.bytes).map_err(|e| io(&path, e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode & 0o7777))
.map_err(|e| io(&path, e))?;
}
#[cfg(not(unix))]
let _ = mode;
report.files += 1;
report.patched_fields += relocation.fields;
report.substitutions += relocation.substitutions;
}
for (rel, target, relocated) in &resolved_links {
let path = out.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
}
#[cfg(unix)]
std::os::unix::fs::symlink(target, &path).map_err(|e| io(&path, e))?;
#[cfg(not(unix))]
{
let _ = target;
return Err(SdkExportError::SymlinksUnsupported {
member: (*rel).to_string(),
});
}
report.symlinks += 1;
if *relocated {
report.relocated_symlinks += 1;
}
}
Ok(report)
}
#[cfg(test)]
mod safe_path_probe {
#[test]
fn a_leading_dot_slash_is_tar_convention_not_traversal() {
assert_eq!(
super::safe_member_path("./index.html").expect("the tar root prefix is not an escape"),
"index.html"
);
assert_eq!(
super::safe_member_path("./a/b.html").expect("nested under the tar root"),
"a/b.html"
);
}
#[test]
fn an_interior_relative_element_is_still_refused() {
for bad in ["a/./b", "a/../b", "../escape", "a/..", "./../x"] {
assert!(
super::safe_member_path(bad).is_err(),
"{bad:?} must still be refused"
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
const BUILT: &str = "/opt/poky/4.0.15/x86_64-pokysdk-linux/default-installation-directory-padded-so-a-temporary-directory-fits-inside-the-relocation-budget-which-can-only-ever-shrink-a-path-never-grow-it";
const SLACK: usize = 8;
fn nul_field(s: &str, width: usize) -> Vec<u8> {
let mut v = s.as_bytes().to_vec();
v.resize(width, 0);
v
}
fn field(s: &str) -> Vec<u8> {
nul_field(s, s.len() + SLACK)
}
fn interp() -> String {
format!("{BUILT}/sysroots/x86_64/lib/ld-linux.so.2")
}
fn fake_binary() -> Vec<u8> {
let mut v = b"\x7fELF".to_vec();
v.extend_from_slice(&field(&interp()));
v.extend_from_slice(&field(&format!("{BUILT}/sysroots/x86_64/usr/lib")));
v.extend_from_slice(b"\0\0trailer\0");
v
}
fn env_setup() -> Vec<u8> {
format!(
"export SDKTARGETSYSROOT={BUILT}/sysroots/aarch64\n\
export PATH={BUILT}/sysroots/x86_64/usr/bin:$PATH\n\
export CC=\"aarch64-poky-linux-gcc --sysroot={BUILT}/sysroots/aarch64\"\n"
)
.into_bytes()
}
fn synthetic_sdk() -> Vec<Member> {
vec![
Member {
path: "sysroots".into(),
body: MemberBody::Dir,
},
Member {
path: "sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc".into(),
body: MemberBody::File {
mode: 0o755,
bytes: fake_binary(),
},
},
Member {
path: "environment-setup-aarch64-poky-linux".into(),
body: MemberBody::File {
mode: 0o644,
bytes: env_setup(),
},
},
Member {
path: "sysroots/x86_64/usr/bin/cc".into(),
body: MemberBody::Symlink {
target: format!("{BUILT}/sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc"),
},
},
]
}
#[test]
fn the_archive_root_directory_entry_is_not_a_refusal() {
let tmp = tempfile::tempdir().unwrap();
let out = out_of_len(tmp.path(), BUILT.len());
let mut members = vec![
Member {
path: "./".into(),
body: MemberBody::Dir,
},
Member {
path: ".".into(),
body: MemberBody::Dir,
},
];
members.extend(synthetic_sdk());
let report =
export_members(&members, BUILT, &out).expect("a `tar -C dir .` archive exports");
assert!(out.join("sysroots").is_dir());
assert_eq!(
report.dirs,
synthetic_sdk()
.iter()
.filter(|m| matches!(m.body, MemberBody::Dir))
.count()
);
}
#[test]
fn only_a_directory_may_name_the_archive_root() {
let tmp = tempfile::tempdir().unwrap();
let out = out_of_len(tmp.path(), BUILT.len());
for body in [
MemberBody::File {
mode: 0o644,
bytes: b"x".to_vec(),
},
MemberBody::Symlink {
target: "/etc".into(),
},
] {
let members = vec![Member {
path: "./".into(),
body,
}];
let err = export_members(&members, BUILT, &out).unwrap_err();
assert!(matches!(err, SdkExportError::UnsafeMember { .. }), "{err}");
}
let members = vec![Member {
path: "./../".into(),
body: MemberBody::Dir,
}];
assert!(export_members(&members, BUILT, &out).is_err());
}
fn out_of_len(base: &Path, len: usize) -> PathBuf {
let base_s = base.to_string_lossy().into_owned();
assert!(base_s.len() < len, "tempdir already longer than {len}");
let pad = len - base_s.len() - 1;
base.join("d".repeat(pad))
}
#[test]
fn a_destination_longer_than_the_build_prefix_is_refused_before_anything_is_written() {
let tmp = tempfile::tempdir().unwrap();
let too_long = out_of_len(tmp.path(), BUILT.len() + 1);
let err = export_members(&synthetic_sdk(), BUILT, &too_long).unwrap_err();
match &err {
SdkExportError::DestinationTooLong {
dest_len, budget, ..
} => {
assert_eq!(*dest_len, BUILT.len() + 1);
assert_eq!(*budget, BUILT.len());
}
other => panic!("expected DestinationTooLong, got {other}"),
}
let msg = err.to_string();
assert!(msg.contains(&too_long.display().to_string()), "{msg}");
assert!(
msg.contains(BUILT),
"names the prefix it was built for: {msg}"
);
assert!(msg.contains("NO LONGER"), "states the rule: {msg}");
assert!(!too_long.exists(), "a refused export must write nothing");
let exact = out_of_len(tmp.path(), BUILT.len());
assert!(check_destination_fits(BUILT, &exact.to_string_lossy()).is_ok());
}
#[test]
fn a_relative_or_prefixless_destination_is_refused() {
assert!(matches!(
check_destination_fits(BUILT, "toolchains/poky"),
Err(SdkExportError::DestinationNotAbsolute(_))
));
assert!(matches!(
check_destination_fits("", "/opt/x"),
Err(SdkExportError::NoBuiltPrefix)
));
assert!(matches!(
check_destination_fits("/", "/opt/x"),
Err(SdkExportError::DestinationTooLong { .. })
));
assert!(check_destination_fits("/opt/poky", "/opt/abcd/").is_ok());
}
#[test]
fn a_component_is_refused_for_a_separator_or_for_a_control_character() {
assert!(
super::component_fault("a/b").is_some(),
"a component containing a separator must be refused"
);
assert!(super::component_fault("a\\b").is_some());
assert!(
super::component_fault("a\nb").is_some(),
"a control character must be refused even though it is not a separator"
);
assert!(super::component_fault("a\tb").is_some());
assert!(super::component_fault("libc.so.6").is_none());
}
#[test]
fn empty_and_dot_components_add_no_depth_to_the_escape_check() {
let r = super::resolve_link_target("m", "./..", "/opt/poky", "/opt/sdk");
assert!(
r.is_err(),
"`./..` climbs above the export root and must be refused, got {r:?}"
);
let r = super::resolve_link_target("m", ".//..", "/opt/poky", "/opt/sdk");
assert!(r.is_err(), "empty and dot components must not fund a climb");
}
#[test]
fn an_absolute_target_under_the_prefix_is_walked_not_merely_prefix_matched() {
let built = "/opt/poky";
for target in ["/opt/poky/./..", "/opt/poky/.//..", "/opt/poky/../.."] {
assert!(
super::resolve_link_target("m", target, built, "/opt/sdk").is_err(),
"{target} climbs out of the export root and must be refused"
);
}
let (t, _) = super::resolve_link_target("m", "/opt/poky/lib/..", built, "/opt/sdk")
.expect("returning to the root stays inside it");
assert_eq!(t, "/opt/sdk/lib/..");
super::resolve_link_target("m", "/opt/poky/usr/../lib/libc.so", built, "/opt/sdk")
.expect("an ordinary absolute SDK symlink must not be refused");
}
#[test]
fn returning_to_the_root_is_not_an_escape() {
let (target, _) = super::resolve_link_target("m", "a/..", "/opt/poky", "/opt/sdk")
.expect("stepping down and back up stays inside the root");
assert_eq!(target, "a/..");
super::resolve_link_target("m", "lib/../lib/libc.so", "/opt/poky", "/opt/sdk")
.expect("a normal SDK symlink must not be refused");
assert!(super::resolve_link_target("m", "a/../..", "/opt/poky", "/opt/sdk").is_err());
}
#[test]
fn patching_one_string_leaves_the_string_before_it_untouched() {
let mut buf = b"KEEP-ME-EXACTLY ".to_vec();
let head = buf.len();
let field = format!("LD_LIBRARY_PATH={BUILT}/sysroots/lib");
buf.extend_from_slice(&nul_field(&field, field.len() + 1 + SLACK));
let r = relocate_bytes("libc.so", &buf, BUILT, "/opt/sdk").unwrap();
assert_eq!(r.bytes.len(), buf.len(), "in-place patch preserves length");
assert_eq!(
&r.bytes[..head],
b"KEEP-ME-EXACTLY\0",
"the preceding string was corrupted — `start` walked past its own \
string boundary"
);
let patched = &r.bytes[head..];
let text = &patched[..patched.iter().position(|b| *b == 0).unwrap()];
assert_eq!(
text,
b"LD_LIBRARY_PATH=/opt/sdk/sysroots/lib",
"the patched field is wrong: {}",
String::from_utf8_lossy(text)
);
assert!(
patched[text.len()..].iter().all(|b| *b == 0),
"everything past the terminator must be NUL padding"
);
assert_eq!(r.fields, 1);
}
#[test]
fn an_unterminated_occurrence_is_stepped_over_rather_than_scanned_forever() {
let mut buf = vec![0u8];
buf.extend_from_slice(BUILT.as_bytes());
let r = relocate_bytes("weird.bin", &buf, BUILT, "/opt/sdk").unwrap();
assert_eq!(
r.fields, 0,
"an unterminated occurrence is not a padded field and must not be patched"
);
assert_eq!(r.bytes, buf, "and nothing about it may be rewritten");
}
#[test]
fn capacity_is_measured_from_the_string_start_not_from_the_occurrence() {
let field = format!("PATH={BUILT}");
let head = b"PRECEDING\0";
let mut buf = head.to_vec();
buf.extend_from_slice(&nul_field(&field, field.len() + 1));
let same = "/x".repeat(BUILT.len() / 2);
let r = relocate_bytes("x", &buf, BUILT, &same).unwrap();
assert_eq!(r.bytes.len(), buf.len());
let longer = format!("{same}Z");
let err = relocate_bytes("x", &buf, BUILT, &longer).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains(&format!("needs {} bytes", field.len() + 2)),
"must say how much the destination needs: {msg}"
);
assert!(
msg.contains(&format!("the field holds {}", buf.len() - head.len())),
"the field is measured from the STRING START, not from the buffer \
start — a capacity that included the preceding string would accept \
a destination that does not fit and overrun the field: {msg}"
);
assert!(
msg.contains(&format!("at offset {}", head.len())),
"and the offset reported is the string start: {msg}"
);
}
#[test]
fn a_needle_exactly_as_long_as_the_haystack_is_still_found() {
assert_eq!(super::find_sub(b"abc", b"abc", 0), Some(0));
assert_eq!(super::find_sub(b"abc", b"abcd", 0), None);
assert_eq!(super::find_sub(b"xabc", b"abc", 0), Some(1));
assert_eq!(super::find_sub(b"abcabc", b"abc", 1), Some(3));
assert_eq!(super::find_sub(b"abc", b"", 0), None);
}
#[test]
fn a_nul_padded_field_is_patched_in_place_and_the_file_length_is_preserved() {
let original = fake_binary();
let r = relocate_bytes("gcc", &original, BUILT, "/opt/sdk").unwrap();
assert_eq!(
r.bytes.len(),
original.len(),
"an in-place patch must not change the file's length"
);
assert_eq!(r.fields, 2, "both path fields patched");
assert_eq!(r.substitutions, 0, "a binary is patched, never sed'ed");
let text = String::from_utf8_lossy(&r.bytes).into_owned();
assert!(text.contains("/opt/sdk/sysroots/x86_64/lib/ld-linux.so.2"));
assert!(
!text.contains(BUILT),
"the build-time prefix must not survive relocation: {text:?}"
);
let width = interp().len() + SLACK;
let patched = &r.bytes[4..4 + width];
let end = patched.iter().position(|b| *b == 0).unwrap();
assert_eq!(
&patched[..end],
b"/opt/sdk/sysroots/x86_64/lib/ld-linux.so.2"
);
assert!(
patched[end..].iter().all(|b| *b == 0),
"the field must be re-padded with NUL"
);
assert!(r.bytes.ends_with(b"trailer\0"));
}
#[test]
fn a_field_too_small_for_the_new_path_is_refused_rather_than_truncated() {
let bytes = nul_field("/opt/a/ld.so", 14);
let ok = relocate_bytes("x", &bytes, "/opt/a", "/opt/ab").unwrap();
assert_eq!(ok.fields, 1);
assert_eq!(ok.bytes.len(), bytes.len());
let err = relocate_bytes("libc.so", &bytes, "/opt/a", "/opt/abc").unwrap_err();
match err {
SdkExportError::FieldTooSmall {
member,
needed,
capacity,
..
} => {
assert_eq!(member, "libc.so", "the refusal must name the FILE");
assert_eq!(capacity, 14);
assert_eq!(needed, 15);
}
other => panic!("expected FieldTooSmall, got {other}"),
}
}
#[test]
fn a_text_file_is_substituted_and_may_change_length() {
let original = env_setup();
let r = relocate_bytes("environment-setup", &original, BUILT, "/opt/sdk").unwrap();
assert_eq!(r.fields, 0, "a text file has no fixed-size field");
assert_eq!(r.substitutions, 3, "every occurrence, not just the first");
let text = String::from_utf8(r.bytes).unwrap();
assert!(text.contains("export SDKTARGETSYSROOT=/opt/sdk/sysroots/aarch64"));
assert!(text.contains("--sysroot=/opt/sdk/sysroots/aarch64"));
assert!(!text.contains(BUILT));
assert!(
text.len() < original.len(),
"a text rewrite is free to change length"
);
}
#[test]
fn the_whole_synthetic_tree_lands_relocated_and_the_source_bytes_are_untouched() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("sdk");
let members = synthetic_sdk();
let signed_binary = fake_binary();
let report = export_members(&members, BUILT, &out).unwrap();
let expected_dirs = members
.iter()
.filter(|m| matches!(m.body, MemberBody::Dir))
.count();
assert!(
expected_dirs > 0,
"the fixture must contain directories or this asserts nothing"
);
assert_eq!(
report.dirs, expected_dirs,
"every directory in the tree is created AND counted"
);
assert_eq!(report.files, 2);
assert_eq!(report.symlinks, 1);
assert_eq!(report.relocated_symlinks, 1);
assert_eq!(report.patched_fields, 2);
assert_eq!(report.substitutions, 3);
let gcc = out.join("sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc");
let on_disk = std::fs::read(&gcc).unwrap();
assert_eq!(on_disk.len(), signed_binary.len(), "in-place patch");
assert_ne!(
on_disk, signed_binary,
"the relocated bytes are NOT the signed bytes — which is exactly why \
the store keeps the archive and verify never hashes the export"
);
assert!(!String::from_utf8_lossy(&on_disk).contains(BUILT));
#[cfg(unix)]
{
let link = out.join("sysroots/x86_64/usr/bin/cc");
let target = std::fs::read_link(&link).unwrap();
assert_eq!(target, gcc, "an SDK-internal link follows the SDK");
}
assert!(out.join("sysroots").is_dir());
assert_eq!(members, synthetic_sdk());
}
#[test]
fn a_member_whose_path_escapes_the_export_is_refused_and_nothing_is_written() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("sdk");
for bad in [
"../../evil",
"/etc/passwd",
"a/../../evil",
"a//b",
"a/./b",
"",
"..",
] {
let members = vec![
Member {
path: "good".into(),
body: MemberBody::File {
mode: 0o644,
bytes: b"good".to_vec(),
},
},
Member {
path: bad.into(),
body: MemberBody::File {
mode: 0o644,
bytes: b"evil".to_vec(),
},
},
];
let err = export_members(&members, BUILT, &out).unwrap_err();
assert!(
matches!(err, SdkExportError::UnsafeMember { .. }),
"member {bad:?} must be refused, got {err}"
);
assert!(
!out.join("good").exists(),
"member {bad:?}: the tree must be refused whole"
);
}
assert!(safe_member_path("a/b/c").is_ok());
assert!(safe_member_path("a/b/").is_ok());
assert_eq!(safe_member_path("a/b/").unwrap(), "a/b");
}
#[test]
fn a_symlink_that_leaves_the_export_is_refused_even_though_every_component_is_safe() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("sdk");
let outside = tmp.path().join("OUTSIDE");
std::fs::create_dir_all(&outside).unwrap();
let err = export_members(
&[Member {
path: "bin/link".into(),
body: MemberBody::Symlink {
target: outside.to_string_lossy().into_owned(),
},
}],
BUILT,
&out,
)
.unwrap_err();
assert!(
matches!(err, SdkExportError::SymlinkEscapes { .. }),
"got {err}"
);
let err = export_members(
&[Member {
path: "bin/link".into(),
body: MemberBody::Symlink {
target: "../../OUTSIDE".into(),
},
}],
BUILT,
&out,
)
.unwrap_err();
assert!(
matches!(err, SdkExportError::SymlinkEscapes { .. }),
"got {err}"
);
let err = export_members(
&[Member {
path: "bin/link".into(),
body: MemberBody::Symlink {
target: format!("{BUILT}/../../../../../../../../tmp/varve-pwned"),
},
}],
BUILT,
&out,
)
.unwrap_err();
assert!(
matches!(err, SdkExportError::SymlinkEscapes { .. }),
"got {err}"
);
let ok = export_members(
&[
Member {
path: "lib/sub/link".into(),
body: MemberBody::Symlink {
target: format!("{BUILT}/lib/sub/../real"),
},
},
Member {
path: "lib/real".into(),
body: MemberBody::File {
bytes: b"x".to_vec(),
mode: 0o644,
},
},
],
BUILT,
&out,
)
.expect("`..` inside the export is legal");
assert_eq!(ok.relocated_symlinks, 1);
let err = export_members(
&[
Member {
path: "bin/link".into(),
body: MemberBody::Symlink {
target: "../lib".into(),
},
},
Member {
path: "bin/link/pwned".into(),
body: MemberBody::File {
mode: 0o644,
bytes: b"PWNED".to_vec(),
},
},
],
BUILT,
&out,
)
.unwrap_err();
assert!(
matches!(err, SdkExportError::WriteThroughSymlink { .. }),
"got {err}"
);
assert!(
std::fs::read_dir(&outside).unwrap().next().is_none(),
"nothing may be written outside the export"
);
assert!(!out.join("bin/link").exists(), "nothing written at all");
let ok = export_members(
&[
Member {
path: "lib/libc.so.6".into(),
body: MemberBody::File {
mode: 0o644,
bytes: b"libc".to_vec(),
},
},
Member {
path: "bin/libc".into(),
body: MemberBody::Symlink {
target: "../lib/libc.so.6".into(),
},
},
],
BUILT,
&out,
)
.unwrap();
assert_eq!(ok.symlinks, 1);
assert_eq!(
ok.relocated_symlinks, 0,
"a relative link needs no patching"
);
}
#[test]
fn two_members_claiming_one_path_are_refused_before_anything_is_written() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("sdk");
let err = export_members(
&[
Member {
path: "bin/gcc".into(),
body: MemberBody::File {
mode: 0o755,
bytes: b"first".to_vec(),
},
},
Member {
path: "bin/gcc".into(),
body: MemberBody::File {
mode: 0o755,
bytes: b"second".to_vec(),
},
},
],
BUILT,
&out,
)
.unwrap_err();
assert!(matches!(err, SdkExportError::Collision { .. }), "got {err}");
assert!(!out.join("bin/gcc").exists());
}
fn synthetic_tarball() -> Vec<u8> {
use std::io::Write;
let mut tar_bytes = Vec::new();
{
let mut b = tar::Builder::new(&mut tar_bytes);
let mut dir = tar::Header::new_gnu();
dir.set_entry_type(tar::EntryType::Directory);
dir.set_size(0);
dir.set_mode(0o755);
b.append_data(&mut dir, "sysroots/", std::io::empty())
.unwrap();
let bin = fake_binary();
let mut f = tar::Header::new_gnu();
f.set_size(bin.len() as u64);
f.set_mode(0o755);
b.append_data(
&mut f,
"sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc",
bin.as_slice(),
)
.unwrap();
let env = env_setup();
let mut t = tar::Header::new_gnu();
t.set_size(env.len() as u64);
t.set_mode(0o644);
b.append_data(
&mut t,
"environment-setup-aarch64-poky-linux",
env.as_slice(),
)
.unwrap();
let mut link = tar::Header::new_gnu();
link.set_entry_type(tar::EntryType::Symlink);
link.set_size(0);
link.set_mode(0o777);
b.append_link(
&mut link,
"sysroots/x86_64/usr/bin/cc",
format!("{BUILT}/sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc"),
)
.unwrap();
b.finish().unwrap();
}
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
gz.write_all(&tar_bytes).unwrap();
gz.finish().unwrap()
}
#[test]
fn a_signed_archive_unpacks_and_relocates_and_the_archive_is_never_modified() {
let tmp = tempfile::tempdir().unwrap();
let out = tmp.path().join("sdk");
let archive = synthetic_tarball();
let before = archive.clone();
let report = export_sdk(&archive, BUILT, &out).unwrap();
assert_eq!(report.files, 2);
assert_eq!(report.symlinks, 1);
assert_eq!(report.patched_fields, 2);
assert_eq!(report.substitutions, 3);
assert_eq!(archive, before, "the signed archive is read-only, always");
let gcc = out.join("sysroots/x86_64/usr/bin/aarch64-poky-linux-gcc");
assert!(!String::from_utf8_lossy(&std::fs::read(&gcc).unwrap()).contains(BUILT));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&gcc).unwrap().permissions().mode() & 0o777,
0o755,
"a compiler must survive the export executable"
);
}
let mut plain = Vec::new();
flate2::read::GzDecoder::new(archive.as_slice())
.read_to_end(&mut plain)
.unwrap();
let out2 = tmp.path().join("sdk2");
assert_eq!(export_sdk(&plain, BUILT, &out2).unwrap(), report);
}
#[test]
fn an_archive_member_that_escapes_is_refused_before_the_tree_is_written() {
use std::io::Write;
let mut tar_bytes = Vec::new();
{
let mut b = tar::Builder::new(&mut tar_bytes);
let mut f = tar::Header::new_gnu();
let payload = b"PWNED";
f.set_size(payload.len() as u64);
f.set_mode(0o644);
{
let gnu = f.as_gnu_mut().unwrap();
let name = b"../../escape";
gnu.name[..name.len()].copy_from_slice(name);
}
f.set_cksum();
b.append(&f, &payload[..]).unwrap();
b.finish().unwrap();
}
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
gz.write_all(&tar_bytes).unwrap();
let evil = gz.finish().unwrap();
let tmp = tempfile::tempdir().unwrap();
let err = export_sdk(&evil, BUILT, &tmp.path().join("sdk")).unwrap_err();
assert!(
matches!(err, SdkExportError::UnsafeMember { .. }),
"got {err}"
);
assert!(!tmp.path().join("escape").exists());
assert!(matches!(
export_sdk(b"\x1f\x8bnot really gzip", BUILT, &tmp.path().join("s2")),
Err(SdkExportError::Archive(_))
));
}
}
#[cfg(test)]
mod xz_tests {
use super::*;
fn xz(bytes: &[u8]) -> Option<Vec<u8>> {
use std::io::Write;
let mut c = std::process::Command::new("xz")
.args(["-c", "-0"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
c.stdin.as_mut()?.write_all(bytes).ok()?;
let out = c.wait_with_output().ok()?;
out.status.success().then_some(out.stdout)
}
#[test]
fn an_xz_payload_is_decoded() {
let plain = b"the tar bytes, near enough for a decoder test".repeat(40);
let Some(compressed) = xz(&plain) else {
eprintln!("system xz unavailable; skipping");
return;
};
assert!(compressed.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]));
assert_ne!(compressed, plain, "the fixture is not actually compressed");
let out = decompress(&compressed).expect("xz must decode");
assert_eq!(out.as_ref(), plain.as_slice());
}
#[test]
fn gzip_and_plain_tar_still_work() {
use std::io::Write;
let plain = b"still a tar".repeat(30);
let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
enc.write_all(&plain).unwrap();
let gz = enc.finish().unwrap();
assert_eq!(decompress(&gz).unwrap().as_ref(), plain.as_slice());
assert_eq!(decompress(&plain).unwrap().as_ref(), plain.as_slice());
}
#[test]
fn a_compression_varve_cannot_decode_names_itself() {
let mut bz = b"BZh9".to_vec();
bz.extend_from_slice(&[0x31, 0x41, 0x59, 0x26, 0x53, 0x59]);
let e = decompress(&bz).expect_err("must refuse");
let msg = e.to_string();
assert!(msg.contains("bzip2"), "{msg}");
assert!(msg.contains("what is missing is a decoder"), "{msg}");
}
#[test]
fn a_truncated_xz_stream_is_an_error_not_a_short_tree() {
let plain = b"a payload long enough to span blocks".repeat(200);
let Some(compressed) = xz(&plain) else { return };
let cut = &compressed[..compressed.len() / 2];
assert!(
decompress(cut).is_err(),
"a truncated stream decoded anyway"
);
}
fn loader(
dirs: &[&str],
sysdirs_size: usize,
class64: bool,
little: bool,
) -> (Vec<u8>, usize, usize) {
let word = if class64 { 8 } else { 4 };
let put = |v: &mut Vec<u8>, at: usize, n: usize, x: u64| {
let b = if little {
x.to_le_bytes()
} else {
x.to_be_bytes()
};
let b = if little { &b[..n] } else { &b[8 - n..] };
v[at..at + n].copy_from_slice(b);
};
let shstrtab = b"\0.shstrtab\0.sysdirslen\0.sysdirs\0".to_vec();
let mut packed = Vec::new();
for d in dirs {
packed.extend_from_slice(d.as_bytes());
packed.push(0);
}
packed.resize(sysdirs_size, 0);
let mut lens = vec![0u8; dirs.len() * word];
for (i, d) in dirs.iter().enumerate() {
put(&mut lens, i * word, word, d.len() as u64);
}
let mut v = vec![0u8; 64];
v[..4].copy_from_slice(b"\x7fELF");
v[4] = if class64 { 2 } else { 1 };
v[5] = if little { 1 } else { 2 };
v[6] = 1;
let shstr_off = v.len();
v.extend_from_slice(&shstrtab);
let lens_off = v.len();
v.extend_from_slice(&lens);
let sys_off = v.len();
v.extend_from_slice(&packed);
let shoff = v.len();
let entsize = if class64 { 64 } else { 40 };
for (name, off, size) in [
(0u64, 0usize, 0usize),
(1, shstr_off, shstrtab.len()),
(11, lens_off, lens.len()),
(23, sys_off, packed.len()),
] {
let mut h = vec![0u8; entsize];
put(&mut h, 0, 4, name);
put(&mut h, 8 + 2 * word, word, off as u64);
put(&mut h, 8 + 3 * word, word, size as u64);
v.extend_from_slice(&h);
}
let (shoff_at, ent_at) = if class64 { (0x28, 0x3A) } else { (0x20, 0x2E) };
put(&mut v, shoff_at, word, shoff as u64);
put(&mut v, ent_at, 2, entsize as u64);
put(&mut v, ent_at + 2, 2, 4);
put(&mut v, ent_at + 4, 2, 1);
(v, lens_off, sys_off)
}
fn loader_with_sysdirs(dirs: &[&str], sysdirs_size: usize) -> (Vec<u8>, usize, usize) {
loader(dirs, sysdirs_size, true, true)
}
fn read_len(b: &[u8], at: usize, width: usize, little: bool) -> u64 {
let mut buf = [0u8; 8];
if little {
buf[..width].copy_from_slice(&b[at..at + width]);
u64::from_le_bytes(buf)
} else {
buf[8 - width..].copy_from_slice(&b[at..at + width]);
u64::from_be_bytes(buf)
}
}
const ZBUILT: &str = "/usr/local/oe-sdk-hardcoded-buildpath";
const ZDIRS: [&str; 2] = [
"/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/lib/",
"/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/usr/lib/",
];
#[test]
fn sysdirs_are_rewritten_for_every_class_and_byte_order() {
for (class64, little) in [(true, true), (true, false), (false, true), (false, false)] {
let (elf, lens_off, sys_off) = loader(&ZDIRS, 512, class64, little);
let r = relocate_bytes("ld.so", &elf, ZBUILT, "/opt/s").unwrap();
let width = if class64 { 8 } else { 4 };
let want = [
"/opt/s/sysroots/x86_64-pokysdk-linux/lib/",
"/opt/s/sysroots/x86_64-pokysdk-linux/usr/lib/",
];
assert_eq!(
(
read_len(&r.bytes, lens_off, width, little),
read_len(&r.bytes, lens_off + width, width, little)
),
(want[0].len() as u64, want[1].len() as u64),
"class64={class64} little={little}"
);
let got = &r.bytes[sys_off..sys_off + want[0].len()];
assert_eq!(got, want[0].as_bytes(), "class64={class64} little={little}");
assert_eq!(r.fields, 2, "two table entries, nothing else in this file");
}
}
#[test]
fn a_prefix_outside_the_table_is_still_patched() {
let (mut elf, _, sys_off) = loader(&ZDIRS, 512, true, true);
let tail = elf.len();
elf.extend_from_slice(b"/usr/local/oe-sdk-hardcoded-buildpath/lib/ld.so\0\0\0\0");
let r = relocate_bytes("ld.so", &elf, ZBUILT, "/opt/s").unwrap();
assert_eq!(r.fields, 3, "two table entries and the trailing path");
assert_eq!(&r.bytes[tail..tail + 17], b"/opt/s/lib/ld.so\0");
assert!(sys_off < tail);
}
#[test]
fn a_table_that_exactly_fills_its_section_fits_and_one_byte_more_does_not() {
let dest = "/opt/s";
let exact: usize = ZDIRS
.iter()
.map(|d| d.len() - ZBUILT.len() + dest.len() + 1)
.sum();
let size = ZDIRS.iter().map(|d| d.len() + 1).sum::<usize>();
let grow = (size - exact) / 2 + dest.len();
let longer = format!("/{}", "x".repeat(grow - 1));
let (elf, _, _) = loader(&ZDIRS, size, true, true);
let fits = relocate_bytes("ld.so", &elf, ZBUILT, &longer).expect("exactly fills");
assert_eq!(fits.fields, 2);
let over = format!("{longer}y");
let err = relocate_bytes("ld.so", &elf, ZBUILT, &over).unwrap_err();
assert!(matches!(err, SdkExportError::FieldTooSmall { .. }), "{err}");
}
#[test]
fn a_truncated_elf_is_not_read_past_its_end() {
let mut short = b"\x7fELF\x02\x01".to_vec();
short.extend_from_slice(b"/usr/local/oe-sdk-hardcoded-buildpath/lib\0\0\0");
let r = relocate_bytes("x", &short, ZBUILT, "/opt/s").unwrap();
assert_eq!(r.fields, 1);
let tiny = b"\x7fE\0".to_vec();
assert!(relocate_bytes("x", &tiny, ZBUILT, "/opt/s").is_ok());
}
#[test]
fn a_shorter_destination_repacks_sysdirs_and_rewrites_their_lengths() {
let built = "/usr/local/oe-sdk-hardcoded-buildpath";
let dirs = [
"/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/lib/",
"/usr/local/oe-sdk-hardcoded-buildpath/sysroots/x86_64-pokysdk-linux/usr/lib/",
];
let (elf, lens_off, sys_off) = loader_with_sysdirs(&dirs, 4096);
let r = relocate_bytes("lib/ld-linux-x86-64.so.2", &elf, built, "/opt/short").unwrap();
assert_eq!(r.bytes.len(), elf.len());
let want_a = "/opt/short/sysroots/x86_64-pokysdk-linux/lib/";
let want_b = "/opt/short/sysroots/x86_64-pokysdk-linux/usr/lib/";
let mut packed = format!("{want_a}\0{want_b}\0").into_bytes();
packed.resize(4096, 0);
assert_eq!(
&r.bytes[sys_off..sys_off + 4096],
&packed[..],
"paths packed back to back"
);
let len = |i: usize| {
u64::from_le_bytes(
r.bytes[lens_off + 8 * i..lens_off + 8 * i + 8]
.try_into()
.unwrap(),
)
};
assert_eq!((len(0), len(1)), (want_a.len() as u64, want_b.len() as u64));
}
#[test]
fn an_equal_length_destination_leaves_the_lengths_equal() {
let built = "/tmp/zephyr-sdk-1.0.1";
let dirs = [
"/tmp/zephyr-sdk-1.0.1/lib/",
"/tmp/zephyr-sdk-1.0.1/usr/lib/",
];
let (elf, lens_off, _) = loader_with_sysdirs(&dirs, 256);
let r = relocate_bytes("ld.so", &elf, built, "/opt/zephyr-sdk-1.0.1").unwrap();
let len0 = u64::from_le_bytes(r.bytes[lens_off..lens_off + 8].try_into().unwrap());
assert_eq!(len0, dirs[0].len() as u64);
}
#[test]
fn sysdirs_without_their_lengths_refuse_a_change_of_length() {
let built = "/tmp/zephyr-sdk-1.0.1";
let dirs = ["/tmp/zephyr-sdk-1.0.1/lib/"];
let (mut elf, _, _) = loader_with_sysdirs(&dirs, 128);
let at = elf.windows(11).position(|w| w == b".sysdirslen").unwrap();
elf[at + 1] = b'X';
let err = relocate_bytes("ld.so", &elf, built, "/opt/z").unwrap_err();
assert!(err.to_string().contains(".sysdirslen"), "{err}");
}
}