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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Centralized registry of synthetic token constants for the CIL emulator.
//!
//! The emulator needs tokens for types, fields, and methods that don't exist
//! in the loaded assembly's metadata (exception types, heap object types, BCL
//! helper objects, etc.). All such tokens are defined here so that:
//!
//! - Every synthetic value has a single named constant (no inline hex literals).
//! - Ranges are documented and collision-free.
//! - Detection helpers (`is_synthetic`, `is_exception_type`, …) live next to
//!   the constants they check.
//!
//! # Token Ranges
//!
//! | Range              | Table | Purpose                              |
//! |--------------------|-------|--------------------------------------|
//! | `0x7F00_xxxx`      | 0x7F  | Synthetic heap-object type tokens    |
//! | `0x7F01_xxxx`      | 0x7F  | Synthetic exception type tokens      |
//! | `0x7F02_xxxx`      | 0x7F  | Dynamic synthetic method tokens      |
//! | `0x7F03_xxxx`      | 0x7F  | Native function pointer method tokens|
//! | `0x7F04_xxxx`      | 0x7F  | Synthetic field tokens on syn. types |
//! | `0x7FFF_xxxx`      | 0x7F  | BCL helper object type tokens        |
//! | `0xEF00_xxxx`      | 0xEF  | Sentinel field tokens                |
//! | `0xF100_xxxx`      | 0xF1  | Generic instantiation tokens         |
//! | `0xFFFF_xxxx`      | 0xFF  | I/O sentinel field tokens            |
//!
//! Tables 0x7F, 0xEF, 0xF1, and 0xFF do not exist in ECMA-335, so these tokens
//! can never collide with real metadata tokens from a loaded assembly.
//!
//! # Token Ranges
//!
//! - `0x7F00_00xx`: Emulation heap object type tokens
//! - `0x7F00_10xx`: Placeholder type tokens (heap streaming)
//! - `0x7F01_00xx`: Synthetic exception hierarchy tokens
//! - `0x7F02_xxxx`: Synthetic method tokens (DynamicMethod)
//! - `0x7F03_xxxx`: Native function pointer method tokens
//! - `0xF100_xxxx`: Generic instantiation tokens

use crate::metadata::token::Token;

/// Reflection types — used for `System.Reflection` heap objects.
pub mod reflection {
    use crate::metadata::token::Token;

    /// `System.Type` reflection object.
    pub const TYPE: Token = Token::new(0x7F00_0001);
    /// `System.Reflection.MethodInfo` / `MethodBase` reflection object.
    pub const METHOD: Token = Token::new(0x7F00_0002);
    /// `System.Reflection.Module` reflection object.
    pub const MODULE: Token = Token::new(0x7F00_0003);
    /// `System.Reflection.FieldInfo` reflection object.
    pub const FIELD: Token = Token::new(0x7F00_0004);
    /// `System.Reflection.PropertyInfo` reflection object.
    pub const PROPERTY: Token = Token::new(0x7F00_0005);
    /// `System.Reflection.ParameterInfo` reflection object.
    pub const PARAMETER: Token = Token::new(0x7F00_0013);
    /// `System.Reflection.MethodBody` reflection object.
    pub const METHOD_BODY: Token = Token::new(0x7F00_0015);
    /// `System.Reflection.CustomAttributeData` object.
    pub const CUSTOM_ATTRIBUTE_DATA: Token = Token::new(0x7F00_0020);
    /// `System.Reflection.AssemblyName` object.
    pub const ASSEMBLY_NAME: Token = Token::new(0x7F00_0014);
}

/// Cryptography types — used for `System.Security.Cryptography` heap objects.
pub mod crypto {
    use crate::metadata::token::Token;

    /// `Rfc2898DeriveBytes` / key derivation object.
    pub const KEY_DERIVATION: Token = Token::new(0x7F00_0007);
    /// `HashAlgorithm` / `HMAC` object.
    pub const CRYPTO_ALGORITHM: Token = Token::new(0x7F00_1004);
    /// `Aes` / `DES` / `TripleDES` symmetric algorithm object.
    pub const SYMMETRIC_ALGORITHM: Token = Token::new(0x7F00_1005);
    /// `ICryptoTransform` object.
    pub const CRYPTO_TRANSFORM: Token = Token::new(0x7F00_1006);
}

/// I/O and stream types.
pub mod io {
    use crate::metadata::token::Token;

    /// `System.IO.Stream` / `MemoryStream` / `FileStream` object.
    pub const STREAM: Token = Token::new(0x7F00_0008);
    /// `System.Security.Cryptography.CryptoStream` object.
    pub const CRYPTO_STREAM: Token = Token::new(0x7F00_0009);
    /// `System.IO.Compression.DeflateStream` / `GZipStream` object.
    pub const COMPRESSED_STREAM: Token = Token::new(0x7F00_0017);
}

/// Collection types — `System.Collections.Generic` heap objects.
pub mod collections {
    use crate::metadata::token::Token;

    /// `Dictionary<TKey, TValue>` object.
    pub const DICTIONARY: Token = Token::new(0x7F00_000D);
    /// `List<T>` object.
    pub const LIST: Token = Token::new(0x7F00_000E);
    /// `Stack<T>` object.
    pub const STACK: Token = Token::new(0x7F00_0010);
    /// `Queue<T>` object.
    pub const QUEUE: Token = Token::new(0x7F00_0011);
    /// `HashSet<T>` object.
    pub const HASH_SET: Token = Token::new(0x7F00_0012);
    /// `IEnumerator` empty enumerator stub object.
    pub const ENUMERATOR: Token = Token::new(0x7F00_0030);
}

/// Dynamic code generation types.
pub mod codegen {
    use crate::metadata::token::Token;

    /// `System.Reflection.Emit.DynamicMethod` object.
    pub const DYNAMIC_METHOD: Token = Token::new(0x7F00_000A);
    /// `System.Reflection.Emit.ILGenerator` object.
    pub const IL_GENERATOR: Token = Token::new(0x7F00_000B);
}

/// System and text utility types.
pub mod system {
    use crate::metadata::token::Token;

    /// `System.String` heap object (primitive wrapper).
    pub const STRING: Token = Token::new(0x7F00_1001);
    /// `System.Array` / multi-dimensional array (primitive wrapper).
    pub const ARRAY: Token = Token::new(0x7F00_1002);
    /// `System.Text.Encoding` object.
    pub const ENCODING: Token = Token::new(0x7F00_1003);
    /// `System.Text.StringBuilder` object.
    pub const STRING_BUILDER: Token = Token::new(0x7F00_000F);
    /// `System.Threading.Thread` object.
    pub const THREAD: Token = Token::new(0x7F00_0016);
    /// `System.Threading.Tasks.Task` (stub for `Task.CompletedTask`).
    pub const TASK: Token = Token::new(0x7F00_0021);
    /// `System.Span<T>` wrapper object.
    pub const SPAN: Token = Token::new(0x7F00_0022);
    /// `System.Memory<T>` wrapper object.
    pub const MEMORY: Token = Token::new(0x7F00_0023);
    /// `System.TypedReference` (created by `mkrefany`).
    pub const TYPED_REFERENCE: Token = Token::new(0x7F00_0024);
    /// `System.Reflection.Emit.OpCode` value type.
    pub const OPCODE: Token = Token::new(0x7F00_0025);
    /// `System.Diagnostics.Process` object.
    pub const PROCESS: Token = Token::new(0x7F00_0026);
    /// `System.Diagnostics.ProcessModule` object.
    pub const PROCESS_MODULE: Token = Token::new(0x7F00_0027);
}

/// Well-known singleton objects used by `FakeObjects`.
pub mod singletons {
    use crate::metadata::token::Token;

    /// Fake `System.Reflection.Assembly` singleton.
    pub const ASSEMBLY: Token = Token::new(0x7F00_00F0);
    /// Fake `System.AppDomain` singleton.
    pub const APP_DOMAIN: Token = Token::new(0x7F00_00F1);
}

/// Native function pointer method tokens (`0x7F03_xxxx` range).
///
/// These tokens represent native methods resolved through `GetProcAddress` and
/// wrapped in delegates via `Marshal.GetDelegateForFunctionPointer`. When the
/// delegate's `Invoke` is called, the dispatcher recognizes these tokens and
/// returns a default success value (e.g. `I32(1)` for `BOOL`-returning APIs
/// like `VirtualProtect`).
pub mod native {
    use crate::metadata::token::Token;

    /// Base value for the native function pointer token range.
    /// Individual function tokens are `RANGE_BASE | function_id`.
    pub const RANGE_BASE: u32 = 0x7F03_0000;

    /// Default marker method token for delegates wrapping native function pointers
    /// when the specific function cannot be identified.
    pub const NATIVE_FUNCTION_POINTER: Token = Token::new(RANGE_BASE | 0x0001);

    /// Creates a native function pointer token from a function ID.
    #[must_use]
    pub const fn token_for_id(id: u32) -> Token {
        Token::new(RANGE_BASE | id)
    }
}

/// Fake virtual addresses used by P/Invoke and native interop hooks.
///
/// These addresses are returned by emulated Win32 API hooks (`GetModuleHandle`,
/// `LoadLibrary`, `GetProcAddress`) and must not overlap with each other or with
/// PE image addresses (typically `0x0040_0000`..`0x0042_0000`).
///
/// # Address Map
///
/// | Range | Purpose |
/// |-------|---------|
/// | `0x0040_0000` | Current process image base (`GetModuleHandle(NULL)`) |
/// | `0x7FFD_0000`..`0x7FFD_FFFF` | Per-function fake addresses (`GetProcAddress`) |
/// | `0x7FFC_0000` | Fallback for `GetFunctionPointerForDelegate` |
/// | `0x7FFE_0000` | Non-null module handle (`GetModuleHandle(other)`) |
/// | `0x7FFE_2000` | Loaded DLL handle (`LoadLibrary`) |
pub mod native_addresses {
    /// Image base address for the current process module.
    ///
    /// Returned by `GetModuleHandle(NULL)`. Matches the default Win32 PE image
    /// base so that pointer arithmetic against the PE header produces correct
    /// offsets.
    pub const CURRENT_MODULE: i64 = 0x0040_0000;

    /// Handle returned for non-null `GetModuleHandle` calls (requesting a
    /// specific DLL by name). Must differ from [`CURRENT_MODULE`] so callers
    /// can distinguish the main module from loaded DLLs.
    pub const OTHER_MODULE: i64 = 0x7FFE_0000;

    /// Handle returned by all `LoadLibrary` variants.
    pub const LOADED_LIBRARY: i64 = 0x7FFE_2000;

    /// Base address for per-function fake pointers allocated by `GetProcAddress`.
    /// Each distinct function name gets `PROC_ADDRESS_BASE + N * PROC_ADDRESS_PAGE`.
    pub const PROC_ADDRESS_BASE: u64 = 0x7FFD_0000;

    /// Page-size increment between consecutive `GetProcAddress` allocations.
    pub const PROC_ADDRESS_PAGE: u64 = 0x1000;

    /// Fallback address returned by `GetFunctionPointerForDelegate` when the
    /// delegate doesn't wrap a known native function.
    pub const DELEGATE_FUNCTION_POINTER_FALLBACK: i64 = 0x7FFC_0000;
}

/// BCL helper type tokens for internal hook objects.
pub mod helpers {
    use crate::metadata::token::Token;

    /// `List<T>.Enumerator` helper object type.
    pub const LIST_ENUMERATOR: Token = Token::new(0x7FFF_0001);
    /// `RNGCryptoServiceProvider` / `RandomNumberGenerator` helper object type.
    pub const RNG: Token = Token::new(0x7FFF_0010);
}

/// Field tokens for `System.Exception` and its subclasses.
///
/// These use the 0xEF00_xxxx range (table 0xEF, unused in ECMA-335) for
/// sentinel fields on exception objects.
pub mod exception_fields {
    use crate::metadata::token::Token;

    /// `Exception.Message` field.
    pub const MESSAGE: Token = Token::new(0xEF00_0010);
    /// `Exception.InnerException` field.
    pub const INNER_EXCEPTION: Token = Token::new(0xEF00_0011);
    /// `Exception.HResult` field.
    pub const HRESULT: Token = Token::new(0xEF00_0012);
    /// `Exception.Source` field.
    pub const SOURCE: Token = Token::new(0xEF00_0013);
}

/// Field tokens for `List<T>.Enumerator` helper objects.
///
/// These use the 0xEF00_xxxx range (table 0xEF, unused in ECMA-335).
pub mod enumerator_fields {
    use crate::metadata::token::Token;

    /// Reference back to the parent `List<T>` object.
    pub const LIST_REF: Token = Token::new(0xEF00_0001);
    /// Current iteration position.
    pub const POSITION: Token = Token::new(0xEF00_0002);
}

/// Field tokens for `RNGCryptoServiceProvider` helper objects.
///
/// These use the 0xEF00_xxxx range (table 0xEF, unused in ECMA-335).
pub mod rng_fields {
    use crate::metadata::token::Token;

    /// Xorshift64 PRNG state stored on the RNG object.
    pub const STATE: Token = Token::new(0xEF00_FF01);
}

/// Field tokens for `CustomAttributeData` objects (0x7F04_xxxx range).
pub mod attribute_fields {
    use crate::metadata::token::Token;

    /// Interface type field on `CustomAttributeData`.
    pub const INTERFACE_TYPE: Token = Token::new(0x7F04_0001);
    /// Interface methods array field on `CustomAttributeData`.
    pub const INTERFACE_METHODS: Token = Token::new(0x7F04_0002);
    /// Target methods array field on `CustomAttributeData`.
    pub const TARGET_METHODS: Token = Token::new(0x7F04_0003);
}

/// Field tokens for I/O types (`BinaryReader`, `BinaryWriter`, `FileInfo`, `StreamReader`).
///
/// These use the `0xFFFF_xxxx` range (table 0xFF, unused in ECMA-335) for
/// sentinel fields that link I/O wrapper objects to their underlying streams.
pub mod io_fields {
    use crate::metadata::token::Token;

    /// Underlying `Stream` reference stored on a `BinaryReader` object.
    pub const BINARY_READER_STREAM: Token = Token::new(0xFFFF_0001);
    /// Underlying `Stream` reference stored on a `BinaryWriter` object.
    pub const BINARY_WRITER_STREAM: Token = Token::new(0xFFFF_0002);
    /// File path stored on a `FileInfo` object.
    pub const FILEINFO_PATH: Token = Token::new(0xFFFF_0020);
    /// Underlying `Stream` reference stored on a `StreamReader` object.
    pub const STREAMREADER_STREAM: Token = Token::new(0xFFFF_0030);
}

/// Field tokens for `Span<T>` and `Memory<T>` wrapper objects.
pub mod span_fields {
    use crate::metadata::token::Token;

    /// Underlying array reference in `Span<T>`.
    pub const SPAN_ARRAY: Token = Token::new(0x7F04_0022);
    /// Underlying array reference in `Memory<T>`.
    pub const MEMORY_ARRAY: Token = Token::new(0x7F04_0023);
}

/// Field tokens for `StackFrame` and `AssemblyName` objects.
pub mod misc_fields {
    use crate::metadata::token::Token;

    /// Method token stored on a `StackFrame` object.
    pub const STACKFRAME_METHOD: Token = Token::new(0x04FF_0001);
    /// Name string stored on an `AssemblyName` object.
    pub const ASSEMBLY_NAME_NAME: Token = Token::new(0x04FF_0010);
    /// `OpCode.Value` field on a boxed OpCode struct.
    pub const OPCODE_VALUE: Token = Token::new(0x7F00_0E01);
}

/// Field tokens for `System.Diagnostics.Process` and `ProcessModule` objects.
pub mod process_fields {
    use crate::metadata::token::Token;

    /// `Process.MainModule` — stores `ProcessModule` reference on a `Process` object.
    pub const MAIN_MODULE: Token = Token::new(0xEF00_0020);
    /// `ProcessModule.FileName` — stores filename string on a `ProcessModule` object.
    pub const FILE_NAME: Token = Token::new(0xEF00_0021);
    /// `ProcessModule.BaseAddress` — stores native int PE base address.
    pub const BASE_ADDRESS: Token = Token::new(0xEF00_0022);
    /// `ProcessModule.ModuleMemorySize` — stores int32 size of image in memory.
    pub const MODULE_MEMORY_SIZE: Token = Token::new(0xEF00_0023);
    /// `ProcessModule.ModuleName` — stores module name string.
    pub const MODULE_NAME: Token = Token::new(0xEF00_0024);
}

/// Constants for dynamic token range detection.
pub mod ranges {
    /// Base address for synthetic method tokens (`DynamicMethod` / `ILGenerator`).
    ///
    /// Tokens are allocated as `SYNTHETIC_METHOD_BASE | id` where `id` starts at 1.
    pub const SYNTHETIC_METHOD_BASE: u32 = 0x7F02_0000;

    /// Mask for isolating the range prefix of synthetic method tokens.
    pub const SYNTHETIC_METHOD_MASK: u32 = 0xFFFF_0000;

    /// Base address for generic instantiation tokens.
    ///
    /// Tokens are allocated as `GENERIC_INSTANTIATION_BASE | id`.
    pub const GENERIC_INSTANTIATION_BASE: u32 = 0xF100_0000;

    /// Mask for isolating the range prefix of generic instantiation tokens.
    pub const GENERIC_INSTANTIATION_MASK: u32 = 0xFF00_0000;

    /// Base address for SzArray primitive tokens.
    ///
    /// Encodes "SzArray of primitive type" as `SZARRAY_PRIMITIVE_BASE | element_kind_id`.
    /// For example, `byte[]` is `SZARRAY_PRIMITIVE_BASE | 5` (U1=5 from CilPrimitiveKind).
    ///
    /// These tokens are produced by `type_signature_to_token` for `SzArray(T)` when `T`
    /// is a primitive type. The `GetTypeFromHandle` and `GetElementType` hooks recognize
    /// this range and handle the array/element relationship correctly.
    pub const SZARRAY_PRIMITIVE_BASE: u32 = 0xF000_0100;

    /// Mask for detecting SzArray primitive tokens.
    pub const SZARRAY_PRIMITIVE_MASK: u32 = 0xFFFF_FF00;
}

/// Returns `true` if the token is a synthetic exception type (`0x7F01_xxxx`).
#[must_use]
pub fn is_exception_type(token: Token) -> bool {
    token.value() & 0xFFFF_0000 == 0x7F01_0000
}

/// Returns `true` if the token is a synthetic heap-object type (`0x7F00_xxxx`).
#[must_use]
pub fn is_heap_type(token: Token) -> bool {
    token.value() & 0xFFFF_0000 == 0x7F00_0000
}

/// Returns `true` if the token is a BCL helper type (`0x7FFF_xxxx`).
#[must_use]
pub fn is_helper_type(token: Token) -> bool {
    token.value() & 0xFFFF_0000 == 0x7FFF_0000
}

/// Returns `true` if the token is a synthetic method (`0x7F02_xxxx`).
#[must_use]
pub fn is_synthetic_method(token: Token) -> bool {
    token.value() & ranges::SYNTHETIC_METHOD_MASK == ranges::SYNTHETIC_METHOD_BASE
}

/// Returns `true` if the token is a native function pointer method (`0x7F03_xxxx`).
#[must_use]
pub fn is_native_function_pointer(token: Token) -> bool {
    token.value() & 0xFFFF_0000 == native::RANGE_BASE
}

/// Returns `true` if the token is a generic instantiation (`0xF1xx_xxxx`).
#[must_use]
pub fn is_generic_instantiation(token: Token) -> bool {
    token.value() & ranges::GENERIC_INSTANTIATION_MASK == ranges::GENERIC_INSTANTIATION_BASE
}

/// Returns `true` if the token represents an SzArray of a primitive type.
#[must_use]
pub fn is_szarray_primitive(token: Token) -> bool {
    token.value() & ranges::SZARRAY_PRIMITIVE_MASK == ranges::SZARRAY_PRIMITIVE_BASE
}

/// Extracts the element type token from an SzArray primitive token.
///
/// Returns `Some(element_token)` where element_token is the `CilPrimitiveKind::token()`
/// of the array's element type. Returns `None` if the token is not an SzArray primitive.
#[must_use]
pub fn szarray_element_token(token: Token) -> Option<Token> {
    if !is_szarray_primitive(token) {
        return None;
    }
    // The element kind ID is in the low byte
    let kind_id = token.value() & 0xFF;
    // Reconstruct the primitive token: 0xF000_0000 | kind_id
    Some(Token::new(0xF000_0000 | kind_id))
}

/// Returns `true` if the token belongs to any synthetic range used by the emulator.
///
/// This covers exception types, heap types, helper types, synthetic methods,
/// synthetic fields (0x7F04), I/O fields (0xFF), and generic instantiations.
#[must_use]
pub fn is_synthetic(token: Token) -> bool {
    let table = token.value() >> 24;
    matches!(table, 0x7F | 0xEF | 0xF1 | 0xFF)
}

#[cfg(test)]
mod tests {
    use crate::{
        emulation::{
            synthetic_exception,
            tokens::{
                self, codegen, collections, crypto, helpers, io, io_fields, native, ranges,
                reflection, singletons, system,
            },
        },
        metadata::token::Token,
    };

    #[test]
    fn exception_type_detection() {
        assert!(tokens::is_exception_type(
            synthetic_exception::BASE_EXCEPTION
        ));
        assert!(tokens::is_exception_type(
            synthetic_exception::NULL_REFERENCE
        ));
        assert!(tokens::is_exception_type(
            synthetic_exception::NOT_IMPLEMENTED
        ));
        assert!(!tokens::is_exception_type(reflection::TYPE));
        assert!(!tokens::is_exception_type(Token::new(0x0200_0001)));
    }

    #[test]
    fn heap_type_detection() {
        assert!(tokens::is_heap_type(reflection::TYPE));
        assert!(tokens::is_heap_type(system::STRING));
        assert!(tokens::is_heap_type(singletons::ASSEMBLY));
        assert!(!tokens::is_heap_type(helpers::LIST_ENUMERATOR));
        assert!(!tokens::is_heap_type(Token::new(0x7F01_0000)));
    }

    #[test]
    fn helper_type_detection() {
        assert!(tokens::is_helper_type(helpers::LIST_ENUMERATOR));
        assert!(tokens::is_helper_type(helpers::RNG));
        assert!(!tokens::is_helper_type(reflection::TYPE));
    }

    #[test]
    fn synthetic_method_detection() {
        assert!(tokens::is_synthetic_method(Token::new(
            ranges::SYNTHETIC_METHOD_BASE | 1
        )));
        assert!(tokens::is_synthetic_method(Token::new(
            ranges::SYNTHETIC_METHOD_BASE | 0xFFFF
        )));
        assert!(!tokens::is_synthetic_method(reflection::TYPE));
    }

    #[test]
    fn native_function_pointer_detection() {
        assert!(tokens::is_native_function_pointer(
            native::NATIVE_FUNCTION_POINTER
        ));
        assert!(tokens::is_native_function_pointer(Token::new(0x7F03_0002)));
        assert!(!tokens::is_native_function_pointer(reflection::TYPE));
        assert!(!tokens::is_native_function_pointer(Token::new(
            ranges::SYNTHETIC_METHOD_BASE | 1
        )));
    }

    #[test]
    fn generic_instantiation_detection() {
        assert!(tokens::is_generic_instantiation(Token::new(
            ranges::GENERIC_INSTANTIATION_BASE | 42
        )));
        assert!(!tokens::is_generic_instantiation(reflection::TYPE));
    }

    #[test]
    fn is_synthetic_covers_all_ranges() {
        // Table 0x7F
        assert!(tokens::is_synthetic(reflection::TYPE));
        assert!(tokens::is_synthetic(helpers::LIST_ENUMERATOR));
        assert!(tokens::is_synthetic(Token::new(
            ranges::SYNTHETIC_METHOD_BASE | 1
        )));
        assert!(tokens::is_synthetic(Token::new(0x7F04_0001)));
        assert!(tokens::is_synthetic(native::NATIVE_FUNCTION_POINTER));

        // Table 0xEF
        assert!(tokens::is_synthetic(Token::new(0xEF00_0010)));

        // Table 0xF1
        assert!(tokens::is_synthetic(Token::new(
            ranges::GENERIC_INSTANTIATION_BASE | 1
        )));

        // Table 0xFF (I/O fields)
        assert!(tokens::is_synthetic(io_fields::BINARY_READER_STREAM));
        assert!(tokens::is_synthetic(io_fields::FILEINFO_PATH));

        // Real metadata token
        assert!(!tokens::is_synthetic(Token::new(0x0200_0001)));
        assert!(!tokens::is_synthetic(Token::new(0x0600_0001)));
    }

    #[test]
    fn no_value_collisions_within_type_tokens() {
        let type_tokens = [
            reflection::TYPE,
            reflection::METHOD,
            reflection::MODULE,
            reflection::FIELD,
            reflection::PROPERTY,
            reflection::PARAMETER,
            reflection::METHOD_BODY,
            reflection::CUSTOM_ATTRIBUTE_DATA,
            reflection::ASSEMBLY_NAME,
            crypto::KEY_DERIVATION,
            crypto::CRYPTO_ALGORITHM,
            crypto::SYMMETRIC_ALGORITHM,
            crypto::CRYPTO_TRANSFORM,
            io::STREAM,
            io::CRYPTO_STREAM,
            io::COMPRESSED_STREAM,
            collections::DICTIONARY,
            collections::LIST,
            collections::STACK,
            collections::QUEUE,
            collections::HASH_SET,
            codegen::DYNAMIC_METHOD,
            codegen::IL_GENERATOR,
            system::STRING,
            system::ARRAY,
            system::ENCODING,
            system::STRING_BUILDER,
            system::THREAD,
            system::TASK,
            system::SPAN,
            system::MEMORY,
            system::PROCESS,
            system::PROCESS_MODULE,
            singletons::ASSEMBLY,
            singletons::APP_DOMAIN,
            helpers::LIST_ENUMERATOR,
            helpers::RNG,
        ];

        for (i, a) in type_tokens.iter().enumerate() {
            for (j, b) in type_tokens.iter().enumerate() {
                if i != j {
                    assert_ne!(
                        a.value(),
                        b.value(),
                        "collision between type_tokens[{i}] (0x{:08X}) and type_tokens[{j}] (0x{:08X})",
                        a.value(),
                        b.value()
                    );
                }
            }
        }
    }
}