use pewter::pe::sections::cor20::{Cor20Flags, ImageCor20Header};
use super::Module;
use crate::dotnet::{
entries::{
well_known::{SystemType, WellKnown},
*,
},
md::streams::tables_stream::{AssemblyFlags, TypeAttributes},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet), repr(C))]
pub enum ModuleKind {
#[default]
Dll,
Console,
Windows,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetRuntime {
NetCore(u16),
NetFramework,
NetCoreImplementation(u16),
}
impl TargetRuntime {
fn corlib(self) -> AssemblyRef {
let (name, version, token) = match self {
Self::NetCore(major) => (
"System.Runtime",
Version {
major,
..Default::default()
},
[0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a],
),
Self::NetCoreImplementation(major) => (
"System.Private.CoreLib",
Version {
major,
..Default::default()
},
[0x7c, 0xec, 0x85, 0xd7, 0xbe, 0xa7, 0x79, 0x8e],
),
Self::NetFramework => (
"mscorlib",
Version {
major: 4,
..Default::default()
},
[0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89],
),
};
AssemblyRef {
name: name.into(),
version,
public_key_or_token: token.to_vec(),
..Default::default()
}
}
pub fn framework_token(self) -> [u8; 8] {
[0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a]
}
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
fn new_mvid(_name: &str) -> uuid::Uuid {
uuid::Uuid::new_v4()
}
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn new_mvid(name: &str) -> uuid::Uuid {
let mut hash: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
for byte in name.bytes() {
hash ^= byte as u128;
hash = hash.wrapping_mul(0x0000_0000_0100_0000_0000_0000_0000_013B);
}
uuid::Builder::from_random_bytes(hash.to_le_bytes()).into_uuid()
}
impl Module {
pub fn new(name: &str, kind: ModuleKind, runtime: TargetRuntime) -> Self {
let extension = if kind == ModuleKind::Dll {
"dll"
} else {
"exe"
};
let global_type = TypeDef {
flags: TypeAttributes::empty(),
name: "<Module>".into(),
..Default::default()
};
let mut module = Self::default();
module.module = Entry::new(ModuleDef {
name: format!("{}.{}", name, extension),
mvid: new_mvid(name),
..Default::default()
});
module.assembly = Some(Entry::new(Assembly {
hash_alg_id: 0x8004,
version: Version {
major: 1,
..Default::default()
},
flags: AssemblyFlags::empty(),
name: name.into(),
..Default::default()
}));
module.types = vec![Entry::new(global_type)];
module.assembly_refs = vec![Entry::new(runtime.corlib())];
module.runtime_version = "v4.0.30319".into();
module.kind = kind;
module.cor20 = ImageCor20Header {
major_rt_version: 2,
minor_rt_version: 5,
flags: Cor20Flags::IL_ONLY,
..Default::default()
};
module
}
pub fn corlib(&self) -> Option<Entry<AssemblyRef>> {
self.assembly_refs
.iter()
.find(|a| a.get().is_corlib())
.cloned()
}
pub fn corlib_type(&mut self, ty: impl TypeName) -> crate::error::Result<TypeDefOrRef> {
let (namespace, name) = ty.type_name();
self.corlib_type_named(&namespace, &name)
}
fn corlib_type_named(
&mut self,
namespace: &str,
name: &str,
) -> crate::error::Result<TypeDefOrRef> {
let corlib = self.corlib().ok_or(crate::error::HaoError::BadImageFormat(
"module has no core library reference",
))?;
let asm_name = corlib.get().name.clone();
self.import_type_from_named(&asm_name, namespace, name)
}
pub fn import_corlib_method(
&mut self,
ty: impl TypeName,
name: &str,
signature: crate::dotnet::signature::MethodSig,
) -> crate::error::Result<crate::dotnet::il::MemberToken> {
let (namespace, type_name) = ty.type_name();
let ty = self.corlib_type_named(&namespace, &type_name)?;
self.import_method_on(&ty, name, signature)
}
pub fn corlib_attribute(
&mut self,
ty: impl TypeName,
) -> crate::error::Result<crate::dotnet::entries::CustomAttributeCtor> {
let (namespace, name) = ty.type_name();
self.corlib_attribute_named(&namespace, &name)
}
fn corlib_attribute_named(
&mut self,
namespace: &str,
name: &str,
) -> crate::error::Result<crate::dotnet::entries::CustomAttributeCtor> {
use crate::dotnet::signature::{MethodSig, TypeSig};
let ty = self.corlib_type_named(namespace, name)?;
let ctor =
self.import_method_on(&ty, ".ctor", MethodSig::new_instance(TypeSig::VOID, vec![]))?;
ctor.try_into().map_err(|_| {
crate::error::HaoError::BadImageFormat("attribute constructor is not a method")
})
}
pub fn import_well_known_method(
&mut self,
method: impl Into<WellKnownMethod>,
) -> crate::error::Result<crate::dotnet::il::MemberToken> {
let (ty, name, signature) = method.into().resolve(self)?;
self.import_method_on(&ty, name, signature)
}
pub fn import_well_known_type(&mut self, ty: WellKnown) -> crate::error::Result<TypeDefOrRef> {
let module = ty.module();
self.add_assembly_ref(module);
self.import_type_from(module.assembly_name(), ty)
}
pub fn add_type(&mut self, ty: TypeDef) -> Entry<TypeDef> {
let ty = Entry::new(ty);
self.types.push(ty.clone());
ty
}
pub fn add_static_class(
&mut self,
namespace: &str,
name: &str,
) -> crate::error::Result<Entry<TypeDef>> {
let object = self.corlib_type(SystemType::Object)?;
Ok(self.add_type(TypeDef::new_static_class(namespace, name, object)))
}
pub fn set_assembly_name(&mut self, name: &str) {
if let Some(assembly) = &self.assembly {
assembly.get_mut().name = name.to_string();
}
self.module.get_mut().name = format!("{}.dll", name);
}
}