dotscope 0.7.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Utility macros for synchronization and threading.
//!
//! This module provides convenience macros for working with Rust's synchronization primitives
//! like [`std::sync::Mutex`], [`std::sync::RwLock`], and [`std::sync::Arc`]. These macros
//! simplify common patterns when working with shared data in concurrent contexts and are
//! primarily used internally by the metadata loading system.
//!
//! # Architecture
//!
//! The macros are organized into three categories:
//! - **Basic Locking**: Direct lock acquisition with panic handling (`lock!`, `read_lock!`, `write_lock!`)
//! - **Functional Style**: Execute closures with automatic lock management (`with_read!`, `with_write!`)
//! - **Collection Operations**: Specialized operations for working with collections of locked data (`map_get_read!`, `for_each_read!`)
//!
//! All macros follow a consistent pattern of automatic panic handling for lock poisoning,
//! treating poisoned locks as unrecoverable errors in the context of metadata analysis.
//!
//! # Key Components
//!
//! - `lock!` - Acquire a mutex lock with panic on failure
//! - `read_lock!` - Acquire a read lock on an `RwLock` with panic on failure
//! - `write_lock!` - Acquire a write lock on an `RwLock` with panic on failure
//! - `with_read!` - Execute a closure with a read lock
//! - `with_write!` - Execute a closure with a write lock
//! - `map_get_read!` - Get an item from a map and acquire a read lock
//! - `for_each_read!` - Iterate over a collection with read locks
//!
//! # Usage Examples
//!
//! ## Basic Locking
//!
//! ```rust,ignore
//! use std::sync::{Mutex, RwLock};
//!
//! let mutex_data = Mutex::new(42);
//! let mut data = lock!(mutex_data);
//! *data = 100;
//!
//! let rwlock_data = RwLock::new(String::from("hello"));
//! let reader = read_lock!(rwlock_data);
//! println!("Value: {}", *reader);
//! ```
//!
//! ## Functional Style
//!
//! ```rust,ignore
//! use std::sync::{Arc, RwLock};
//!
//! let shared_data = Arc::new(RwLock::new(vec![1, 2, 3]));
//!
//! // Execute closure with read access
//! let length = with_read!(shared_data, |vec| vec.len());
//!
//! // Execute closure with write access
//! with_write!(shared_data, |vec| vec.push(4));
//! ```
//!
//! # Error Handling
//!
//! All macros in this module use panic-based error handling for lock poisoning:
//! - **Lock Poisoning**: When a thread panics while holding a lock, all macros will panic with descriptive messages
//! - **Timeout**: No timeout handling is provided; locks are acquired with indefinite blocking
//!
//! This design is appropriate for the metadata loading context where lock poisoning indicates
//! an unrecoverable error in the parsing process.
//!
//! # Thread Safety
//!
//! The macros themselves do not impose additional thread safety requirements beyond
//! the underlying synchronization primitives. All operations preserve the thread safety
//! guarantees of the wrapped [`std::sync::Mutex`] and [`std::sync::RwLock`] types.
//! All macros are thread-safe as they operate on already thread-safe synchronization
//! primitives and do not introduce additional shared state.
//!
//! # Integration
//!
//! These macros integrate primarily with:
//! - [`crate::metadata::loader`] - Metadata loading system for concurrent parsing
//! - [`crate::metadata::tables`] - Shared access to metadata table structures
//! - Internal caching systems that require synchronized access to parsed data

#![allow(unused_macros)]

/// Unwrap a `Result` inside a BCL hook, converting errors to `PreHookResult::Error`.
///
/// BCL hooks return `PreHookResult`, not `Result`. This macro bridges the gap
/// by converting any `Err(e)` into `PreHookResult::Error(format!("{e}"))` with
/// an early return, while unwrapping `Ok(val)` for normal flow.
///
/// # Usage
///
/// ```rust,ignore
/// let value = try_hook!(heap.get_string(href));
/// // `value` is the unwrapped Ok variant
/// ```
macro_rules! try_hook {
    ($expr:expr) => {
        match $expr {
            Ok(val) => val,
            Err(e) => return PreHookResult::Error(format!("{e}")),
        }
    };
}

/// Acquire a mutex lock with automatic panic handling.
///
/// This macro simplifies acquiring a lock on a [`std::sync::Mutex`] by automatically
/// handling lock poisoning with a panic. It's designed for use cases where lock
/// poisoning indicates an unrecoverable error.
///
/// # Panics
///
/// Panics if the mutex is poisoned (another thread panicked while holding the lock).
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::sync::Mutex;
///
/// let shared_data = Mutex::new(42);
/// let mut data = lock!(shared_data);
/// *data = 100;
/// // Lock is automatically released when `data` goes out of scope
/// ```
macro_rules! lock {
    ($lock:expr) => {
        $lock.lock().expect("Failed to acquire lock")
    };
}

/// Acquire a read lock on an [`std::sync::RwLock`] with automatic panic handling.
///
/// This macro simplifies acquiring a read lock by automatically handling lock
/// poisoning with a panic. Multiple readers can hold the lock simultaneously.
///
/// # Panics
///
/// Panics if the [`std::sync::RwLock`] is poisoned.
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::sync::RwLock;
///
/// let shared_data = RwLock::new("hello world".to_string());
/// let data = read_lock!(shared_data);
/// println!("Data: {}", *data);
/// // Read lock is automatically released when `data` goes out of scope
/// ```
macro_rules! read_lock {
    ($arc_rwlock:expr) => {
        $arc_rwlock.read().expect("Failed to acquire read lock")
    };
}

/// Acquire a write lock on an [`std::sync::RwLock`] with automatic panic handling.
///
/// This macro simplifies acquiring a write lock by automatically handling lock
/// poisoning with a panic. Only one writer can hold the lock at a time, and
/// no readers can access the data while a write lock is held.
///
/// # Panics
///
/// Panics if the [`std::sync::RwLock`] is poisoned.
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::sync::RwLock;
///
/// let shared_data = RwLock::new(vec![1, 2, 3]);
/// let mut data = write_lock!(shared_data);
/// data.push(4);
/// // Write lock is automatically released when `data` goes out of scope
/// ```
macro_rules! write_lock {
    ($arc_rwlock:expr) => {
        $arc_rwlock.write().expect("Failed to acquire write lock")
    };
}

/// Execute a closure with read access to shared data.
///
/// This macro acquires a read lock, executes the provided closure with access
/// to the data, and automatically releases the lock when the closure completes.
/// The closure's return value is passed through.
///
/// # Arguments
/// * `$arc_rwlock` - An [`std::sync::RwLock`] to acquire a read lock on
/// * `$closure` - A closure that takes a reference to the locked data
///
/// # Panics
///
/// Panics if the [`std::sync::RwLock`] is poisoned.
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::sync::{Arc, RwLock};
///
/// let shared_data = Arc::new(RwLock::new("Hello".to_string()));
/// let length = with_read!(shared_data, |data| data.len());
/// assert_eq!(length, 5);
/// ```
macro_rules! with_read {
    ($arc_rwlock:expr, $closure:expr) => {{
        let guard = $arc_rwlock.read().expect("Failed to acquire read lock");
        $closure(&*guard)
    }};
}

/// Execute a closure with write access to shared data.
///
/// This macro acquires a write lock, executes the provided closure with mutable
/// access to the data, and automatically releases the lock when the closure completes.
/// The closure's return value is passed through.
///
/// # Arguments
/// * `$arc_rwlock` - An [`std::sync::RwLock`] to acquire a write lock on
/// * `$closure` - A closure that takes a mutable reference to the locked data
///
/// # Panics
///
/// Panics if the [`std::sync::RwLock`] is poisoned.
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::sync::{Arc, RwLock};
///
/// let shared_data = Arc::new(RwLock::new(vec![1, 2, 3]));
/// with_write!(shared_data, |data| data.push(4));
///
/// let length = with_read!(shared_data, |data| data.len());
/// assert_eq!(length, 4);
/// ```
macro_rules! with_write {
    ($arc_rwlock:expr, $closure:expr) => {{
        let mut guard = $arc_rwlock.write().expect("Failed to acquire write lock");
        $closure(&mut *guard)
    }};
}

/// Get an item from a map and acquire a read lock on it.
///
/// This macro combines map lookup with read lock acquisition, returning an
/// [`std::option::Option`] containing the locked data if the key exists.
///
/// # Arguments
/// * `$map` - A map-like collection containing [`std::sync::Arc`]<[`std::sync::RwLock`]<`T`>> values
/// * `$key` - The key to look up in the map
///
/// # Returns
/// An [`std::option::Option`] containing a read guard if the key exists, or [`std::option::Option::None`] if not found.
///
/// # Panics
///
/// Panics if the [`std::sync::RwLock`] is poisoned.
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::collections::HashMap;
/// use std::sync::{Arc, RwLock};
///
/// let mut map = HashMap::new();
/// map.insert(1, Arc::new(RwLock::new("value".to_string())));
///
/// if let Some(guard) = map_get_read!(map, &1) {
///     println!("Found: {}", *guard);
/// }
/// ```
macro_rules! map_get_read {
    ($map:expr, $key:expr) => {{
        $map.get($key).map(|arc_rwlock| read_lock!(arc_rwlock))
    }};
}

/// Iterate over a collection of locked items with read access.
///
/// This macro simplifies iterating over a collection where each item is wrapped
/// in an [`std::sync::Arc`]<[`std::sync::RwLock`]<`T`>>. It automatically acquires
/// a read lock for each item during iteration.
///
/// # Arguments
/// * `$collection` - A collection containing [`std::sync::Arc`]<[`std::sync::RwLock`]<`T`>> items
/// * `$var` - The variable name to bind the locked data to in each iteration
/// * `$body` - The code block to execute for each item
///
/// # Panics
///
/// Panics if any [`std::sync::RwLock`] in the collection is poisoned.
///
/// # Usage Examples
///
/// ```rust,ignore
/// use std::sync::{Arc, RwLock};
///
/// let items = vec![
///     Arc::new(RwLock::new("first".to_string())),
///     Arc::new(RwLock::new("second".to_string())),
/// ];
///
/// for_each_read!(items, item, {
///     println!("Item: {}", *item);
/// });
/// ```
macro_rules! for_each_read {
    ($collection:expr, $var:ident, $body:block) => {
        for item in $collection.iter() {
            let $var = read_lock!(item);
            $body
        }
    };
}

/// Generates a newtype wrapper for metadata flag/attribute types.
///
/// This macro creates a strongly-typed flags struct with a comprehensive set of trait
/// implementations for bitwise operations, formatting, conversion, and comparison.
/// It replaces the previous patterns of `pub mod Name { pub const X: u32 }` const
/// modules and `bitflags!` macro invocations with a single unified pattern that
/// provides type safety and consistent API across all metadata flag types.
///
/// # Generated API
///
/// For a declaration `metadata_flags! { pub struct Foo(u32); }`, the macro generates:
///
/// ## Derives and Traits
/// - `Clone`, `Copy`, `PartialEq`, `Eq`, `Hash` (derived)
/// - `Debug` — formats as `Foo(0xVALUE)`
/// - `UpperHex`, `LowerHex` — delegates to inner type
/// - `BitOr<Self>`, `BitAnd<Self>`, `BitOrAssign`, `BitAndAssign`, `Not`
/// - `From<inner>` — construct from raw value
///
/// ## Methods
/// - `pub const fn new(v: inner) -> Self` — construct from raw value (const)
/// - `pub const fn bits(self) -> inner` — extract raw value
/// - `pub const fn contains(self, other: Self) -> bool` — test if all bits in `other` are set
/// - `pub const fn is_empty(self) -> bool` — test if no bits are set
///
/// ## Constants
/// - `pub const ZERO: Self = Self(0)` — the zero/empty value
///
/// # Usage
///
/// ```rust,ignore
/// metadata_flags! {
///     /// ECMA-335 §II.23.1.15 TypeDef attribute flags.
///     pub struct TypeAttributes(u32);
/// }
///
/// impl TypeAttributes {
///     pub const PUBLIC: Self = Self(0x0000_0001);
///     pub const SEALED: Self = Self(0x0000_0100);
///     // ...
/// }
/// ```
///
/// # Design Rationale
///
/// Unlike `bitflags!`, this macro intentionally keeps the `impl` block separate so that
/// each flag constant can retain its full doc comment describing ECMA-335 semantics.
/// The macro only generates the boilerplate traits; domain-specific constants, keyword
/// methods, predicates, and `Display` impls are written manually in the `impl` block.
macro_rules! metadata_flags {
    (
        $(#[$outer:meta])*
        $vis:vis struct $Name:ident($inner:ty);
    ) => {
        $(#[$outer])*
        #[derive(Clone, Copy, PartialEq, Eq, Hash)]
        $vis struct $Name($inner);

        impl $Name {
            /// The zero (empty) value with no flags set.
            pub const ZERO: Self = Self(0);

            /// Constructs a new flags value from a raw integer.
            #[inline]
            #[must_use]
            pub const fn new(v: $inner) -> Self {
                Self(v)
            }

            /// Returns the raw integer value of the flags.
            #[inline]
            #[must_use]
            pub const fn bits(self) -> $inner {
                self.0
            }

            /// Returns `true` if all bits in `other` are set in `self`.
            #[inline]
            #[must_use]
            pub const fn contains(self, other: Self) -> bool {
                (self.0 & other.0) == other.0
            }

            /// Returns `true` if no flags are set.
            #[inline]
            #[must_use]
            pub const fn is_empty(self) -> bool {
                self.0 == 0
            }
        }

        impl std::fmt::Debug for $Name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}(0x{:X})", stringify!($Name), self.0)
            }
        }

        impl std::fmt::UpperHex for $Name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                std::fmt::UpperHex::fmt(&self.0, f)
            }
        }

        impl std::fmt::LowerHex for $Name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                std::fmt::LowerHex::fmt(&self.0, f)
            }
        }

        impl std::ops::BitOr for $Name {
            type Output = Self;
            #[inline]
            fn bitor(self, rhs: Self) -> Self {
                Self(self.0 | rhs.0)
            }
        }

        impl std::ops::BitAnd for $Name {
            type Output = Self;
            #[inline]
            fn bitand(self, rhs: Self) -> Self {
                Self(self.0 & rhs.0)
            }
        }

        impl std::ops::BitOrAssign for $Name {
            #[inline]
            fn bitor_assign(&mut self, rhs: Self) {
                self.0 |= rhs.0;
            }
        }

        impl std::ops::BitAndAssign for $Name {
            #[inline]
            fn bitand_assign(&mut self, rhs: Self) {
                self.0 &= rhs.0;
            }
        }

        impl std::ops::Not for $Name {
            type Output = Self;
            #[inline]
            fn not(self) -> Self {
                Self(!self.0)
            }
        }

        impl From<$inner> for $Name {
            #[inline]
            fn from(v: $inner) -> Self {
                Self(v)
            }
        }

        impl std::ops::Deref for $Name {
            type Target = $inner;
            #[inline]
            fn deref(&self) -> &$inner {
                &self.0
            }
        }

        impl PartialEq<$inner> for $Name {
            #[inline]
            fn eq(&self, other: &$inner) -> bool {
                self.0 == *other
            }
        }

        impl PartialOrd<$inner> for $Name {
            #[inline]
            fn partial_cmp(&self, other: &$inner) -> Option<std::cmp::Ordering> {
                self.0.partial_cmp(other)
            }
        }
    };
}