Skip to main content

Entry

Struct Entry 

Source
pub struct Entry<T>(/* private fields */);
Expand description

A shared handle to a metadata entry (a type, method, field, …).

Cloning an Entry is cheap and produces another handle to the same value. Entries compare and hash by identity.

Implementations§

Source§

impl<T> Entry<T>

Source

pub fn new(value: T) -> Self

Source

pub fn get(&self) -> ReadGuard<'_, T>

Borrows the value. Panics if it is currently mutably borrowed.

Examples found in repository?
examples/load_module.rs (line 18)
10fn main() {
11    let path = std::env::args()
12        .nth(1)
13        .expect("usage: load_module <assembly>");
14    let module = Module::from_path(&path).unwrap();
15    println!("loaded {}", module.name());
16
17    for ty in module.all_types() {
18        let ty = ty.get();
19        println!("{} {}.{}", ty.kind().keyword(), ty.namespace, ty.name);
20
21        // Decode compile-time constants (enum members and `const` fields) into a
22        // typed value, rather than hand-reading the raw blob.
23        for field in &ty.fields {
24            let field = field.get();
25            if let Some(value) = field.constant.as_ref().and_then(Constant::decode) {
26                println!("    {} = {value}", field.name);
27            }
28        }
29    }
30}
More examples
Hide additional examples
examples/patch_method.rs (line 27)
14fn main() -> hao::error::Result<()> {
15    let mut args = std::env::args().skip(1);
16    let (input, output) = match (args.next(), args.next()) {
17        (Some(i), Some(o)) => (i, o),
18        _ => panic!("usage: patch_method <Sample.dll> <output.dll>"),
19    };
20    let mut module = Module::from_path_no_resolve(&input)?;
21
22    // A common BCL member whose signature is known: one call, no hand-written sig.
23    let write_line =
24        module.import_well_known_method(WellKnownMethod::Console(ConsoleMethod::WriteLineStr))?;
25
26    let add = module.find_method("Sample.Calc", "Add").expect("Calc.Add");
27    println!("before:\n{}", add.get().body.as_ref().unwrap().csharp());
28
29    add.edit_body(|body| {
30        // a + b  ->  a * b
31        let index = body.position(|i| i.opcode == OpCode::Add).unwrap();
32        body.instructions[index] = Instruction::simple(OpCode::Mul);
33
34        // Console.WriteLine("Add called") at the start of the method.
35        body.insert(
36            0,
37            [
38                Instruction::ldstr("Add called"),
39                Instruction::call(write_line),
40            ],
41        );
42    });
43    println!("after:\n{}", add.get().body.as_ref().unwrap().csharp());
44
45    let main = module.entry_point.clone().expect("entry point");
46    main.edit_body(|body| {
47        body.replace_operand(
48            &"Hello from hao".into(),
49            "Hello from a patched assembly".into(),
50        )
51    });
52
53    if let Some(dir) = std::path::Path::new(&output).parent() {
54        std::fs::create_dir_all(dir).ok();
55    }
56    module.write_to_path(&output)?;
57    println!("wrote {}", output);
58    Ok(())
59}
Source

pub fn get_mut(&self) -> WriteGuard<'_, T>

Mutably borrows the value. Panics if it is currently borrowed.

Source

pub fn try_get(&self) -> Option<ReadGuard<'_, T>>

Source

pub fn try_get_mut(&self) -> Option<WriteGuard<'_, T>>

Source

pub fn replace(&self, value: T) -> T

Replaces the value, returning the old one.

Source

pub fn rid(&self) -> u32

The row this entry was loaded from, or 0 if it was created after loading.

Source

pub fn ptr_eq(&self, other: &Self) -> bool

Source

pub fn downgrade(&self) -> WeakEntry<T>

Source§

impl Entry<TypeDef>

Builder methods that need the shared handle (to set each child’s declaring_type back-reference to its parent), so they live on Entry<TypeDef> rather than TypeDef.

Source

pub fn add_field(&self, field: Field) -> Entry<Field>

Source

pub fn add_method(&self, method: Method) -> Entry<Method>

Source

pub fn add_nested_type(&self, ty: TypeDef) -> Entry<TypeDef>

Source

pub fn with_nested(&self) -> Vec<Entry<TypeDef>>

This type and all nested types, depth first.

Source§

impl Entry<Method>

Source

pub fn edit_body<R>(&self, f: impl FnOnce(&mut MethodBody) -> R) -> Option<R>

Runs f on the method body. Returns None if the method has no body.

Examples found in repository?
examples/patch_method.rs (lines 29-42)
14fn main() -> hao::error::Result<()> {
15    let mut args = std::env::args().skip(1);
16    let (input, output) = match (args.next(), args.next()) {
17        (Some(i), Some(o)) => (i, o),
18        _ => panic!("usage: patch_method <Sample.dll> <output.dll>"),
19    };
20    let mut module = Module::from_path_no_resolve(&input)?;
21
22    // A common BCL member whose signature is known: one call, no hand-written sig.
23    let write_line =
24        module.import_well_known_method(WellKnownMethod::Console(ConsoleMethod::WriteLineStr))?;
25
26    let add = module.find_method("Sample.Calc", "Add").expect("Calc.Add");
27    println!("before:\n{}", add.get().body.as_ref().unwrap().csharp());
28
29    add.edit_body(|body| {
30        // a + b  ->  a * b
31        let index = body.position(|i| i.opcode == OpCode::Add).unwrap();
32        body.instructions[index] = Instruction::simple(OpCode::Mul);
33
34        // Console.WriteLine("Add called") at the start of the method.
35        body.insert(
36            0,
37            [
38                Instruction::ldstr("Add called"),
39                Instruction::call(write_line),
40            ],
41        );
42    });
43    println!("after:\n{}", add.get().body.as_ref().unwrap().csharp());
44
45    let main = module.entry_point.clone().expect("entry point");
46    main.edit_body(|body| {
47        body.replace_operand(
48            &"Hello from hao".into(),
49            "Hello from a patched assembly".into(),
50        )
51    });
52
53    if let Some(dir) = std::path::Path::new(&output).parent() {
54        std::fs::create_dir_all(dir).ok();
55    }
56    module.write_to_path(&output)?;
57    println!("wrote {}", output);
58    Ok(())
59}

Trait Implementations§

Source§

impl<T> Clone for Entry<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for Entry<T>
where T: EntryName,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for Entry<T>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T> Eq for Entry<T>

Source§

impl<'ʄ, T> Facet<'ʄ> for Entry<T>
where T: Facet<'ʄ>,

Source§

const SHAPE: &'static Shape

The shape of this type, including: whether it’s a Struct, an Enum, something else? Read more
Source§

impl From<Entry<Field>> for MemberToken

Source§

fn from(value: Entry<Field>) -> Self

Converts to this type from the input type.
Source§

impl From<Entry<MemberRef>> for MemberToken

Source§

fn from(value: Entry<MemberRef>) -> Self

Converts to this type from the input type.
Source§

impl From<Entry<Method>> for MemberToken

Source§

fn from(value: Entry<Method>) -> Self

Converts to this type from the input type.
Source§

impl From<Entry<MethodSpec>> for MemberToken

Source§

fn from(value: Entry<MethodSpec>) -> Self

Converts to this type from the input type.
Source§

impl From<Entry<TypeDef>> for MemberToken

Source§

fn from(value: Entry<TypeDef>) -> Self

Converts to this type from the input type.
Source§

impl From<Entry<TypeRef>> for MemberToken

Source§

fn from(value: Entry<TypeRef>) -> Self

Converts to this type from the input type.
Source§

impl From<Entry<TypeSpec>> for MemberToken

Source§

fn from(value: Entry<TypeSpec>) -> Self

Converts to this type from the input type.
Source§

impl<T> Hash for Entry<T>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T> PartialEq for Entry<T>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<T: WriteCSharp> WriteCSharp for Entry<T>

Source§

fn write_csharp<W: Write>(&self, w: &mut CSharpWriter<W>) -> Result

Source§

fn to_csharp(&self) -> String

Source§

fn csharp(&self) -> CSharp<'_, Self>

A Display adapter.

Auto Trait Implementations§

§

impl<T> Forget for Entry<T>

§

impl<T> Freeze for Entry<T>
where *const ArcInner<EntryInner<T>> is !null: Freeze, PhantomData<ArcInner<EntryInner<T>>>: Freeze,

§

impl<T> Move for Entry<T>

§

impl<T> RefUnwindSafe for Entry<T>

§

impl<T> Send for Entry<T>
where Arc<EntryInner<T>>: Send,

§

impl<T> Sync for Entry<T>
where Arc<EntryInner<T>>: Sync,

§

impl<T> Unpin for Entry<T>
where Arc<EntryInner<T>>: Unpin,

§

impl<T> UnsafeUnpin for Entry<T>
where *const ArcInner<EntryInner<T>> is !null: UnsafeUnpin, PhantomData<ArcInner<EntryInner<T>>>: UnsafeUnpin,

§

impl<T> UnwindSafe for Entry<T>
where Arc<EntryInner<T>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.