use super::{field_initial_value_size, get, Loader, SecurityOwner};
use crate::{
dotnet::{
entries::*,
md::streams::tables_stream::{coded_tokens::*, *},
signature::ElementType,
},
error::{HaoError, Result},
};
impl Loader<'_> {
pub(super) fn link(&mut self) -> Result<()> {
self.link_nested_classes()?;
self.link_member_owners();
let interface_impls = self.link_interfaces()?;
self.link_constants()?;
self.link_field_marshal()?;
let decl_security = self.link_decl_security()?;
self.link_class_layout()?;
self.link_field_layout()?;
self.link_method_semantics()?;
self.link_method_impls()?;
self.link_impl_map()?;
self.link_field_rvas()?;
self.link_generic_params()?;
let constraints = self.link_generic_param_constraints()?;
self.link_custom_attributes(&interface_impls, &decl_security, &constraints)
}
fn link_nested_classes(&mut self) -> Result<()> {
let l = self.locations;
let mut is_nested = vec![false; self.t.type_defs.len()];
for row in self.rows::<NestedClassTableRow>(l.nested_class)? {
let nested = get(&self.t.type_defs, row.nested_class.0, "TypeDef")?;
let enclosing = get(&self.t.type_defs, row.enclosing_class.0, "TypeDef")?;
nested.get_mut().declaring_type = enclosing.downgrade();
enclosing.get_mut().nested_types.push(nested);
is_nested[row.nested_class.0 as usize - 1] = true;
}
self.t.top_level_types = self
.t
.type_defs
.iter()
.zip(is_nested)
.filter(|(_, nested)| !nested)
.map(|(t, _)| t.clone())
.collect();
Ok(())
}
fn link_member_owners(&mut self) {
for ty in &self.t.type_defs {
let weak = ty.downgrade();
let ty = ty.get();
for f in &ty.fields {
f.get_mut().declaring_type = weak.clone();
}
for m in &ty.methods {
m.get_mut().declaring_type = weak.clone();
}
}
}
fn link_interfaces(&mut self) -> Result<Vec<(Entry<TypeDef>, usize)>> {
let l = self.locations;
let mut interface_impls = Vec::new();
for row in self.rows::<InterfaceImplTableRow>(l.interface_impl)? {
let class = get(&self.t.type_defs, row.class.0, "TypeDef")?;
let interface = self
.type_def_or_ref(row.interface)?
.ok_or(HaoError::InvalidEntryReference("InterfaceImpl", 0))?;
let index = class.get().interfaces.len();
class
.get_mut()
.interfaces
.push(InterfaceImpl::new(interface));
interface_impls.push((class, index));
}
Ok(interface_impls)
}
fn link_constants(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<ConstantTableRow>(l.constant)? {
let constant = Constant {
element_type: ElementType::from_repr(row.ty)
.ok_or(HaoError::InvalidSignatureElementType(row.ty, 0))?,
value: self.blob(row.value)?.to_vec(),
};
let rid = row.parent.rid;
match row.parent.target {
HasConstantToken::Field => {
get(&self.t.fields, rid, "Field")?.get_mut().constant = Some(constant)
}
HasConstantToken::Param => {
get(&self.t.params, rid, "Param")?.get_mut().constant = Some(constant)
}
HasConstantToken::Property => {
get(&self.t.properties, rid, "Property")?.get_mut().constant = Some(constant)
}
}
}
Ok(())
}
fn link_field_marshal(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<FieldMarshalTableRow>(l.field_marshal)? {
let marshal = Some(self.blob(row.native_type)?.to_vec());
let rid = row.parent.rid;
match row.parent.target {
HasFieldMarshalToken::Field => {
get(&self.t.fields, rid, "Field")?.get_mut().marshal = marshal
}
HasFieldMarshalToken::Param => {
get(&self.t.params, rid, "Param")?.get_mut().marshal = marshal
}
}
}
Ok(())
}
fn link_decl_security(&mut self) -> Result<Vec<SecurityOwner>> {
let l = self.locations;
let mut decl_security = Vec::new();
for row in self.rows::<DeclSecurityTableRow>(l.decl_security)? {
let security = DeclSecurity {
action: row.action,
permission_set: self.blob(row.permission_set)?.to_vec(),
custom_attributes: Vec::new(),
};
let rid = row.parent.rid;
let owner = match row.parent.target {
HasDeclSecurityToken::TypeDef => {
let ty = get(&self.t.type_defs, rid, "TypeDef")?;
let index = ty.get().security.len();
ty.get_mut().security.push(security);
SecurityOwner::TypeDef(ty, index)
}
HasDeclSecurityToken::Method => {
let m = get(&self.t.methods, rid, "Method")?;
let index = m.get().security.len();
m.get_mut().security.push(security);
SecurityOwner::Method(m, index)
}
HasDeclSecurityToken::Assembly => {
let a = get(&self.t.assembly, rid, "Assembly")?;
let index = a.get().security.len();
a.get_mut().security.push(security);
SecurityOwner::Assembly(a, index)
}
};
decl_security.push(owner);
}
Ok(decl_security)
}
fn link_class_layout(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<ClassLayoutTableRow>(l.class_layout)? {
get(&self.t.type_defs, row.parent.0, "TypeDef")?
.get_mut()
.class_layout = Some(ClassLayout {
packing_size: row.packing_size,
class_size: row.class_size,
});
}
Ok(())
}
fn link_field_layout(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<FieldLayoutTableRow>(l.field_layout)? {
get(&self.t.fields, row.field.0, "Field")?.get_mut().offset = Some(row.offset);
}
Ok(())
}
fn link_method_semantics(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<MethodSemanticsTableRow>(l.method_semantics)? {
let method = get(&self.t.methods, row.method.0, "Method")?;
let rid = row.association.rid;
let s = row.semantic;
match row.association.target {
HasSemanticToken::Property => {
let prop = get(&self.t.properties, rid, "Property")?;
let mut prop = prop.get_mut();
if s.contains(MethodSemanticsFlags::Getter) {
prop.getter = Some(method);
} else if s.contains(MethodSemanticsFlags::Setter) {
prop.setter = Some(method);
} else {
prop.other_methods.push(method);
}
}
HasSemanticToken::Event => {
let event = get(&self.t.events, rid, "Event")?;
let mut event = event.get_mut();
if s.contains(MethodSemanticsFlags::AddOn) {
event.add = Some(method);
} else if s.contains(MethodSemanticsFlags::RemoveOn) {
event.remove = Some(method);
} else if s.contains(MethodSemanticsFlags::Fire) {
event.fire = Some(method);
} else {
event.other_methods.push(method);
}
}
}
}
Ok(())
}
fn link_method_impls(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<MethodImplTableRow>(l.method_impl)? {
let class = get(&self.t.type_defs, row.class.0, "TypeDef")?;
let method_impl = MethodImpl {
body: self.method_def_or_ref(row.method_body)?,
declaration: self.method_def_or_ref(row.method_declaration)?,
};
class.get_mut().method_impls.push(method_impl);
}
Ok(())
}
fn link_impl_map(&mut self) -> Result<()> {
let l = self.locations;
for row in self.rows::<ImplMapTableRow>(l.impl_map)? {
let impl_map = Some(ImplMap {
flags: row.mapping_flags,
import_name: self.string(row.import_name)?,
scope: get(&self.t.module_refs, row.import_scope.0, "ModuleRef")?,
});
let rid = row.member_forwarded.rid;
match row.member_forwarded.target {
MemberForwardedToken::Field => {
get(&self.t.fields, rid, "Field")?.get_mut().impl_map = impl_map
}
MemberForwardedToken::Method => {
get(&self.t.methods, rid, "Method")?.get_mut().impl_map = impl_map
}
}
}
Ok(())
}
fn link_field_rvas(&mut self) -> Result<()> {
let l = self.locations;
let mut field_rvas = self.rows::<FieldRVATableRow>(l.field_rva)?;
field_rvas.sort_by_key(|r| r.rva);
for (i, row) in field_rvas.iter().enumerate() {
let field = get(&self.t.fields, row.field.0, "Field")?;
let next_rva = field_rvas
.get(i + 1)
.map(|n| n.rva)
.filter(|n| *n > row.rva);
let size = field_initial_value_size(&field.get().signature.ty)
.or_else(|| next_rva.map(|n| (n - row.rva) as usize));
let size = match size {
Some(size) => size,
None if self.options.strict_field_rva => {
return Err(HaoError::BadImageFormat(
"Could not determine FieldRVA data size",
))
}
None => continue,
};
let data = self
.md
.pe_image
.create_reader(row.rva, None)?
.read_slice(size)?
.to_vec();
field.get_mut().initial_value = Some(data);
}
Ok(())
}
fn link_generic_params(&mut self) -> Result<()> {
let l = self.locations;
for (entry, row) in self
.t
.generic_params
.iter()
.zip(self.rows::<GenericParamTableRow>(l.generic_param)?)
{
let rid = row.owner.rid;
match row.owner.target {
TypeOrMethodDefToken::TypeDef => get(&self.t.type_defs, rid, "TypeDef")?
.get_mut()
.generic_params
.push(entry.clone()),
TypeOrMethodDefToken::Method => get(&self.t.methods, rid, "Method")?
.get_mut()
.generic_params
.push(entry.clone()),
}
}
for owner in self
.t
.type_defs
.iter()
.map(|t| t.get().generic_params.clone())
.chain(
self.t
.methods
.iter()
.map(|m| m.get().generic_params.clone()),
)
{
debug_assert!(owner
.windows(2)
.all(|w| w[0].get().number <= w[1].get().number));
}
Ok(())
}
fn link_generic_param_constraints(&mut self) -> Result<Vec<(Entry<GenericParam>, usize)>> {
let l = self.locations;
let mut constraints = Vec::new();
for row in self.rows::<GenericParamConstraintTableRow>(l.generic_param_constraint)? {
let owner = get(&self.t.generic_params, row.owner.0, "GenericParam")?;
let constraint = self
.type_def_or_ref(row.constraint)?
.ok_or(HaoError::InvalidEntryReference("GenericParamConstraint", 0))?;
let index = owner.get().constraints.len();
owner.get_mut().constraints.push(GenericParamConstraint {
constraint,
custom_attributes: Vec::new(),
});
constraints.push((owner, index));
}
Ok(constraints)
}
fn link_custom_attributes(
&mut self,
interface_impls: &[(Entry<TypeDef>, usize)],
decl_security: &[SecurityOwner],
constraints: &[(Entry<GenericParam>, usize)],
) -> Result<()> {
let l = self.locations;
for row in self.rows::<CustomAttributeTableRow>(l.custom_attribute)? {
let constructor = match row.ty.target {
CustomAttributeTypeToken::Method => {
CustomAttributeCtor::Method(get(&self.t.methods, row.ty.rid, "Method")?)
}
CustomAttributeTypeToken::MemberRef => CustomAttributeCtor::MemberRef(get(
&self.t.member_refs,
row.ty.rid,
"MemberRef",
)?),
_ => {
return Err(HaoError::InvalidCodedToken(
row.ty.rid,
"CustomAttributeType",
))
}
};
let attribute = CustomAttribute {
constructor,
value: self.blob(row.value)?.to_vec(),
};
let rid = row.parent.rid;
let name: &'static str = row.parent.target.into();
let t = &self.t;
macro_rules! push {
($table:expr) => {
get(&$table, rid, name)?
.get_mut()
.custom_attributes
.push(attribute)
};
}
let index = |len: usize| {
rid.checked_sub(1)
.map(|i| i as usize)
.filter(|i| *i < len)
.ok_or(HaoError::InvalidEntryReference(
"CustomAttribute parent",
rid as usize,
))
};
match row.parent.target {
HasCustomAttributeToken::Method => push!(t.methods),
HasCustomAttributeToken::Field => push!(t.fields),
HasCustomAttributeToken::TypeRef => push!(t.type_refs),
HasCustomAttributeToken::TypeDef => push!(t.type_defs),
HasCustomAttributeToken::Param => push!(t.params),
HasCustomAttributeToken::MemberRef => push!(t.member_refs),
HasCustomAttributeToken::Module => push!(t.module),
HasCustomAttributeToken::Property => push!(t.properties),
HasCustomAttributeToken::Event => push!(t.events),
HasCustomAttributeToken::ModuleRef => push!(t.module_refs),
HasCustomAttributeToken::TypeSpec => push!(t.type_specs),
HasCustomAttributeToken::Assembly => push!(t.assembly),
HasCustomAttributeToken::AssemblyRef => push!(t.assembly_refs),
HasCustomAttributeToken::File => push!(t.files),
HasCustomAttributeToken::ExportedType => push!(t.exported_types),
HasCustomAttributeToken::ManifestResource => push!(t.resources),
HasCustomAttributeToken::GenericParam => push!(t.generic_params),
HasCustomAttributeToken::MethodSpec => push!(t.method_specs),
HasCustomAttributeToken::InterfaceImpl => {
let (class, i) = &interface_impls[index(interface_impls.len())?];
class.get_mut().interfaces[*i]
.custom_attributes
.push(attribute);
}
HasCustomAttributeToken::GenericParamConstraint => {
let (owner, i) = &constraints[index(constraints.len())?];
owner.get_mut().constraints[*i]
.custom_attributes
.push(attribute);
}
HasCustomAttributeToken::DeclSecurity => {
decl_security[index(decl_security.len())?].push_attribute(attribute)
}
HasCustomAttributeToken::StandAloneSig
| HasCustomAttributeToken::Unused1
| HasCustomAttributeToken::Unused2 => {}
}
}
Ok(())
}
}