Skip to main content

Operand

Enum Operand 

Source
#[non_exhaustive]
pub enum Operand {
Show 15 variants None, I8(i8), I32(i32), I64(i64), R32(f32), R64(f64), BranchTarget(u32), Switch(Vec<u32>), Method(Token), Field(Token), Type(Token), Tok(Token), Sig(Token), String(UserStringToken), Var(u16),
}
Expand description

A decoded instruction operand.

PartialEq follows IEEE semantics for the float variants, so two decodes of the same ldc.r4 NaN are not equal; compare to_bits() when that matters.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

None

No operand, or a macro encoding with no implied value.

§

I8(i8)

A one-byte signed value that is not a widened constant, i.e. the no. prefix check mask.

§

I32(i32)

A 4-byte signed integer, including the widened ldc.i4.s and the constants implied by ldc.i4.0 through ldc.i4.8 and ldc.i4.m1.

§

I64(i64)

An 8-byte signed integer.

§

R32(f32)

A 4-byte float.

§

R64(f64)

An 8-byte float.

§

BranchTarget(u32)

An absolute IL offset, already resolved from the encoded delta.

§

Switch(Vec<u32>)

Absolute IL offsets for a switch, in table order.

§

Method(Token)

A method token from call, callvirt, newobj, ldftn, jmp.

§

Field(Token)

A field token from ldfld, stsfld, ldflda.

§

Type(Token)

A type token from castclass, newarr, box, constrained..

§

Tok(Token)

An unrestricted token from ldtoken.

§

Sig(Token)

A StandAloneSig token from calli.

§

String(UserStringToken)

A #US token from ldstr.

§

Var(u16)

A local or argument index, widened from the short and macro encodings.

Implementations§

Source§

impl Operand

Source

pub const fn token(&self) -> Option<Token>

The token, for the operand kinds that carry one.

Examples found in repository?
examples/dump.rs (line 120)
10fn main() -> Result<(), Box<dyn std::error::Error>> {
11    let mut args = std::env::args().skip(1);
12    let path = args.next().ok_or("usage: dump <image.dll> [MethodName]")?;
13    let wanted = args.next();
14
15    let bytes = std::fs::read(&path)?;
16    let image = PeImage::parse(&bytes)?;
17    let header = image.cli_header()?;
18    println!("{path}");
19    println!(
20        "  {} machine={:#06x} runtime={}.{} il_only={} 32bit_required={} 32bit_preferred={}",
21        if image.is_pe32_plus() { "PE32+" } else { "PE32" },
22        image.machine(),
23        header.major_runtime_version,
24        header.minor_runtime_version,
25        header.flags.il_only(),
26        header.flags.requires_32bit(),
27        header.flags.prefers_32bit(),
28    );
29
30    let metadata = image.metadata()?;
31    println!("  metadata version {}", metadata.version_string());
32    print!("  streams:");
33    for stream in metadata.streams() {
34        print!(" {}({})", stream.name_lossy(), stream.size);
35    }
36    println!();
37
38    let tables = metadata.tables();
39    let mut populated: Vec<(TableId, u32)> = TableId::ALL
40        .iter()
41        .map(|&id| (id, tables.row_count(id)))
42        .filter(|&(_, count)| count > 0)
43        .collect();
44    populated.sort_by_key(|&(id, _)| id.to_u8());
45    println!("  tables:");
46    for (id, count) in &populated {
47        println!("    {:<24} {count:>8}", id.name());
48    }
49
50    for diagnostic in image.diagnostics().iter().chain(metadata.diagnostics()) {
51        println!("  diagnostic: {diagnostic}");
52    }
53
54    let names = Names::new(&metadata);
55    let Some(wanted) = wanted else { return Ok(()) };
56    let wanted_rid: Option<u32> = wanted.strip_prefix('#').and_then(|r| r.parse().ok());
57    for (rid, row) in tables.iter::<MethodDefRow>() {
58        let row = row?;
59        let matched = match wanted_rid {
60            Some(target) => rid == target,
61            None => metadata.strings().str_opt(row.name) == Some(wanted.as_str()),
62        };
63        if !matched {
64            continue;
65        }
66        println!("\n{}", names.method_def_full(Rid::new(rid))?);
67        let Some(body) = MethodBody::from_image(&image, &row)? else {
68            println!("  (no body)");
69            continue;
70        };
71        println!(
72            "  .maxstack {}  code {} bytes  handlers {}",
73            body.max_stack,
74            body.code_size(),
75            body.exception_handlers.len()
76        );
77        if let Some(token) = body.local_var_sig {
78            let sig_row = tables.stand_alone_sig(token.rid())?;
79            let blob = metadata.blobs().get(sig_row.signature)?;
80            let locals = cildec::LocalVarSig::parse(blob)?;
81            for (slot, local) in locals.locals.iter().enumerate() {
82                println!("  .local [{slot}] {}", names.type_(&local.type_));
83            }
84        }
85        for folded in body.folded_instructions() {
86            let folded = folded?;
87            let instruction = &folded.instruction;
88            let mut line = format!("  IL_{:04x}: ", instruction.offset);
89            if folded.prefixes.volatile {
90                line.push_str("volatile. ");
91            }
92            if folded.prefixes.tail {
93                line.push_str("tail. ");
94            }
95            if let Some(token) = folded.prefixes.constrained {
96                line.push_str(&format!("constrained. {} ", names.token(token)));
97            }
98            line.push_str(instruction.opcode.name());
99            match &instruction.operand {
100                _ if instruction.info().operand == cildec::OperandKind::InlineNone => {}
101                cildec::Operand::None => {}
102                cildec::Operand::Var(index) => line.push_str(&format!(" {index}")),
103                cildec::Operand::I8(value) => line.push_str(&format!(" {value}")),
104                cildec::Operand::I32(value) => line.push_str(&format!(" {value}")),
105                cildec::Operand::I64(value) => line.push_str(&format!(" {value}")),
106                cildec::Operand::R32(value) => line.push_str(&format!(" {value}")),
107                cildec::Operand::R64(value) => line.push_str(&format!(" {value}")),
108                cildec::Operand::BranchTarget(target) => {
109                    line.push_str(&format!(" IL_{target:04x}"));
110                }
111                cildec::Operand::Switch(targets) => {
112                    let list: Vec<String> = targets.iter().map(|t| format!("IL_{t:04x}")).collect();
113                    line.push_str(&format!(" ({})", list.join(", ")));
114                }
115                cildec::Operand::String(token) => {
116                    let text = metadata.user_strings().get(*token)?;
117                    line.push_str(&format!(" {:?}", text.to_string_lossy()));
118                }
119                operand => {
120                    if let Some(token) = operand.token() {
121                        line.push_str(&format!(" {}", names.token(token)));
122                    }
123                }
124            }
125            println!("{line}");
126        }
127        for handler in &body.exception_handlers {
128            println!(
129                "  .try IL_{:04x}..IL_{:04x} {:?} handler IL_{:04x}..IL_{:04x}",
130                handler.try_offset,
131                handler.try_end(),
132                handler.kind,
133                handler.handler_offset,
134                handler.handler_end()
135            );
136        }
137        if let Err(e) = body.validate_handlers() {
138            println!("  invalid exception table: {e}");
139        }
140    }
141
142    let type_count = tables.row_count(TableId::TypeDef);
143    if type_count > 0 {
144        let first: TypeDefRow = tables.type_def(1)?;
145        let _ = first;
146    }
147    Ok(())
148}
Source

pub fn branch_targets(&self) -> &[u32]

The absolute branch targets of this operand, if it has any.

Trait Implementations§

Source§

impl Clone for Operand

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 Debug for Operand

Source§

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

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

impl PartialEq for Operand

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 StructuralPartialEq for Operand

Auto Trait Implementations§

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.