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(path, &mut script, local, rest)?;
}
Some(("local", rest)) => {
local = true;
push(path, &mut script, local, rest)?;
}
Some((other, _)) => {
return Err(script_error(
path,
format!("`{other}:` is not a version script label"),
));
}
None => push(path, &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(
path: &str,
script: &mut VersionScript,
local: bool,
name: &str,
) -> Result<()> {
if name.is_empty() {
return Ok(());
}
let wildcard = has_wildcard(name);
let name = unquote(name);
let pattern = if wildcard {
validate_glob(path, name)?;
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);
}
Ok(())
}
fn has_wildcard(token: &str) -> bool {
token.bytes().any(|c| matches!(c, b'?' | b'*' | b'['))
}
fn unquote(token: &str) -> &str {
token
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(token)
}
fn validate_glob(path: &str, pattern: &str) -> Result<()> {
let bytes = pattern.as_bytes();
let mut i = 0usize;
while let Some(&c) = bytes.get(i) {
match c {
b'\\' => i = i.saturating_add(2),
b'[' => {
let end = class_end(bytes, i).ok_or_else(|| {
script_error(
path,
format!("unterminated `[` in pattern `{pattern}`"),
)
})?;
check_ranges(path, pattern, bytes, i, end)?;
i = end;
}
_ => i = i.saturating_add(1),
}
}
Ok(())
}
fn class_end(bytes: &[u8], open: usize) -> Option<usize> {
let first = open.checked_add(1)?;
let first = if matches!(bytes.get(first), Some(b'^' | b'!')) {
first.checked_add(1)?
} else {
first
};
let from = first.checked_add(1)?;
let at = bytes.get(from..)?.iter().position(|&c| c == b']')?;
from.checked_add(at)?.checked_add(1)
}
fn check_ranges(
path: &str,
pattern: &str,
bytes: &[u8],
open: usize,
end: usize,
) -> Result<()> {
let mut i = open.saturating_add(1);
while i < end.saturating_sub(1) {
let (Some(&start), Some(&dash), Some(&last)) =
(bytes.get(i), bytes.get(i + 1), bytes.get(i + 2))
else {
return Ok(());
};
if dash == b'-' && last != b']' {
if start > last {
return Err(script_error(
path,
format!("reversed range in pattern `{pattern}`"),
));
}
i = i.saturating_add(3);
} else {
i = i.saturating_add(1);
}
}
Ok(())
}
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() {
if pattern.get(p) == Some(&b'*') {
star = Some(p);
retry = n;
p = p.saturating_add(1);
continue;
}
match one(pattern, p, name[n]) {
Some(next) => {
p = next;
n = n.saturating_add(1);
}
None => match star {
Some(at) => {
p = at.saturating_add(1);
retry = retry.saturating_add(1);
n = retry;
}
None => return false,
},
}
}
pattern
.get(p..)
.is_some_and(|rest| rest.iter().all(|&c| c == b'*'))
}
fn one(pattern: &[u8], p: usize, byte: u8) -> Option<usize> {
match pattern.get(p)? {
b'?' => p.checked_add(1),
b'[' => {
let end = class_end(pattern, p)?;
in_class(pattern, p, end, byte).then_some(end)
}
b'\\' => {
let literal = *pattern.get(p.checked_add(1)?)?;
(literal == byte).then(|| p.saturating_add(2))
}
&c => (c == byte).then(|| p.saturating_add(1)),
}
}
fn in_class(pattern: &[u8], open: usize, end: usize, byte: u8) -> bool {
let mut i = open.saturating_add(1);
let invert = matches!(pattern.get(i), Some(b'^' | b'!'));
if invert {
i = i.saturating_add(1);
}
let mut hit = false;
while i < end.saturating_sub(1) {
let Some(&c) = pattern.get(i) else {
break;
};
if pattern.get(i.saturating_add(1)) == Some(&b'-')
&& pattern
.get(i.saturating_add(2))
.is_some_and(|&last| last != b']')
{
let last = pattern.get(i.saturating_add(2)).copied().unwrap_or(c);
if (c..=last).contains(&byte) {
hit = true;
}
i = i.saturating_add(3);
continue;
}
if c == byte {
hit = true;
}
i = i.saturating_add(1);
}
hit != invert
}
fn script_error(path: &str, what: String) -> Error {
Error::script(path.to_string(), what)
}