1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use pewter::pe::sections::cor20::{Cor20Flags, ImageCor20Header};
use super::Module;
use crate::dotnet::{
entries::{
well_known::{SystemType, WellKnown},
*,
},
md::streams::tables_stream::{AssemblyFlags, TypeAttributes},
};
/// What kind of image [`Module::new`] creates, which sets its file extension
/// and PE subsystem.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "reflect", derive(facet::Facet), repr(C))]
pub enum ModuleKind {
/// A class library (`.dll`).
#[default]
Dll,
/// A console application (`.exe`); set [`Module::entry_point`] to its `Main`.
Console,
/// A GUI application (`.exe`) that opens no console window.
Windows,
}
/// The core library new modules reference.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetRuntime {
/// .NET (Core) 5+, referencing `System.Runtime` with the given major version.
NetCore(u16),
/// .NET Framework 4.x and Mono (including Unity), referencing `mscorlib`.
NetFramework,
/// .NET (Core) referencing the implementation assembly `System.Private.CoreLib`,
/// where every core type lives. Only suitable for code that runs on the
/// runtime it is generated for, as the reference ties it to that version.
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()
}
}
/// Microsoft's public key token (`b03f5f7f11d50a3a`), which the .NET
/// (Core) reference assemblies other than the core library use. On .NET
/// Framework it depends on the assembly (`System` and `System.Core` use the
/// ECMA key, `b77a5c561934e089`), so reference those through
/// [`WellKnownModule`](crate::dotnet::entries::WellKnownModule), which
/// carries each assembly's own token.
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()
}
/// Browser wasm has no randomness, so derive the id from the name (FNV-1a).
/// Set `module.module.get_mut().mvid` if it has to be unique.
#[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 {
/// A new, empty assembly. `name` is the assembly name without an extension.
///
/// ```
/// use hao::{Module, dotnet::module::{ModuleKind, TargetRuntime}};
///
/// let module = Module::new("Generated", ModuleKind::Dll, TargetRuntime::NetCore(9));
/// assert_eq!(module.name(), "Generated.dll");
/// ```
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
}
/// The reference to the core library (`System.Runtime`, `mscorlib`, ...).
pub fn corlib(&self) -> Option<Entry<AssemblyRef>> {
self.assembly_refs
.iter()
.find(|a| a.get().is_corlib())
.cloned()
}
/// A type from the core library, e.g. `SystemType::Object` or `"System.Object"`.
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)
}
/// Non-generic core of [`Module::corlib_type`], shared by the corlib helpers.
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)
}
/// A method of a core library type, e.g. `SystemType::Math` / `"System.Math"` `::Max`.
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)
}
/// The parameterless constructor of a core library attribute, for
/// [`Method::with_attribute`](crate::dotnet::entries::Method::with_attribute), e.g.
/// `SystemRuntimeInteropServicesType::UnmanagedCallersOnlyAttribute`.
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)
}
/// Non-generic core of [`Module::corlib_attribute`].
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")
})
}
/// Imports a [`WellKnown`] type, resolving its assembly from
/// [`WellKnown::module`] and adding the reference automatically — so no
/// assembly name is needed, e.g.
/// `import_well_known_type(WellKnown::System(SystemType::Uri))`.
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)
}
/// Adds a new top level type.
pub fn add_type(&mut self, ty: TypeDef) -> Entry<TypeDef> {
let ty = Entry::new(ty);
self.types.push(ty.clone());
ty
}
/// Adds a `public static class`.
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)))
}
/// Renames the assembly, e.g. to load an edited copy next to the original.
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);
}
}