use super::Error;
use crate::discovery::{ResolvedItem, ResolvedItemKind, SymbolDeclaration, SymbolSafety};
use crate::layout;
use crate::pdb::ir::{
Alignment, CallingConvention, Database, PointerKind, PrimitiveKind, Type, TypeId,
};
use std::collections::BTreeSet;
use std::fmt::Write as _;
struct TypeFact {
rust: String,
size: u64,
alignment: u64,
}
enum SourceAbi {
Void,
Scalar {
kind: PrimitiveKind,
size: u64,
alignment: u64,
},
Pointer {
size: u64,
alignment: u64,
},
Other,
}
pub(super) fn render(item: &ResolvedItem, database: &Database) -> Result<Vec<u8>, Error> {
let ResolvedItemKind::Symbols { declarations } = &item.kind else {
unreachable!()
};
let mut out = String::from("const _: () = assert!(::core::mem::size_of::<usize>() == 8);\n");
for declaration in declarations {
match declaration {
SymbolDeclaration::Function(function) => {
render_function(&mut out, item, database, function)?
}
SymbolDeclaration::Global(global) => render_global(&mut out, item, database, global)?,
}
}
syn::parse_file(&out).map_err(|source| Error::InvalidFragment {
rust_name: "symbols".into(),
source,
})?;
Ok(out.into_bytes())
}
fn render_function(
out: &mut String,
item: &ResolvedItem,
db: &Database,
source: &crate::discovery::SymbolFunction,
) -> Result<(), Error> {
let function = match db.function(&source.name) {
Ok(function) => function,
Err(crate::pdb::error::Error::Missing { .. }) if db.globals.contains_key(&source.name) => {
return Err(Error::SymbolKindMismatch {
image: item.image.image.clone(),
name: source.name.clone(),
expected: "function",
actual: "global",
});
}
Err(error) => {
return Err(Error::SymbolLookup {
image: item.image.image.clone(),
kind: "function",
name: source.name.clone(),
source: Box::new(error),
});
}
};
let signature = match db.types.get(&function.signature) {
Some(Type::Procedure(signature)) => signature,
Some(Type::MemberFunction { .. }) => {
return unsupported(
&source.name,
&source.name,
"function symbol has a member-function type",
);
}
Some(_) => {
return unsupported(
&source.name,
&source.name,
"function symbol is not a procedure",
);
}
None => {
return unsupported(
&source.name,
&source.name,
"function symbol has a missing PDB type",
);
}
};
if signature.variadic {
return unsupported(&source.name, &source.name, "PDB procedure is variadic");
}
if signature.arguments.len() != source.arguments.len() {
return unsupported(
&source.name,
&source.name,
"PDB procedure argument count differs from Rust declaration",
);
}
if !matches!(
signature.calling_convention,
CallingConvention::NearC | CallingConvention::NearStd | CallingConvention::NearFast
) {
return unsupported(
&source.name,
&source.name,
"unsupported PDB calling convention",
);
}
let return_fact = validate_function_type(
db,
signature.return_type,
source.output.as_deref().unwrap_or("()"),
&source.name,
"return",
)?;
let arguments = source
.arguments
.iter()
.zip(&signature.arguments)
.enumerate()
.map(|(index, (argument, id))| {
validate_function_type(
db,
*id,
&argument.ty,
&source.name,
&format!("argument {index}"),
)
})
.collect::<Result<Vec<_>, _>>()?;
emit_fact(out, &return_fact);
for fact in &arguments {
emit_fact(out, fact);
}
attributes(out, &source.attributes);
if source.name.chars().any(char::is_uppercase) {
out.push_str("#[allow(non_snake_case)]\n");
}
let unsafe_prefix = if source.safety == SymbolSafety::Unsafe {
"unsafe "
} else {
""
};
let arguments_source = source
.arguments
.iter()
.map(|arg| format!("{}: {}", arg.name, arg.ty))
.collect::<Vec<_>>()
.join(", ");
let argument_types = source
.arguments
.iter()
.map(|argument| argument.ty.as_str())
.collect::<Vec<_>>()
.join(", ");
let output = source
.output
.as_ref()
.map(|ty| format!(" -> {ty}"))
.unwrap_or_default();
let pointer = format!(
"{}extern \"system\" fn({argument_types}){output}",
unsafe_prefix
);
writeln!(
out,
"{}{}extern \"system\" fn {}({arguments_source}){output} {{",
visibility(&source.visibility),
unsafe_prefix,
source.name
)
.expect("writing to a String cannot fail");
writeln!(
out,
" let address = ({})().wrapping_add(0x{:x}usize);",
item.image.base, function.rva.0
)
.expect("writing to a String cannot fail");
out.push_str(" // SAFETY: exact PDB lookup validated the procedure ABI; the user-owned base provider supplies the image base.\n");
writeln!(
out,
" let target: {pointer} = unsafe {{ ::core::mem::transmute(address) }};"
)
.expect("writing to a String cannot fail");
let names = source
.arguments
.iter()
.map(|arg| arg.name.as_str())
.collect::<Vec<_>>()
.join(", ");
if source.safety == SymbolSafety::Safe {
writeln!(out, " target({names})").expect("writing to a String cannot fail");
} else {
out.push_str(" // SAFETY: the source declaration is unsafe, so the caller upholds the foreign function's obligations.\n");
writeln!(out, " unsafe {{ target({names}) }}").expect("writing to a String cannot fail");
}
out.push_str("}\n");
Ok(())
}
fn render_global(
out: &mut String,
item: &ResolvedItem,
db: &Database,
source: &crate::discovery::SymbolGlobal,
) -> Result<(), Error> {
let global = match db.global(&source.name) {
Ok(global) => global,
Err(crate::pdb::error::Error::Missing { .. })
if db.functions.contains_key(&source.name) =>
{
return Err(Error::SymbolKindMismatch {
image: item.image.image.clone(),
name: source.name.clone(),
expected: "global",
actual: "function",
});
}
Err(error) => {
return Err(Error::SymbolLookup {
image: item.image.image.clone(),
kind: "global",
name: source.name.clone(),
source: Box::new(error),
});
}
};
let fact = validate_global_type(db, global.ty, &source.ty, &source.name)?;
emit_fact(out, &Some(fact));
attributes(out, &source.attributes);
if source.name.chars().any(char::is_uppercase) {
out.push_str("#[allow(non_snake_case)]\n");
}
let unsafe_prefix = if source.safety == SymbolSafety::Unsafe || source.mutable {
"unsafe "
} else {
""
};
let pointer = if source.mutable { "*mut" } else { "*const" };
writeln!(
out,
"{}{}fn {}() -> {pointer} {} {{",
visibility(&source.visibility),
unsafe_prefix,
source.name,
source.ty
)
.expect("writing to a String cannot fail");
write!(
out,
" ({})().wrapping_add(0x{:x}usize) as {pointer} {}\n}}\n",
item.image.base, global.rva.0, source.ty
)
.expect("writing to a String cannot fail");
Ok(())
}
fn validate_function_type(
db: &Database,
id: TypeId,
rust: &str,
name: &str,
role: &str,
) -> Result<Option<TypeFact>, Error> {
let parsed = syn::parse_str::<syn::Type>(rust).map_err(|_| Error::Unsupported {
pdb_name: name.into(),
rust_name: rust.into(),
detail: "invalid Rust ABI type".into(),
})?;
match (source_abi(&parsed), resolve(db, id, name, rust)?) {
(SourceAbi::Void, Type::Void) => Ok(None),
(
SourceAbi::Scalar {
kind,
size,
alignment,
},
Type::Primitive {
kind: actual,
size: actual_size,
alignment: Alignment::Known(actual_alignment),
},
) if *actual_size == size
&& *actual_alignment == alignment
&& primitive_matches(kind, *actual, size) =>
{
Ok(Some(TypeFact {
rust: rust.into(),
size,
alignment,
}))
}
(
SourceAbi::Pointer {
size: 8,
alignment: 8,
},
Type::Pointer {
size: 8,
alignment: Alignment::Known(8),
kind: PointerKind::Pointer,
..
},
) => Ok(Some(TypeFact {
rust: rust.into(),
size: 8,
alignment: 8,
})),
_ => mismatch(name, rust, role),
}
}
fn validate_global_type(
db: &Database,
id: TypeId,
rust: &str,
name: &str,
) -> Result<TypeFact, Error> {
let parsed = syn::parse_str::<syn::Type>(rust).map_err(|_| Error::Unsupported {
pdb_name: name.into(),
rust_name: rust.into(),
detail: "invalid Rust global type".into(),
})?;
match source_abi(&parsed) {
SourceAbi::Scalar {
kind,
size,
alignment,
} => match resolve(db, id, name, rust)? {
Type::Primitive {
kind: actual,
size: actual_size,
alignment: Alignment::Known(actual_alignment),
} if *actual_size == size
&& *actual_alignment == alignment
&& primitive_matches(kind, *actual, size) =>
{
Ok(TypeFact {
rust: rust.into(),
size,
alignment,
})
}
_ => mismatch(name, rust, "global"),
},
SourceAbi::Pointer { .. } => match resolve(db, id, name, rust)? {
Type::Pointer {
size: 8,
alignment: Alignment::Known(8),
kind: PointerKind::Pointer,
..
} => Ok(TypeFact {
rust: rust.into(),
size: 8,
alignment: 8,
}),
_ => mismatch(name, rust, "global"),
},
SourceAbi::Void => mismatch(name, rust, "global"),
SourceAbi::Other => match resolve(db, id, name, rust)? {
Type::Record(record_id) => {
let layout = layout::record(db, *record_id).map_err(|source| Error::Layout {
pdb_name: name.into(),
source,
})?;
let Alignment::Known(alignment) = layout.alignment else {
return unsupported(name, rust, "global record has unavailable alignment");
};
if alignment == 0 || !alignment.is_power_of_two() {
return unsupported(name, rust, "global record has invalid alignment");
}
Ok(TypeFact {
rust: rust.into(),
size: layout.size,
alignment,
})
}
_ => mismatch(name, rust, "global"),
},
}
}
fn resolve<'a>(
db: &'a Database,
mut id: TypeId,
name: &str,
rust: &str,
) -> Result<&'a Type, Error> {
let mut seen = BTreeSet::new();
loop {
if !seen.insert(id) {
return unsupported(name, rust, "PDB modifier type cycle");
}
match db.types.get(&id) {
Some(Type::Modifier { target, .. }) => id = *target,
Some(ty) => return Ok(ty),
None => return unsupported(name, rust, "missing PDB type"),
}
}
}
fn source_abi(ty: &syn::Type) -> SourceAbi {
if matches!(ty, syn::Type::Tuple(tuple) if tuple.elems.is_empty()) {
return SourceAbi::Void;
}
if matches!(ty, syn::Type::Ptr(_)) {
return SourceAbi::Pointer {
size: 8,
alignment: 8,
};
}
source_scalar(ty)
.map(|(kind, size, alignment)| SourceAbi::Scalar {
kind,
size,
alignment,
})
.unwrap_or(SourceAbi::Other)
}
fn source_scalar(ty: &syn::Type) -> Option<(PrimitiveKind, u64, u64)> {
let syn::Type::Path(path) = ty else {
return None;
};
if path.qself.is_some() || path.path.leading_colon.is_some() || path.path.segments.len() != 1 {
return None;
}
let segment = path.path.segments.first()?;
if !matches!(segment.arguments, syn::PathArguments::None) {
return None;
}
match segment.ident.to_string().as_str() {
"i8" => Some((PrimitiveKind::Signed, 1, 1)),
"i16" => Some((PrimitiveKind::Signed, 2, 2)),
"i32" => Some((PrimitiveKind::Signed, 4, 4)),
"i64" | "isize" => Some((PrimitiveKind::Signed, 8, 8)),
"u8" => Some((PrimitiveKind::Unsigned, 1, 1)),
"u16" => Some((PrimitiveKind::Unsigned, 2, 2)),
"u32" => Some((PrimitiveKind::Unsigned, 4, 4)),
"u64" | "usize" => Some((PrimitiveKind::Unsigned, 8, 8)),
"bool" => Some((PrimitiveKind::Boolean, 1, 1)),
"f32" => Some((PrimitiveKind::Float, 4, 4)),
"f64" => Some((PrimitiveKind::Float, 8, 8)),
_ => None,
}
}
fn primitive_matches(expected: PrimitiveKind, actual: PrimitiveKind, size: u64) -> bool {
expected == actual
|| (size == 1
&& matches!(
(expected, actual),
(
PrimitiveKind::Signed | PrimitiveKind::Unsigned,
PrimitiveKind::Character
)
))
}
fn emit_fact(out: &mut String, fact: &Option<TypeFact>) {
if let Some(fact) = fact {
write!(out, "const _: () = assert!(::core::mem::size_of::<{}>() == {});\nconst _: () = assert!(::core::mem::align_of::<{}>() == {});\n", fact.rust, fact.size, fact.rust, fact.alignment)
.expect("writing to a String cannot fail");
}
}
fn mismatch<T>(name: &str, rust: &str, role: &str) -> Result<T, Error> {
unsupported(name, rust, format!("PDB ABI type differs for {role}"))
}
fn unsupported<T>(name: &str, rust: &str, detail: impl Into<String>) -> Result<T, Error> {
Err(Error::Unsupported {
pdb_name: name.into(),
rust_name: rust.into(),
detail: detail.into(),
})
}
fn attributes(out: &mut String, attrs: &[String]) {
for attr in attrs {
out.push_str(attr);
out.push('\n');
}
}
fn visibility(value: &str) -> String {
if value.is_empty() {
String::new()
} else {
format!("{value} ")
}
}