use std::{ffi::OsString, path::PathBuf};
use xold::{
buildid::{self, BuildId},
dynamic::{HashStyle, Strip, ZOptions},
icf::IcfMode,
macho::{MachoTarget, PlatformVersion},
search::LibKind,
};
use super::{
DEFAULT_INTERP, Options, inputs::Inputs, unknown_icf, unknown_option,
};
#[derive(Clone, Copy)]
pub enum Attached {
Output,
Entry,
Soname,
Interp,
Icf,
Rpath,
BuildId,
VersionScript,
Undefined,
HashStyle,
Emulation,
Threads,
OptLevel,
}
pub const ATTACHED: [(&str, Attached); 19] = [
("--dynamic-linker=", Attached::Interp),
("--threads=", Attached::Threads),
("--hash-style=", Attached::HashStyle),
("--build-id=", Attached::BuildId),
("--undefined=", Attached::Undefined),
("--version-script=", Attached::VersionScript),
("-version-script=", Attached::VersionScript),
("--rpath=", Attached::Rpath),
("-rpath=", Attached::Rpath),
("-dynamic-linker=", Attached::Interp),
("--output=", Attached::Output),
("--soname=", Attached::Soname),
("--entry=", Attached::Entry),
("-soname=", Attached::Soname),
("--icf=", Attached::Icf),
("-e=", Attached::Entry),
("-o", Attached::Output),
("-m", Attached::Emulation),
("-O", Attached::OptLevel),
];
pub fn attached(arg: &str) -> Option<(Attached, &str)> {
if arg == "-mllvm" {
return None;
}
ATTACHED.iter().find_map(|&(prefix, opt)| {
arg.strip_prefix(prefix)
.filter(|rest| !rest.is_empty())
.map(|rest| (opt, rest))
})
}
pub fn parse_build_id(value: &str) -> std::result::Result<BuildId, String> {
match value {
"none" => Ok(BuildId::None),
"fast" => Ok(BuildId::Fast),
"md5" => Ok(BuildId::Md5),
"sha1" | "tree" => Ok(BuildId::Sha1),
"uuid" => Err("xold: --build-id=uuid asks for a random identifier, \
which would make the same inputs produce a different \
image on every run; use fast, md5 or sha1"
.into()),
hex if hex.starts_with("0x") => buildid::parse_hex(&hex[2..])
.map(BuildId::Hex)
.ok_or_else(|| {
format!(
"xold: --build-id={hex} is not an even-length string of \
hexadecimal digits"
)
}),
other => Err(format!(
"xold: unknown --build-id value `{other}` (expected \
none|fast|md5|sha1|0xHEXSTRING)"
)),
}
}
pub fn parse_hash_style(value: &str) -> std::result::Result<HashStyle, String> {
match value {
"both" => Ok(HashStyle::Both),
"sysv" => Ok(HashStyle::Sysv),
"gnu" => Ok(HashStyle::Gnu),
other => Err(format!(
"xold: unknown --hash-style value `{other}` (expected \
sysv|gnu|both)"
)),
}
}
pub fn parse_icf(value: &str) -> std::result::Result<IcfMode, String> {
match value {
"all" => Ok(IcfMode::All),
"safe" => Ok(IcfMode::Safe),
"none" => Ok(IcfMode::None),
other => Err(unknown_icf(other)),
}
}
pub fn is_noop_flag(arg: &str) -> bool {
matches!(
arg,
"--eh-frame-hdr"
| "--start-group"
| "-("
| "--end-group"
| "-)"
| "--no-add-needed"
| "--no-copy-dt-needed-entries"
| "--fatal-warnings"
| "--no-fatal-warnings"
| "-demangle"
| "-no_deduplicate"
)
}
pub fn parse_macho_arch(
value: &str,
) -> std::result::Result<MachoTarget, String> {
match value {
"arm64" => Ok(MachoTarget::Arm64),
"x86_64" => Ok(MachoTarget::X86_64),
other => Err(format!(
"xold: unsupported -arch value `{other}` (expected arm64|x86_64)"
)),
}
}
pub fn parse_platform_version(
platform: &str,
min_os: &str,
sdk: &str,
) -> std::result::Result<PlatformVersion, String> {
let platform = match platform {
"macos" => 1,
other => {
return Err(format!(
"xold: unsupported Mach-O platform `{other}` (expected macos)"
));
}
};
Ok(PlatformVersion {
platform,
min_os: parse_macho_version(min_os)?,
sdk: parse_macho_version(sdk)?,
})
}
fn parse_macho_version(value: &str) -> std::result::Result<u32, String> {
let mut parts = value.split('.');
let parse = |part: Option<&str>| -> Option<u32> {
match part {
None => Some(0),
Some("") => None,
Some(n) => n.parse().ok(),
}
};
let major = parse(parts.next());
let minor = parse(parts.next());
let patch = parse(parts.next());
let valid = parts.next().is_none()
&& major.is_some_and(|n| n <= 0xffff)
&& minor.is_some_and(|n| n <= 0xff)
&& patch.is_some_and(|n| n <= 0xff);
if !valid {
return Err(format!(
"xold: invalid Mach-O version `{value}` (expected major[.minor[.patch]])"
));
}
Ok((major.unwrap_or(0) << 16)
| (minor.unwrap_or(0) << 8)
| patch.unwrap_or(0))
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Default)]
pub struct Switches {
pub shared: bool,
pub dynamic_exec: bool,
pub gc_sections: bool,
pub relax_off: bool,
pub relax_named: bool,
pub no_fork: bool,
pub export_dynamic: bool,
pub strip: Strip,
pub pie: Option<bool>,
pub static_link: bool,
}
impl Switches {
pub fn parse(&mut self, arg: &str) -> bool {
match arg {
"-shared" | "--shared" => self.shared = true,
"--dynamic-exec" => self.dynamic_exec = true,
"--gc-sections" => self.gc_sections = true,
"--no-gc-sections" => self.gc_sections = false,
"--no-fork" => self.no_fork = true,
"--export-dynamic" | "-E" => self.export_dynamic = true,
"--no-export-dynamic" => self.export_dynamic = false,
"-pie" | "--pic-executable" => {
self.pie = Some(true);
self.dynamic_exec = true;
}
"-no-pie" | "--no-pic-executable" => self.pie = Some(false),
"--strip-all" | "-s" => self.strip = Strip::All,
"--strip-debug" | "-S" => {
if self.strip != Strip::All {
self.strip = Strip::Debug;
}
}
"--relax" | "--no-relax" => {
self.relax_off = arg == "--no-relax";
self.relax_named = true;
}
_ => return false,
}
true
}
}
pub fn positional(
inputs: &mut Inputs,
arg: &str,
) -> std::result::Result<bool, String> {
match arg {
"-Bstatic" | "-dn" | "-non_shared" => {
inputs.kind = LibKind::ArchiveOnly;
}
"-Bdynamic" | "-dy" | "-call_shared" => inputs.kind = LibKind::Any,
"--as-needed" => inputs.as_needed = true,
"--no-as-needed" => inputs.as_needed = false,
"--push-state" => inputs.push_state(),
"--pop-state" => inputs.pop_state()?,
_ => return Ok(false),
}
Ok(true)
}
pub fn parse_lib_marker(
inputs: &mut Inputs,
arg: &str,
) -> std::result::Result<(), String> {
if arg == "--start-lib" {
if inputs.in_lib {
return Err("xold: nested --start-lib".into());
}
inputs.begin_lib();
return Ok(());
}
if !inputs.in_lib {
return Err("xold: --end-lib without --start-lib".into());
}
inputs.end_lib();
Ok(())
}
pub fn raw_argument(
inputs: &mut Inputs,
arg: &OsString,
) -> std::result::Result<(), String> {
let raw = arg.as_encoded_bytes();
if raw.first() == Some(&b'-') && raw.len() > 1 {
return Err(unknown_option(&arg.to_string_lossy()));
}
inputs.file(arg);
Ok(())
}
pub struct Parsed {
pub output: PathBuf,
pub build_id: BuildId,
pub undefined: Vec<String>,
pub version_script: Option<String>,
pub undefined_version: bool,
pub rpath: Vec<String>,
pub hash_style: HashStyle,
pub z: ZOptions,
pub no_undefined: bool,
pub emulation: Option<String>,
pub threads: Option<usize>,
pub entry: String,
pub entry_given: bool,
pub soname: Option<String>,
pub interpreter: String,
pub icf: IcfMode,
pub sw: Switches,
pub macho_dynamic: bool,
pub macho_arch: Option<MachoTarget>,
pub macho_platform: Option<PlatformVersion>,
pub macho_dead_strip: bool,
}
impl Default for Parsed {
fn default() -> Self {
Self {
output: PathBuf::from("a.out"),
build_id: BuildId::None,
undefined: Vec::new(),
version_script: None,
undefined_version: true,
rpath: Vec::new(),
z: ZOptions::new(),
no_undefined: false,
hash_style: HashStyle::Both,
emulation: None,
threads: None,
entry: String::from("_start"),
entry_given: false,
soname: None,
interpreter: String::from(DEFAULT_INTERP),
icf: IcfMode::None,
sw: Switches::default(),
macho_dynamic: false,
macho_arch: None,
macho_platform: None,
macho_dead_strip: false,
}
}
}
impl Parsed {
pub fn zkeyword(&mut self, kw: &str) -> std::result::Result<(), String> {
if kw == "defs" {
self.no_undefined = true;
return Ok(());
}
if kw == "undefs" {
self.no_undefined = false;
return Ok(());
}
super::zopts::keyword(&mut self.z, kw)
}
pub fn into_options(self, inputs: Inputs) -> Options {
Options {
lib_groups: inputs.lib_groups,
pie: self.sw.pie,
export_dynamic: self.sw.export_dynamic,
strip: self.sw.strip,
hash_style: self.hash_style,
rpath: self.rpath.join(":"),
build_id: self.build_id,
undefined: self.undefined,
version_script: self.version_script,
undefined_version: self.undefined_version,
z: self.z,
no_undefined: self.no_undefined,
as_needed: inputs.as_needed_flags,
emulation: self.emulation,
threads: self.threads,
static_link: self.sw.static_link,
from_l: inputs.from_l,
search: inputs.search,
sysroot: inputs.sysroot,
entry_given: self.entry_given,
inputs: inputs.paths,
output: self.output,
entry: self.entry,
shared: self.sw.shared,
soname: self.soname,
dynamic_exec: self.sw.dynamic_exec,
interpreter: self.interpreter,
gc_sections: self.sw.gc_sections,
icf: self.icf,
relax: !self.sw.relax_off,
relax_named: self.sw.relax_named,
no_fork: self.sw.no_fork,
macho_dynamic: self.macho_dynamic,
macho_arch: self.macho_arch,
macho_platform: self.macho_platform,
macho_dead_strip: self.macho_dead_strip,
}
}
}