hao 0.0.12

Read, edit, create and write .net assemblies
Documentation
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! The link phase: wires every metadata table's rows into the entry graph.
//! An `impl Loader` block kept out of `mod.rs` because it is large; it reaches
//! the parent module's private helpers (`get`, `self.rows`, ...) as a descendant.

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)
    }

    /// NestedClass: `declaring_type`/`nested_types` links, and the top-level set.
    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(())
    }

    /// Back-link every field and method to its declaring type.
    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();
            }
        }
    }

    /// InterfaceImpl. Returns `(class, interface index)` for the attribute pass.
    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::InvalidEntryRefrence("InterfaceImpl", 0))?;
            let index = class.get().interfaces.len();
            class
                .get_mut()
                .interfaces
                .push(InterfaceImpl::new(interface));
            interface_impls.push((class, index));
        }
        Ok(interface_impls)
    }

    /// Constant: Field / Param / Property default values.
    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(())
    }

    /// FieldMarshal: Field / Param marshalling descriptors.
    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(())
    }

    /// DeclSecurity. Returns the owners for the attribute pass.
    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)
    }

    /// ClassLayout: packing/size on a TypeDef.
    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(())
    }

    /// FieldLayout: explicit field offsets.
    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(())
    }

    /// MethodSemantics: Property / Event accessor methods.
    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(())
    }

    /// MethodImpl: explicit method-override bodies on a TypeDef.
    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(())
    }

    /// ImplMap: P/Invoke info on a Field / Method.
    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(())
    }

    /// FieldRVA: static field initializers read from the image.
    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",
                    ))
                }
                // Can't size this initializer (an external value type in the
                // last FieldRVA entry). Leave it unset rather than failing to
                // open the module.
                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(())
    }

    /// GenericParam: link each parameter to its owning TypeDef / Method.
    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(())
    }

    /// GenericParamConstraint. Returns `(owner, index)` for the attribute pass.
    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::InvalidEntryRefrence("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)
    }

    /// CustomAttribute: attach to every owner kind. The three side tables come
    /// from the interface/decl-security/constraint passes (their rows own the
    /// attribute lists the coded token points into).
    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;
            // The owner-table name (used only in the not-found error) is the
            // token's own variant name, via strum.
            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::InvalidEntryRefrence(
                        "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(())
    }
}