use crate::error::{Error, Result};
enum Pattern {
Exact(Vec<u8>),
Glob(Vec<u8>),
}
impl Pattern {
fn matches(&self, name: &[u8]) -> bool {
match self {
Self::Exact(text) => text == name,
Self::Glob(pattern) => glob(pattern, name),
}
}
const fn is_exact(&self) -> bool {
matches!(self, Self::Exact(_))
}
}
#[derive(Default)]
pub struct VersionScript {
global: Vec<Pattern>,
local: Vec<Pattern>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
Global,
Local,
Unmentioned,
}
impl VersionScript {
pub fn visibility(&self, name: &[u8]) -> Visibility {
let global = Self::rank(&self.global, name);
let local = Self::rank(&self.local, name);
match (global, local) {
(None, None) => Visibility::Unmentioned,
(None, Some(_)) => Visibility::Local,
(Some(g), Some(l)) if l > g => Visibility::Local,
(Some(_), _) => Visibility::Global,
}
}
fn rank(list: &[Pattern], name: &[u8]) -> Option<u8> {
let mut best = None;
for pattern in list {
if !pattern.matches(name) {
continue;
}
let rank = u8::from(pattern.is_exact()) + 1;
best = Some(best.map_or(rank, |b: u8| b.max(rank)));
}
best
}
pub fn exact_names(&self) -> impl Iterator<Item = &[u8]> {
self.global
.iter()
.chain(self.local.iter())
.filter_map(|p| match p {
Pattern::Exact(name) => Some(name.as_slice()),
Pattern::Glob(_) => None,
})
}
pub fn hides_anything(&self) -> bool {
!self.local.is_empty()
}
}
pub fn parse(path: &str, text: &str) -> Result<VersionScript> {
let mut script = VersionScript::default();
let body = anonymous_body(path, text)?;
let body = body.as_str();
let mut local = false;
for entry in body.split(';') {
let entry = entry.trim();
if entry.is_empty() {
continue;
}
match strip_label(entry) {
Some(("global", rest)) => {
local = false;
push(&mut script, local, rest);
}
Some(("local", rest)) => {
local = true;
push(&mut script, local, rest);
}
Some((other, _)) => {
return Err(script_error(
path,
format!("`{other}:` is not a version script label"),
));
}
None => push(&mut script, local, entry),
}
}
Ok(script)
}
fn strip_label(entry: &str) -> Option<(&str, &str)> {
let (label, rest) = entry.split_once(':')?;
Some((label.trim(), rest.trim()))
}
fn push(script: &mut VersionScript, local: bool, name: &str) {
if name.is_empty() {
return;
}
let pattern = if name.contains('*') || name.contains('?') {
Pattern::Glob(name.as_bytes().to_vec())
} else {
Pattern::Exact(name.as_bytes().to_vec())
};
if local {
script.local.push(pattern);
} else {
script.global.push(pattern);
}
}
fn anonymous_body(path: &str, text: &str) -> Result<String> {
let text = strip_comments(text);
let text = text.as_str();
let open = text.find('{').ok_or_else(|| {
script_error(path, "no version node: expected `{ ... };`".to_string())
})?;
let name = text.get(..open).unwrap_or("").trim();
if !name.is_empty() {
return Err(script_error(
path,
format!(
"the named version node `{name}` needs `.gnu.version_d` \
records, which this linker does not emit; an anonymous node \
(`{{ global: ...; local: *; }};`) is what it implements"
),
));
}
let close = text.rfind('}').ok_or_else(|| {
script_error(path, "the version node is not closed".to_string())
})?;
let body = text.get(open + 1..close).unwrap_or("");
if body.contains('{') {
return Err(script_error(
path,
"a nested block (`extern \"C++\" { ... }`) is not implemented"
.to_string(),
));
}
if text.get(close + 1..).is_some_and(|rest| rest.contains('{')) {
return Err(script_error(
path,
"more than one version node needs `.gnu.version_d` records, \
which this linker does not emit"
.to_string(),
));
}
Ok(body.to_string())
}
fn strip_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
loop {
let line = rest.find('#');
let block = rest.find("/*");
let Some(at) = line.into_iter().chain(block).min() else {
out.push_str(rest);
return out;
};
out.push_str(rest.get(..at).unwrap_or(""));
out.push(' ');
let after = rest.get(at..).unwrap_or("");
rest = if Some(at) == line {
after.find('\n').map_or("", |end| &after[end..])
} else {
after.find("*/").map_or("", |end| &after[end + 2..])
};
}
}
fn glob(pattern: &[u8], name: &[u8]) -> bool {
let (mut p, mut n) = (0usize, 0usize);
let (mut star, mut retry) = (None, 0usize);
while n < name.len() {
match pattern.get(p) {
Some(b'*') => {
star = Some(p);
retry = n;
p += 1;
}
Some(b'?') => {
p += 1;
n += 1;
}
Some(&c) if c == name[n] => {
p += 1;
n += 1;
}
_ => match star {
Some(at) => {
p = at + 1;
retry += 1;
n = retry;
}
None => return false,
},
}
}
pattern
.get(p..)
.is_some_and(|rest| rest.iter().all(|&c| c == b'*'))
}
fn script_error(path: &str, what: String) -> Error {
Error::script(path.to_string(), what)
}