Skip to main content

Rid

Struct Rid 

Source
pub struct Rid<T> { /* private fields */ }
Expand description

A 1-based row identifier within a statically known table.

Zero means “no row”, matching the metadata encoding.

Implementations§

Source§

impl<T> Rid<T>

Source

pub const fn new(value: u32) -> Self

Wraps a raw 1-based row id.

Examples found in repository?
examples/dump.rs (line 66)
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 const fn get(self) -> u32

The raw 1-based row id.

Source

pub const fn is_null(self) -> bool

True when this refers to no row.

Source

pub const fn index(self) -> Option<usize>

The zero-based index into the table, or None for a null RID.

Source§

impl<T: Table> Rid<T>

Source

pub const fn table(self) -> TableId

The table id this RID belongs to.

Source

pub const fn token(self) -> Token

The equivalent Token.

Trait Implementations§

Source§

impl<T> Clone for Rid<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> Copy for Rid<T>

Source§

impl<T: Table> Debug for Rid<T>

Source§

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

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

impl<T> Default for Rid<T>

Source§

fn default() -> Self

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

impl<T> Eq for Rid<T>

Source§

impl<T: Table> From<Rid<T>> for Token

Source§

fn from(rid: Rid<T>) -> Token

Converts to this type from the input type.
Source§

impl<T> Hash for Rid<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> Ord for Rid<T>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl<T> PartialEq for Rid<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> PartialOrd for Rid<T>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

§

impl<T> Forget for Rid<T>

§

impl<T> Freeze for Rid<T>
where PhantomData<fn() -> T>: Freeze,

§

impl<T> Move for Rid<T>

§

impl<T> RefUnwindSafe for Rid<T>
where PhantomData<fn() -> T>: RefUnwindSafe,

§

impl<T> Send for Rid<T>
where PhantomData<fn() -> T>: Send,

§

impl<T> Sync for Rid<T>
where PhantomData<fn() -> T>: Sync,

§

impl<T> Unpin for Rid<T>
where PhantomData<fn() -> T>: Unpin,

§

impl<T> UnsafeUnpin for Rid<T>
where PhantomData<fn() -> T>: UnsafeUnpin,

§

impl<T> UnwindSafe for Rid<T>
where PhantomData<fn() -> 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.