dotscope 0.6.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! .NET CIL method exception handler representation and analysis.
//!
//! This module provides comprehensive support for analyzing exception handling structures
//! in Common Intermediate Language (CIL) method bodies. Exception handlers define
//! try/catch/finally/fault regions that control program flow during exception processing,
//! as specified by ECMA-335.
//!
//! # Exception Handling in .NET
//!
//! The .NET runtime uses structured exception handling (SEH) with four types of handlers:
//!
//! 1. **Exception Handlers**: Catch specific exception types using type matching
//! 2. **Filter Handlers**: Use custom filter expressions to determine exception handling
//! 3. **Finally Handlers**: Execute cleanup code regardless of exception occurrence
//! 4. **Fault Handlers**: Execute cleanup code only when exceptions are thrown
//!
//! ## Exception Handler Layout
//!
//! Exception handlers are defined by two regions in the IL code:
//! ```text
//! try {
//!     // Protected region: [try_offset, try_offset + try_length)
//!     // Code that may throw exceptions
//! }
//! catch (SpecificException) {
//!     // Handler region: [handler_offset, handler_offset + handler_length)
//!     // Exception handling code
//! }
//! ```
//!
//! # Common Use Cases
//!
//! ## Exception Handler Analysis
//!
//! ```rust
//! use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
//!
//! # fn analyze_method_body() -> Result<(), Box<dyn std::error::Error>> {
//! # let exception_handlers: Vec<ExceptionHandler> = vec![];
//! for handler in &exception_handlers {
//!     match handler.flags {
//!         ExceptionHandlerFlags::EXCEPTION => {
//!             println!("Catch block for try region [{}, {})",
//!                 handler.try_offset,
//!                 handler.try_offset + handler.try_length);
//!             
//!             if let Some(exception_type) = &handler.handler {
//!                 println!("  Catches: {}", exception_type.name);
//!             }
//!         },
//!         ExceptionHandlerFlags::FINALLY => {
//!             println!("Finally block at offset 0x{:04X}", handler.handler_offset);
//!         },
//!         ExceptionHandlerFlags::FILTER => {
//!             println!("Filter handler at offset 0x{:04X}", handler.filter_offset);
//!         },
//!         ExceptionHandlerFlags::FAULT => {
//!             println!("Fault handler at offset 0x{:04X}", handler.handler_offset);
//!         },
//!         _ => println!("Unknown handler type: {:?}", handler.flags),
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Control Flow Graph Construction
//!
//! ```rust
//! # use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
//! # fn build_control_flow_graph() -> Result<(), Box<dyn std::error::Error>> {
//! # let exception_handlers: Vec<ExceptionHandler> = vec![];
//! // Exception handlers create additional control flow edges
//! for handler in &exception_handlers {
//!     // Entry point for protected region
//!     let protected_start = handler.try_offset;
//!     let protected_end = handler.try_offset + handler.try_length;
//!     
//!     // Handler entry point
//!     let handler_start = handler.handler_offset;
//!     
//!     // Any instruction in protected region can transfer to handler
//!     println!("Protected region: [0x{:04X}, 0x{:04X}) -> Handler: 0x{:04X}",
//!         protected_start, protected_end, handler_start);
//!         
//!     if handler.flags == ExceptionHandlerFlags::FILTER {
//!         println!("  Filter expression at: 0x{:04X}", handler.filter_offset);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Security Analysis
//!
//! ```rust
//! # use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
//! # fn security_analysis() -> Result<(), Box<dyn std::error::Error>> {
//! # let exception_handlers: Vec<ExceptionHandler> = vec![];
//! // Analyze exception handling patterns for security implications
//! let mut has_generic_catch = false;
//! let mut has_empty_catch = false;
//!
//! for handler in &exception_handlers {
//!     if handler.flags == ExceptionHandlerFlags::EXCEPTION {
//!         if let Some(exception_type) = &handler.handler {
//!             if exception_type.name == "System.Exception" {
//!                 has_generic_catch = true;
//!             }
//!         }
//!         
//!         if handler.handler_length == 0 {
//!             has_empty_catch = true;
//!         }
//!     }
//! }
//!
//! if has_generic_catch {
//!     println!("WARNING: Catches all exceptions (potential information hiding)");
//! }
//! if has_empty_catch {
//!     println!("WARNING: Empty exception handler (swallows exceptions)");
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Binary Format
//!
//! Exception handlers are stored in method body headers using two formats:
//!
//! ## Small Format (12 bytes per handler)
//! ```text
//! - Flags: u16
//! - TryOffset: u16  
//! - TryLength: u8
//! - HandlerOffset: u16
//! - HandlerLength: u8
//! - ClassToken/FilterOffset: u32
//! ```
//!
//! ## Fat Format (24 bytes per handler)
//! ```text
//! - Flags: u32
//! - TryOffset: u32
//! - TryLength: u32  
//! - HandlerOffset: u32
//! - HandlerLength: u32
//! - ClassToken/FilterOffset: u32
//! ```
//!
//! # ECMA-335 Compliance
//!
//! This implementation follows ECMA-335 6th Edition specifications:
//! - **Partition I, Section 12.4**: Exception handling model
//! - **Partition II, Section 25.4.6**: Exception handling clauses format
//! - **Partition III, Section 1.7.5**: Exception handling instruction semantics
//!
//! # Thread Safety
//!
//! [`ExceptionHandler`] instances are immutable and safe to share across threads.
//! Exception type references use reference-counted smart pointers for efficient sharing.

use bitflags::bitflags;

use crate::{metadata::typesystem::CilTypeRc, Result};

bitflags! {
    /// Exception handler type flags defining the kind of exception handling clause.
    ///
    /// These flags determine how the exception handler processes exceptions and controls
    /// program flow within structured exception handling blocks. Each flag represents
    /// a different exception handling strategy as defined by ECMA-335.
    ///
    /// # Handler Types
    ///
    /// The four fundamental exception handler types each serve different purposes:
    ///
    /// - **Exception Handlers**: Type-based exception catching with class token matching
    /// - **Filter Handlers**: Custom filter expressions for complex exception logic
    /// - **Finally Handlers**: Guaranteed cleanup code execution
    /// - **Fault Handlers**: Exception-only cleanup code execution
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::method::ExceptionHandlerFlags;
    ///
    /// // Check handler type
    /// let flags = ExceptionHandlerFlags::EXCEPTION;
    /// assert!(flags == ExceptionHandlerFlags::EXCEPTION);
    /// assert!(!flags.contains(ExceptionHandlerFlags::FINALLY));
    ///
    /// // Multiple flags are mutually exclusive for exception handlers
    /// assert!(ExceptionHandlerFlags::EXCEPTION.bits() == 0x0000);
    /// assert!(ExceptionHandlerFlags::FILTER.bits() == 0x0001);
    /// ```
    ///
    /// # Binary Representation
    ///
    /// The flags are stored as a 16-bit or 32-bit value in the exception handler
    /// table, depending on whether the small or fat format is used.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct ExceptionHandlerFlags: u16 {
        /// A typed exception clause that catches specific exception types.
        ///
        /// The handler catches exceptions that are assignment-compatible with the
        /// exception type specified by the `class_token` field. This includes the
        /// exact type and all derived types.
        ///
        /// # Usage
        ///
        /// ```csharp
        /// try {
        ///     // Protected code
        /// }
        /// catch (ArgumentException ex) {
        ///     // Handler code - class_token points to ArgumentException
        /// }
        /// ```
        ///
        /// # Implementation Notes
        ///
        /// - The `class_token` field contains the metadata token of the exception type
        /// - Type matching follows .NET inheritance rules (catches derived types)
        /// - Most common exception handler type in .NET assemblies
        const EXCEPTION = 0x0000;

        /// An exception filter and handler clause with custom filter logic.
        ///
        /// The filter expression is executed first to determine whether this handler
        /// should process the exception. The filter can examine the exception object
        /// and execution context to make complex decisions.
        ///
        /// # Usage
        ///
        /// ```csharp
        /// try {
        ///     // Protected code
        /// }
        /// catch (Exception ex) when (ex.Message.Contains("specific")) {
        ///     // Handler code - filter_offset points to filter expression
        /// }
        /// ```
        ///
        /// # Implementation Notes
        ///
        /// - The `filter_offset` field points to the filter expression code
        /// - Filter must leave a boolean value on the evaluation stack
        /// - Provides fine-grained control over exception handling logic
        /// - Less common than typed exception handlers
        const FILTER = 0x0001;

        /// A finally clause that executes regardless of exception occurrence.
        ///
        /// Finally blocks provide guaranteed cleanup code execution during both
        /// normal control flow and exception unwinding. The runtime ensures
        /// finally blocks execute even when exceptions are thrown.
        ///
        /// # Usage
        ///
        /// ```csharp
        /// try {
        ///     // Protected code
        /// }
        /// finally {
        ///     // Cleanup code - always executes
        /// }
        /// ```
        ///
        /// # Implementation Notes
        ///
        /// - Executes during normal method exit and exception unwinding
        /// - Cannot catch exceptions, only perform cleanup
        /// - Essential for resource management (using statements compile to finally)
        /// - The `class_token`/`filter_offset` field is unused for finally handlers
        const FINALLY = 0x0002;

        /// A fault clause that executes only when exceptions are thrown.
        ///
        /// Fault handlers are similar to finally blocks but only execute during
        /// exception unwinding, not during normal control flow. They provide
        /// exception-specific cleanup without catching the exception.
        ///
        /// # Usage
        ///
        /// ```csharp
        /// try {
        ///     // Protected code
        /// }
        /// fault {
        ///     // Cleanup code - executes only on exceptions
        /// }
        /// ```
        ///
        /// # Implementation Notes
        ///
        /// - Only executes during exception unwinding, not normal exit
        /// - Cannot catch exceptions, only perform fault-specific cleanup
        /// - Less common than finally handlers in typical .NET code
        /// - The `class_token`/`filter_offset` field is unused for fault handlers
        const FAULT = 0x0004;
    }
}

/// Represents a single exception handler within a .NET method body.
///
/// An `ExceptionHandler` defines a structured exception handling region that consists
/// of a protected try block and associated handler code. Exception handlers implement
/// the .NET runtime's structured exception handling (SEH) model as specified by ECMA-335.
///
/// # Structure
///
/// Each exception handler defines two key regions:
///
/// 1. **Protected Region**: The try block where exceptions may be thrown
/// 2. **Handler Region**: The catch/finally/fault code that processes exceptions
///
/// # Handler Types and Field Usage
///
/// Different handler types use the fields differently:
///
/// ## Exception Handlers (`EXCEPTION` flag)
/// - `handler`: Contains the exception type that this handler catches
/// - `filter_offset`: Unused (contains class token value for historical reasons)
/// - Catches exceptions assignable to the specified type
///
/// ## Filter Handlers (`FILTER` flag)  
/// - `handler`: Contains the exception type (typically `System.Exception`)
/// - `filter_offset`: Points to the filter expression code within the method
/// - Filter code determines whether to handle the exception
///
/// ## Finally Handlers (`FINALLY` flag)
/// - `handler`: Unused (None)
/// - `filter_offset`: Unused  
/// - Always executes during normal and exceptional control flow
///
/// ## Fault Handlers (`FAULT` flag)
/// - `handler`: Unused (None)
/// - `filter_offset`: Unused
/// - Executes only during exception unwinding
///
/// # Memory Layout
///
/// ```text
/// Try Block:     [try_offset, try_offset + try_length)
/// Handler Block: [handler_offset, handler_offset + handler_length)
/// Filter Block:  [filter_offset, ...]  (FILTER handlers only)
/// ```
///
/// # Examples
///
/// ## Basic Exception Handler Analysis
///
/// ```rust
/// use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
///
/// # fn analyze_handler(handler: &ExceptionHandler) -> Result<(), Box<dyn std::error::Error>> {
/// match handler.flags {
///     ExceptionHandlerFlags::EXCEPTION => {
///         println!("Exception handler:");
///         println!("  Protected: [0x{:04X}, 0x{:04X})",
///             handler.try_offset,
///             handler.try_offset + handler.try_length);
///         println!("  Handler: [0x{:04X}, 0x{:04X})",
///             handler.handler_offset,
///             handler.handler_offset + handler.handler_length);
///             
///         if let Some(exception_type) = &handler.handler {
///             println!("  Catches: {}", exception_type.name);
///         }
///     },
///     ExceptionHandlerFlags::FINALLY => {
///         println!("Finally handler at 0x{:04X} (length: {})",
///             handler.handler_offset, handler.handler_length);
///     },
///     _ => println!("Other handler type: {:?}", handler.flags),
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Control Flow Edge Detection
///
/// ```rust
/// # use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
/// # fn detect_control_flow_edges(handlers: &[ExceptionHandler]) -> Result<(), Box<dyn std::error::Error>> {
/// for handler in handlers {
///     // Any instruction in the protected region can transfer to the handler
///     for offset in handler.try_offset..(handler.try_offset + handler.try_length) {
///         println!("IL_{:04X} -> Handler_{:04X} (exception edge)",
///             offset, handler.handler_offset);
///     }
///     
///     // Filter handlers have additional control flow
///     if handler.flags == ExceptionHandlerFlags::FILTER {
///         println!("IL_{:04X} -> Filter_{:04X} (filter evaluation)",
///             handler.try_offset, handler.filter_offset);
///         println!("Filter_{:04X} -> Handler_{:04X} (filter success)",
///             handler.filter_offset, handler.handler_offset);
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Exception Handler Overlap Detection
///
/// ```rust
/// # use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
/// # fn check_handler_overlap(handlers: &[ExceptionHandler]) -> Result<(), Box<dyn std::error::Error>> {
/// for (i, handler1) in handlers.iter().enumerate() {
///     for (j, handler2) in handlers.iter().enumerate() {
///         if i != j {
///             let h1_start = handler1.try_offset;
///             let h1_end = handler1.try_offset + handler1.try_length;
///             let h2_start = handler2.try_offset;
///             let h2_end = handler2.try_offset + handler2.try_length;
///             
///             // Check for nested or overlapping handlers
///             if h1_start < h2_end && h2_start < h1_end {
///                 println!("Overlapping handlers: [{}, {}) and [{}, {})",
///                     h1_start, h1_end, h2_start, h2_end);
///             }
///         }
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Binary Format Compatibility
///
/// Exception handlers support both small (12-byte) and fat (24-byte) binary formats.
/// The format choice depends on the size of offsets and lengths in the method body.
/// This struct normalizes both formats to 32-bit fields for consistent processing.
///
/// # ECMA-335 References
///
/// - **Partition I, Section 12.4**: Exception handling model and semantics  
/// - **Partition II, Section 25.4.6**: Exception handling clause binary format
/// - **Partition III, Section 1.7.5**: Exception handling instruction behavior
///
/// # Thread Safety
///
/// `ExceptionHandler` instances are immutable and safe to share across threads.
/// The optional exception type reference uses a reference-counted smart pointer.
pub struct ExceptionHandler {
    /// Exception handler type flags (EXCEPTION, FILTER, FINALLY, or FAULT).
    ///
    /// Determines the behavior and semantics of this exception handler. Each flag
    /// corresponds to a different exception handling strategy defined by ECMA-335.
    /// The flags are mutually exclusive - each handler has exactly one type.
    pub flags: ExceptionHandlerFlags,

    /// Byte offset of the protected try block from the start of the method body.
    ///
    /// This offset points to the first IL instruction that is protected by this
    /// exception handler. All instructions in the range [`try_offset`, `try_offset` + `try_length`)
    /// are covered by this handler and can potentially transfer control to the handler code.
    pub try_offset: u32,

    /// Length of the protected try block in bytes.
    ///
    /// Combined with `try_offset`, this defines the complete protected region.
    /// The protected region spans [`try_offset`, `try_offset` + `try_length`) and includes
    /// all IL instructions that may throw exceptions handled by this handler.
    pub try_length: u32,

    /// Byte offset of the exception handler code from the start of the method body.
    ///
    /// Points to the first IL instruction of the handler code (catch, finally, or fault block).
    /// For FILTER handlers, this points to the actual handler code, not the filter expression.
    /// The handler code spans [`handler_offset`, `handler_offset` + `handler_length`).
    pub handler_offset: u32,

    /// Length of the exception handler code in bytes.
    ///
    /// Defines the size of the handler code block. Combined with `handler_offset`,
    /// this specifies the complete range of IL instructions that comprise the
    /// exception handling logic for this handler.
    pub handler_length: u32,

    /// The exception type that this handler catches (for EXCEPTION handlers only).
    ///
    /// Contains a reference to the .NET type that this handler catches. For EXCEPTION
    /// handlers, this specifies the exact type and all derived types that will be
    /// caught. For other handler types (FILTER, FINALLY, FAULT), this field is None.
    ///
    /// # Type Matching
    ///
    /// Exception catching follows .NET's type system rules:
    /// - Exact type matches are caught
    /// - Derived types (subclasses) are caught  
    /// - Interface implementations are caught if the exception type is an interface
    /// - System.Object catches all exceptions
    pub handler: Option<CilTypeRc>,

    /// Byte offset of the filter expression code (for FILTER handlers only).
    ///
    /// For FILTER handlers, this points to the IL code that evaluates whether
    /// this handler should process the exception. The filter code must leave
    /// a boolean value on the evaluation stack. For non-FILTER handlers, this
    /// field may contain legacy data and should be ignored.
    ///
    /// # Filter Execution
    ///
    /// The filter expression:
    /// 1. Receives the exception object and execution context
    /// 2. Executes custom logic to test the exception
    /// 3. Returns true (1) to handle or false (0) to continue unwinding
    ///
    /// # Dual Purpose (ECMA-335 II.25.4.6)
    ///
    /// This field has different meanings depending on the handler type:
    /// - **FILTER handlers**: Contains the IL byte offset where the filter expression begins
    /// - **EXCEPTION handlers**: Initially contains the TypeDef/TypeRef/TypeSpec token for the
    ///   caught exception type (before resolution). After type resolution via
    ///   [`Method::parse()`][crate::metadata::method::Method::parse], this is cleared to 0
    ///   and the resolved type is stored in the [`handler`][Self::handler] field.
    /// - **FINALLY/FAULT handlers**: Should be 0 (unused)
    ///
    /// For type-safe access, use the [`get_filter_offset()`][Self::get_filter_offset] and
    /// [`get_class_token()`][Self::get_class_token] accessor methods.
    pub filter_offset: u32,
}

impl ExceptionHandler {
    /// Returns the filter expression offset for FILTER handlers.
    ///
    /// For FILTER exception handlers, this returns the IL byte offset where the
    /// filter expression code begins. The filter expression evaluates whether
    /// this handler should process the current exception.
    ///
    /// # Returns
    ///
    /// - `Some(offset)` if this is a FILTER handler
    /// - `None` for all other handler types (EXCEPTION, FINALLY, FAULT)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
    ///
    /// let handler = ExceptionHandler {
    ///     flags: ExceptionHandlerFlags::FILTER,
    ///     try_offset: 0,
    ///     try_length: 10,
    ///     handler_offset: 20,
    ///     handler_length: 5,
    ///     handler: None,
    ///     filter_offset: 15,
    /// };
    ///
    /// assert_eq!(handler.get_filter_offset(), Some(15));
    /// ```
    #[must_use]
    pub fn get_filter_offset(&self) -> Option<u32> {
        if self.flags.contains(ExceptionHandlerFlags::FILTER) {
            Some(self.filter_offset)
        } else {
            None
        }
    }

    /// Returns the class token for unresolved EXCEPTION handlers.
    ///
    /// For EXCEPTION (catch) handlers that have not yet been resolved, this returns
    /// the raw TypeDef/TypeRef/TypeSpec token that identifies the exception type
    /// to catch.
    ///
    /// # Returns
    ///
    /// - `Some(token)` if this is an EXCEPTION handler with a non-zero token
    ///   (i.e., before type resolution)
    /// - `None` if this is not an EXCEPTION handler, or if the type has already
    ///   been resolved (token cleared to 0)
    ///
    /// # Note
    ///
    /// After [`Method::parse()`][crate::metadata::method::Method::parse] is called,
    /// the class token is resolved to an actual type reference stored in the
    /// [`handler`][Self::handler] field, and this method will return `None`.
    /// Use the `handler` field to access the resolved type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags};
    ///
    /// // Before type resolution
    /// let handler = ExceptionHandler {
    ///     flags: ExceptionHandlerFlags::EXCEPTION,
    ///     try_offset: 0,
    ///     try_length: 10,
    ///     handler_offset: 10,
    ///     handler_length: 5,
    ///     handler: None,
    ///     filter_offset: 0x01000001, // TypeRef token
    /// };
    ///
    /// assert_eq!(handler.get_class_token(), Some(0x01000001));
    /// ```
    #[must_use]
    pub fn get_class_token(&self) -> Option<u32> {
        // EXCEPTION is 0x0000, so we check that this is a catch handler and has a non-zero token
        if self.is_catch() && self.filter_offset != 0 {
            Some(self.filter_offset)
        } else {
            None
        }
    }

    /// Returns true if this handler catches a specific exception type.
    ///
    /// This is a convenience method to check if the handler is an EXCEPTION
    /// handler (catch block) as opposed to FILTER, FINALLY, or FAULT.
    ///
    /// Since `EXCEPTION = 0x0000`, this checks that none of the other handler
    /// type flags (FILTER, FINALLY, FAULT) are set.
    #[must_use]
    pub fn is_catch(&self) -> bool {
        // EXCEPTION is 0x0000, so we check that no other flags are set
        !self.flags.contains(ExceptionHandlerFlags::FILTER)
            && !self.flags.contains(ExceptionHandlerFlags::FINALLY)
            && !self.flags.contains(ExceptionHandlerFlags::FAULT)
    }

    /// Returns true if this handler is a finally block.
    #[must_use]
    pub fn is_finally(&self) -> bool {
        self.flags.contains(ExceptionHandlerFlags::FINALLY)
    }

    /// Returns true if this handler is a fault block.
    #[must_use]
    pub fn is_fault(&self) -> bool {
        self.flags.contains(ExceptionHandlerFlags::FAULT)
    }

    /// Returns true if this handler uses a filter expression.
    #[must_use]
    pub fn is_filter(&self) -> bool {
        self.flags.contains(ExceptionHandlerFlags::FILTER)
    }
}

/// Encodes exception handlers according to ECMA-335 II.25.4.6.
///
/// Exception handler sections are encoded after the method body with the following format:
/// - Section header (4 bytes for small format, 12 bytes for fat format)
/// - Exception handler entries (12 bytes each for small, 24 bytes each for fat)
///
/// Format selection:
/// - Small format: if all offsets and lengths fit in 16 bits
/// - Fat format: if any offset or length requires 32 bits
///
/// # Limitations
///
/// **Warning**: This function cannot fully encode `EXCEPTION` (catch) handlers. The type token
/// for catch clauses is written as `0` because the original metadata token is not preserved
/// in [`ExceptionHandler`]. This means:
///
/// - **Round-trip operations** (read method → modify → write back) will produce invalid
///   exception handlers for catch blocks
/// - **FILTER, FINALLY, and FAULT handlers** encode correctly as they don't require type tokens
/// - Use this function only for **newly created handlers** where type tokens will be resolved
///   separately, or for handlers that don't catch specific exception types
///
/// To properly support round-trip encoding of catch handlers, the `ExceptionHandler` struct
/// would need to preserve the original `ClassToken` value from parsing.
///
/// # Arguments
///
/// * `handlers` - The exception handlers to encode
///
/// # Returns
///
/// The encoded exception handler section bytes, or an empty vector if no handlers.
///
/// # Errors
///
/// Returns an error if encoding fails or values exceed expected ranges.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::metadata::method::{ExceptionHandler, ExceptionHandlerFlags, encode_exception_handlers};
///
/// let handlers = vec![
///     ExceptionHandler {
///         flags: ExceptionHandlerFlags::FINALLY,
///         try_offset: 0,
///         try_length: 10,
///         handler_offset: 10,
///         handler_length: 5,
///         handler: None,
///         filter_offset: 0,
///     }
/// ];
///
/// let encoded = encode_exception_handlers(&handlers)?;
/// # Ok::<(), dotscope::Error>(())
/// ```
pub fn encode_exception_handlers(handlers: &[ExceptionHandler]) -> Result<Vec<u8>> {
    if handlers.is_empty() {
        return Ok(Vec::new());
    }

    // Determine if we need fat or small format
    let needs_fat_format = handlers.iter().any(|eh| {
        eh.try_offset > 0xFFFF
            || eh.try_length > 0xFFFF
            || eh.handler_offset > 0xFFFF
            || eh.handler_length > 0xFFFF
    });

    let mut section = Vec::new();

    if needs_fat_format {
        // Fat format: 4-byte header + 24 bytes per handler
        let section_size = 4 + (handlers.len() * 24);

        // Section header (fat format)
        section.extend_from_slice(&[
            0x41, // Kind = EHTable | FatFormat
            0x00, 0x00, // Reserved
        ]);
        let section_size_u32 = u32::try_from(section_size)
            .map_err(|_| malformed_error!("Exception section size exceeds u32 range"))?;
        section.extend_from_slice(&section_size_u32.to_le_bytes()[..3]); // DataSize (3 bytes)

        // Write each exception handler (24 bytes each)
        for eh in handlers {
            // Flags (4 bytes)
            section.extend_from_slice(&u32::from(eh.flags.bits()).to_le_bytes());

            // TryOffset (4 bytes)
            section.extend_from_slice(&eh.try_offset.to_le_bytes());

            // TryLength (4 bytes)
            section.extend_from_slice(&eh.try_length.to_le_bytes());

            // HandlerOffset (4 bytes)
            section.extend_from_slice(&eh.handler_offset.to_le_bytes());

            // HandlerLength (4 bytes)
            section.extend_from_slice(&eh.handler_length.to_le_bytes());

            // ClassToken or FilterOffset (4 bytes)
            if eh.flags.contains(ExceptionHandlerFlags::FILTER) {
                // FILTER: filter_offset is the code offset where filter starts
                section.extend_from_slice(&eh.filter_offset.to_le_bytes());
            } else if let Some(handler_type) = &eh.handler {
                // EXCEPTION with resolved type: use the type's token
                section.extend_from_slice(&handler_type.token.value().to_le_bytes());
            } else if eh.flags == ExceptionHandlerFlags::EXCEPTION {
                // EXCEPTION with unresolved type: filter_offset contains the raw type token
                section.extend_from_slice(&eh.filter_offset.to_le_bytes());
            } else {
                // FINALLY (0x02) or FAULT (0x04): no type token needed
                section.extend_from_slice(&0u32.to_le_bytes());
            }
        }
    } else {
        // Small format: 4-byte header + 12 bytes per handler
        let section_size = 4 + (handlers.len() * 12);

        // Section header (small format)
        let section_size_u8 = u8::try_from(section_size).map_err(|_| {
            malformed_error!("Exception section size exceeds u8 range for small format")
        })?;
        section.extend_from_slice(&[
            0x01,            // Kind = EHTable (small format)
            section_size_u8, // DataSize (1 byte)
            0x00,
            0x00, // Reserved
        ]);

        // Write each exception handler (12 bytes each)
        for eh in handlers {
            // Flags (2 bytes)
            section.extend_from_slice(&eh.flags.bits().to_le_bytes());

            // TryOffset (2 bytes)
            let try_offset_u16 = u16::try_from(eh.try_offset)
                .map_err(|_| malformed_error!("Exception handler try_offset exceeds u16 range"))?;
            section.extend_from_slice(&try_offset_u16.to_le_bytes());

            // TryLength (1 byte)
            let try_length_u8 = u8::try_from(eh.try_length)
                .map_err(|_| malformed_error!("Exception handler try_length exceeds u8 range"))?;
            section.push(try_length_u8);

            // HandlerOffset (2 bytes)
            let handler_offset_u16 = u16::try_from(eh.handler_offset).map_err(|_| {
                malformed_error!("Exception handler handler_offset exceeds u16 range")
            })?;
            section.extend_from_slice(&handler_offset_u16.to_le_bytes());

            // HandlerLength (1 byte)
            let handler_length_u8 = u8::try_from(eh.handler_length).map_err(|_| {
                malformed_error!("Exception handler handler_length exceeds u8 range")
            })?;
            section.push(handler_length_u8);

            // ClassToken or FilterOffset (4 bytes)
            if eh.flags.contains(ExceptionHandlerFlags::FILTER) {
                // FILTER: filter_offset is the code offset where filter starts
                section.extend_from_slice(&eh.filter_offset.to_le_bytes());
            } else if let Some(handler_type) = &eh.handler {
                // EXCEPTION with resolved type: use the type's token
                section.extend_from_slice(&handler_type.token.value().to_le_bytes());
            } else if eh.flags == ExceptionHandlerFlags::EXCEPTION {
                // EXCEPTION with unresolved type: filter_offset contains the raw type token
                section.extend_from_slice(&eh.filter_offset.to_le_bytes());
            } else {
                // FINALLY (0x02) or FAULT (0x04): no type token needed
                section.extend_from_slice(&0u32.to_le_bytes());
            }
        }
    }

    // Align to 4-byte boundary
    while section.len() % 4 != 0 {
        section.push(0);
    }

    Ok(section)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_exception_handlers_empty() {
        let handlers = vec![];
        let result = encode_exception_handlers(&handlers).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_encode_exception_handlers_small_format() {
        let handlers = vec![ExceptionHandler {
            flags: ExceptionHandlerFlags::FINALLY,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0,
        }];

        let result = encode_exception_handlers(&handlers).unwrap();

        // Should use small format: 4-byte header + 12 bytes per handler = 16 bytes
        assert_eq!(result.len(), 16);

        // First byte should be 0x01 (EHTable, small format)
        assert_eq!(result[0], 0x01);

        // Second byte should be section size (16)
        assert_eq!(result[1], 16);
    }

    #[test]
    fn test_encode_exception_handlers_fat_format() {
        let handlers = vec![ExceptionHandler {
            flags: ExceptionHandlerFlags::EXCEPTION,
            try_offset: 0x10000, // Forces fat format (> 16 bits)
            try_length: 10,
            handler_offset: 20,
            handler_length: 5,
            handler: None,
            filter_offset: 0,
        }];

        let result = encode_exception_handlers(&handlers).unwrap();

        // Should use fat format: 4-byte header + 24 bytes per handler = 28 bytes,
        // but aligned to 4-byte boundary = 32 bytes
        assert_eq!(result.len(), 32);

        // First byte should be 0x41 (EHTable | FatFormat)
        assert_eq!(result[0], 0x41);
    }

    #[test]
    fn test_encode_exception_handlers_filter() {
        let handlers = vec![ExceptionHandler {
            flags: ExceptionHandlerFlags::FILTER,
            try_offset: 0,
            try_length: 10,
            handler_offset: 20,
            handler_length: 5,
            handler: None,
            filter_offset: 15,
        }];

        let result = encode_exception_handlers(&handlers).unwrap();

        // Should successfully encode filter handler
        assert_eq!(result.len(), 16); // Small format
        assert_eq!(result[0], 0x01); // Small format flag
    }

    // Tests for ExceptionHandler accessor methods (MTH-L008)

    #[test]
    fn test_exception_handler_get_filter_offset() {
        // FILTER handler should return Some
        let filter_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::FILTER,
            try_offset: 0,
            try_length: 10,
            handler_offset: 20,
            handler_length: 5,
            handler: None,
            filter_offset: 15,
        };
        assert_eq!(filter_handler.get_filter_offset(), Some(15));

        // Non-FILTER handlers should return None
        let finally_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::FINALLY,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0,
        };
        assert_eq!(finally_handler.get_filter_offset(), None);

        let exception_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::EXCEPTION,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0x01000001, // Type token
        };
        assert_eq!(exception_handler.get_filter_offset(), None);
    }

    #[test]
    fn test_exception_handler_get_class_token() {
        // EXCEPTION handler with non-zero token should return Some
        let unresolved_catch = ExceptionHandler {
            flags: ExceptionHandlerFlags::EXCEPTION,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0x01000001, // TypeRef token
        };
        assert_eq!(unresolved_catch.get_class_token(), Some(0x01000001));

        // EXCEPTION handler with zero token (resolved) should return None
        let resolved_catch = ExceptionHandler {
            flags: ExceptionHandlerFlags::EXCEPTION,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None, // Would have resolved type in real scenario
            filter_offset: 0,
        };
        assert_eq!(resolved_catch.get_class_token(), None);

        // Non-EXCEPTION handlers should return None
        let filter_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::FILTER,
            try_offset: 0,
            try_length: 10,
            handler_offset: 20,
            handler_length: 5,
            handler: None,
            filter_offset: 15,
        };
        assert_eq!(filter_handler.get_class_token(), None);
    }

    #[test]
    fn test_exception_handler_type_checks() {
        let catch_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::EXCEPTION,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0,
        };
        assert!(catch_handler.is_catch());
        assert!(!catch_handler.is_finally());
        assert!(!catch_handler.is_fault());
        assert!(!catch_handler.is_filter());

        let finally_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::FINALLY,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0,
        };
        assert!(!finally_handler.is_catch());
        assert!(finally_handler.is_finally());
        assert!(!finally_handler.is_fault());
        assert!(!finally_handler.is_filter());

        let fault_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::FAULT,
            try_offset: 0,
            try_length: 10,
            handler_offset: 10,
            handler_length: 5,
            handler: None,
            filter_offset: 0,
        };
        assert!(!fault_handler.is_catch());
        assert!(!fault_handler.is_finally());
        assert!(fault_handler.is_fault());
        assert!(!fault_handler.is_filter());

        let filter_handler = ExceptionHandler {
            flags: ExceptionHandlerFlags::FILTER,
            try_offset: 0,
            try_length: 10,
            handler_offset: 20,
            handler_length: 5,
            handler: None,
            filter_offset: 15,
        };
        assert!(!filter_handler.is_catch());
        assert!(!filter_handler.is_finally());
        assert!(!filter_handler.is_fault());
        assert!(filter_handler.is_filter());
    }
}