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
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
//! Representation and parsing of CIL method bodies in .NET assemblies.
//!
//! This module provides types and logic for decoding method headers, CIL bytecode, local variable
//! signatures, and exception handling regions from .NET metadata. Supports both tiny and fat method
//! headers as specified by ECMA-335.
//!
//! # Method Body Format
//!
//! .NET methods can have two types of headers:
//!
//! ## Tiny Headers
//! - **Size**: 1 byte
//! - **Code Size**: Up to 63 bytes
//! - **Max Stack**: Fixed at 8
//! - **Local Variables**: None allowed
//! - **Exception Handling**: Not supported
//! - **Use Case**: Simple methods with minimal bytecode
//!
//! ## Fat Headers
//! - **Size**: 12 bytes minimum
//! - **Code Size**: Up to 4GB
//! - **Max Stack**: Configurable up to 65535
//! - **Local Variables**: Supported with signature token
//! - **Exception Handling**: Full support with multiple handlers
//! - **Use Case**: Complex methods with significant bytecode
//!
//! # Exception Handling
//!
//! Fat method headers can include exception handling sections with:
//! - **Try Blocks**: Protected code regions
//! - **Handler Types**: Exception, finally, fault, and filter handlers
//! - **Multiple Handlers**: Support for nested and sequential exception handling
//! - **Section Formats**: Both tiny (12-byte) and fat (24-byte) handler entries
//!
//! # Thread Safety
//!
//! All types in this module are thread-safe:
//! - **`MethodBody`**: Immutable after construction
//! - **Parsing**: No shared state during parsing operations
//! - **Exception Handlers**: Read-only data structures
//!
//! # Usage Patterns
//!
//! ## Basic Method Information
//! ```rust,ignore
//! use dotscope::metadata::method::MethodBody;
//!
//! let method_data = /* ... method body bytes ... */;
//! let body = MethodBody::from(method_data)?;
//!
//! println!("Method has {} bytes of IL code", body.size_code);
//! println!("Header type: {}", if body.is_fat { "Fat" } else { "Tiny" });
//! ```
//!
//! ## Local Variable Analysis
//! ```rust,ignore
//! if body.local_var_sig_token != 0 {
//!     println!("Method has local variables (signature token: 0x{:08X})",
//!              body.local_var_sig_token);
//!     if body.is_init_local {
//!         println!("Local variables are zero-initialized");
//!     }
//! }
//! ```
//!
//! ## Exception Handler Processing
//! ```rust,ignore
//! if body.is_exception_data {
//!     println!("Method has {} exception handlers", body.exception_handlers.len());
//!     for (i, handler) in body.exception_handlers.iter().enumerate() {
//!         println!("Handler {}: try=[{:#x}..{:#x}], handler=[{:#x}..{:#x}]",
//!                  i, handler.try_offset,
//!                  handler.try_offset + handler.try_length,
//!                  handler.handler_offset,
//!                  handler.handler_offset + handler.handler_length);
//!     }
//! }
//! ```
//!
//! # Examples
//!
//! ```rust,no_run
//! use dotscope::{CilObject, metadata::method::MethodBody};
//!
//! let assembly = CilObject::from_path("tests/samples/WindowsBase.dll")?;
//! let methods = assembly.methods();
//!
//! for entry in methods.iter() {
//!     let (token, method) = (entry.key(), entry.value());
//!     if let Some(body) = method.body.get() {
//!         println!("Method {}: {} bytes of IL code", method.name, body.size_code);
//!         println!("  Max stack: {}", body.max_stack);
//!         println!("  Header type: {}", if body.is_fat { "Fat" } else { "Tiny" });
//!         if body.local_var_sig_token != 0 {
//!             println!("  Has local variables (token: 0x{:08X})", body.local_var_sig_token);
//!         }
//!     }
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # References
//! - ECMA-335 6th Edition, Partition II, Section 25.4 - Method Header Format
//! - ECMA-335 6th Edition, Partition II, Section 25.4.6 - Exception Handling Data Sections

use std::io::Write;

use crate::{
    metadata::method::{
        encode_exception_handlers, ExceptionHandler, ExceptionHandlerFlags, MethodBodyFlags,
        SectionFlags,
    },
    utils::{read_le, read_le_at},
    Result,
};

/// Maximum number of exception handlers allowed per method.
/// Real-world methods typically have < 20 handlers.
const MAX_EXCEPTION_HANDLERS: usize = 1024;

/// Controls how exception handler validation is performed during parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EhValidationMode {
    /// Strict: return error on any invalid handler (used by `from()`)
    Strict,
    /// Filter: log warning and skip invalid handlers (used by `from_lenient()`)
    Filter,
    /// Raw: no validation, keep all parsed handlers (used by `from_raw()` for detection)
    Raw,
}

/// Validates that an exception handler's offsets and lengths are within the method body bounds.
///
/// # Arguments
/// * `handler` - The exception handler to validate
/// * `code_size` - The size of the method's IL code in bytes
/// * `handler_index` - The index of the handler (for error messages)
///
/// # Errors
/// Returns an error if any offset or region extends beyond the method body.
fn validate_exception_handler_bounds(
    handler: &ExceptionHandler,
    code_size: u32,
    handler_index: usize,
) -> Result<()> {
    let try_end = handler
        .try_offset
        .checked_add(handler.try_length)
        .ok_or_else(|| {
            malformed_error!(
                "Exception handler {} try region overflow: offset {} + length {} overflows u32",
                handler_index,
                handler.try_offset,
                handler.try_length
            )
        })?;

    if try_end > code_size {
        return Err(malformed_error!(
            "Exception handler {} try region [{}, {}) exceeds method code size {}",
            handler_index,
            handler.try_offset,
            try_end,
            code_size
        ));
    }

    let handler_end = handler
        .handler_offset
        .checked_add(handler.handler_length)
        .ok_or_else(|| {
            malformed_error!(
                "Exception handler {} handler region overflow: offset {} + length {} overflows u32",
                handler_index,
                handler.handler_offset,
                handler.handler_length
            )
        })?;

    if handler_end > code_size {
        return Err(malformed_error!(
            "Exception handler {} handler region [{}, {}) exceeds method code size {}",
            handler_index,
            handler.handler_offset,
            handler_end,
            code_size
        ));
    }

    if handler.flags.contains(ExceptionHandlerFlags::FILTER) && handler.filter_offset >= code_size {
        return Err(malformed_error!(
            "Exception handler {} filter offset {} exceeds method code size {}",
            handler_index,
            handler.filter_offset,
            code_size
        ));
    }

    Ok(())
}

/// Describes one method that has been compiled to CIL bytecode.
///
/// The `MethodBody` struct represents the parsed body of a .NET method, including header information,
/// code size, stack requirements, local variable signature, and exception handling regions.
///
/// # Header Format Detection
///
/// The structure automatically detects whether the method uses a tiny or fat header format
/// based on the first byte(s) of the method body data:
/// - **Tiny Format**: Single byte header for methods with ≤63 bytes of code
/// - **Fat Format**: 12-byte header for complex methods with extensive metadata
///
/// # Field Organization
///
/// ## Size Information
/// - [`Self::size_code`]: Length of the actual CIL instructions in bytes
/// - [`Self::size_header`]: Length of the method header (1 for tiny, 12+ for fat)
///
/// ## Stack and Variables
/// - [`Self::max_stack`]: Maximum operand stack depth during execution
/// - [`Self::local_var_sig_token`]: Metadata token for local variable type signature
/// - [`Self::is_init_local`]: Whether local variables are zero-initialized
///
/// ## Format and Features
/// - [`Self::is_fat`]: Whether this method uses the fat header format
/// - [`Self::is_exception_data`]: Whether exception handling data is present
/// - [`Self::exception_handlers`]: Collection of exception handling regions
///
/// # Memory Layout
///
/// ```text
/// Tiny Header (1 byte):
/// ┌─────────────────────────────────────┐
/// │ Size(6) │ Reserved(2) │ Format(2)   │
/// └─────────────────────────────────────┘
///
/// Fat Header (12 bytes):
/// ┌─────────────────────────────────────┐
/// │ Flags(12) │ Size(4) │ Format(2)     │  (bytes 0-1)
/// ├─────────────────────────────────────┤
/// │ MaxStack (16 bits)                  │  (bytes 2-3)
/// ├─────────────────────────────────────┤
/// │ CodeSize (32 bits)                  │  (bytes 4-7)
/// ├─────────────────────────────────────┤
/// │ LocalVarSigTok (32 bits)            │  (bytes 8-11)
/// └─────────────────────────────────────┘
/// ```
///
/// # Thread Safety
///
/// `MethodBody` is fully thread-safe:
/// - All fields are immutable after construction
/// - No interior mutability or shared state
/// - Safe to share across threads without synchronization
pub struct MethodBody {
    /// Size of the method code (length of all CIL instructions, excluding the header) in bytes
    pub size_code: usize,
    /// Size of the method header in bytes (1 for tiny format, 12+ for fat format)
    pub size_header: usize,
    /// Metadata token for a signature describing the layout of local variables (0 = no locals)
    pub local_var_sig_token: u32,
    /// Maximum number of items on the operand stack during method execution
    pub max_stack: usize,
    /// Flag indicating the method header format (false = tiny, true = fat)
    pub is_fat: bool,
    /// Flag indicating whether to zero-initialize all local variables before method execution
    pub is_init_local: bool,
    /// Flag indicating whether this method has exception handling data sections
    pub is_exception_data: bool,
    /// Collection of exception handlers for this method (empty if no exception handling)
    pub exception_handlers: Vec<ExceptionHandler>,
}

impl MethodBody {
    /// Create a `MethodBody` object from a sequence of bytes.
    ///
    /// Parses a complete .NET method body including header, CIL instructions, and optional
    /// exception handling sections. Automatically detects and handles both tiny and fat
    /// header formats according to ECMA-335 specifications.
    ///
    /// # Arguments
    ///
    /// * `data` - The byte slice containing the complete method body data, starting with
    ///   the method header and including all CIL instructions and exception handling sections
    ///
    /// # Returns
    ///
    /// * [`Ok`]([`MethodBody`]) - Successfully parsed method body with all metadata
    /// * [`Err`]([`crate::Error`]) - Parsing failed due to invalid format, insufficient data, or corruption
    ///
    /// # Errors
    ///
    /// This method returns an error in the following cases:
    /// - **Empty Data**: The provided byte slice is empty
    /// - **Invalid Format**: Header format bits don't match tiny or fat patterns
    /// - **Insufficient Data**: Not enough bytes for the declared header or code size
    /// - **Malformed Sections**: Exception handling sections have invalid structure
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::method::MethodBody;
    ///
    /// let method_data = &[0x16, 0x00, 0x2A]; // Simple method: ldarg.0, ret
    /// let body = MethodBody::from(method_data)?;
    ///
    /// assert!(!body.is_fat);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn from(data: &[u8]) -> Result<MethodBody> {
        let (body, _) = Self::parse(data, EhValidationMode::Strict)?;
        Ok(body)
    }

    /// Create a `MethodBody` from bytes, filtering out invalid exception handlers.
    ///
    /// This is useful for parsing method bodies with malformed exception handlers
    /// (e.g., injected by BitMono's AntiDecompiler) where the handler offsets are
    /// garbage but the method header and IL code are valid. Invalid handlers are
    /// logged and skipped; only valid handlers are kept.
    ///
    /// # Arguments
    ///
    /// * `data` - The byte slice containing the complete method body data
    ///
    /// # Returns
    ///
    /// * [`Ok`]`((MethodBody, usize))` - Successfully parsed method body with only valid
    ///   exception handlers, and the count of invalid handlers that were filtered out
    /// * [`Err`]([`crate::Error`]) - Parsing failed due to invalid header format or insufficient data
    pub fn from_lenient(data: &[u8]) -> Result<(MethodBody, usize)> {
        let (body, filtered) = Self::parse(data, EhValidationMode::Filter)?;
        if filtered > 0 {
            log::warn!(
                "Filtered {filtered} invalid exception handler(s), {} valid handler(s) kept",
                body.exception_handlers.len()
            );
        }
        Ok((body, filtered))
    }

    /// Parse without any EH validation. Returns all parsed handlers including garbage.
    ///
    /// Used for obfuscation detection where we need to see raw handler data to
    /// identify injected garbage exception handlers.
    ///
    /// # Arguments
    ///
    /// * `data` - The byte slice containing the complete method body data
    ///
    /// # Returns
    ///
    /// * [`Ok`]([`MethodBody`]) - Successfully parsed method body with all handlers (unvalidated)
    /// * [`Err`]([`crate::Error`]) - Parsing failed due to invalid header format or insufficient data
    pub fn from_raw(data: &[u8]) -> Result<MethodBody> {
        let (body, _) = Self::parse(data, EhValidationMode::Raw)?;
        Ok(body)
    }

    /// Checks the declared handler count against MAX_EXCEPTION_HANDLERS.
    ///
    /// - **Strict**: returns an error
    /// - **Filter**: no-op (declared count is irrelevant; valid-handler cap is checked per push)
    /// - **Raw**: logs a warning and signals the caller to break
    ///
    /// Returns `Ok(true)` to continue parsing, `Ok(false)` to break (skip this section).
    fn check_handler_count(handler_count: u32, eh_mode: EhValidationMode) -> Result<bool> {
        if eh_mode == EhValidationMode::Filter || (handler_count as usize) <= MAX_EXCEPTION_HANDLERS
        {
            return Ok(true);
        }

        match eh_mode {
            EhValidationMode::Strict => Err(malformed_error!(
                "Method has too many exception handlers: {} (max: {})",
                handler_count,
                MAX_EXCEPTION_HANDLERS
            )),
            _ => {
                log::warn!(
                    "Method has too many exception handlers: {} (max: {}), skipping",
                    handler_count,
                    MAX_EXCEPTION_HANDLERS
                );
                Ok(false)
            }
        }
    }

    /// Validates and pushes a parsed exception handler according to the validation mode.
    ///
    /// - **Strict**: validates bounds and returns error on failure
    /// - **Filter**: validates bounds; valid handlers are pushed, invalid ones increment
    ///   `filtered_count` silently (caller logs the total)
    /// - **Raw**: pushes unconditionally
    ///
    /// Returns `Ok(true)` to continue iterating, `Ok(false)` to stop (max valid handlers reached).
    fn push_handler(
        handler: ExceptionHandler,
        handler_idx: usize,
        code_size: u32,
        eh_mode: EhValidationMode,
        handlers: &mut Vec<ExceptionHandler>,
        filtered_count: &mut usize,
    ) -> Result<bool> {
        match eh_mode {
            EhValidationMode::Strict => {
                validate_exception_handler_bounds(&handler, code_size, handler_idx)?;
                handlers.push(handler);
            }
            EhValidationMode::Filter => {
                if validate_exception_handler_bounds(&handler, code_size, handler_idx).is_ok() {
                    handlers.push(handler);
                    if handlers.len() >= MAX_EXCEPTION_HANDLERS {
                        return Ok(false);
                    }
                } else {
                    *filtered_count += 1;
                }
            }
            EhValidationMode::Raw => {
                handlers.push(handler);
            }
        }
        Ok(true)
    }

    /// Internal parsing logic shared by `from()`, `from_lenient()`, and `from_raw()`.
    ///
    /// Returns the parsed body and the number of filtered (invalid) exception handlers.
    /// In Strict mode, this count is always 0 (errors abort before counting).
    /// In Raw mode, this count is always 0 (nothing is filtered).
    fn parse(data: &[u8], eh_mode: EhValidationMode) -> Result<(MethodBody, usize)> {
        if data.is_empty() {
            return Err(malformed_error!("Provided data for body parsing is empty"));
        }

        let first_byte = read_le::<u8>(data)?;
        match MethodBodyFlags::new(u16::from(first_byte & 0b_00000011_u8)) {
            MethodBodyFlags::TINY_FORMAT => {
                let size_code = (first_byte >> 2) as usize;
                if size_code + 1 > data.len() {
                    return Err(out_of_bounds_error!());
                }

                Ok((
                    MethodBody {
                        size_code,
                        size_header: 1,
                        local_var_sig_token: 0,
                        max_stack: 8,
                        is_fat: false,
                        is_init_local: false,
                        is_exception_data: false,
                        exception_handlers: Vec::new(),
                    },
                    0,
                ))
            }
            MethodBodyFlags::FAT_FORMAT => {
                if data.len() < 12 {
                    return Err(out_of_bounds_error!());
                }

                let first_duo = read_le::<u16>(data)?;

                let size_header = (first_duo >> 12) * 4;
                let size_code = read_le::<u32>(&data[4..])?;
                if data.len() < (size_code as usize + size_header as usize) {
                    return Err(out_of_bounds_error!());
                }

                let local_var_sig_token = read_le::<u32>(&data[8..])?;
                let flags_header = MethodBodyFlags::new(first_duo & 0b_0000111111111111_u16);
                let max_stack = read_le::<u16>(&data[2..])? as usize;

                let is_init_local = flags_header.contains(MethodBodyFlags::INIT_LOCALS);

                // Exception Handling -> II.25.4.6
                // The extra sections currently can only contain exception handling data
                let mut exception_handlers = Vec::new();
                let mut filtered_count: usize = 0;
                if flags_header.contains(MethodBodyFlags::MORE_SECTS) {
                    // Set cursor to the end of the header + body, to process exception tables
                    let mut cursor = size_header as usize + size_code as usize;
                    cursor = (cursor + 3) & !3;

                    while data.len() > (cursor + 4) {
                        let method_data_section_flags =
                            SectionFlags::new(read_le::<u8>(&data[cursor..])?);
                        if !method_data_section_flags.contains(SectionFlags::EHTABLE) {
                            break;
                        }

                        if method_data_section_flags.contains(SectionFlags::FAT_FORMAT) {
                            let method_data_section_size =
                                read_le::<u32>(&data[cursor + 1..])? & 0x00FF_FFFF;

                            // ECMA-335 says DataSize includes the 4-byte section header,
                            // but some tools emit DataSize without the header. Using
                            // DataSize/24 handles both cases via integer division
                            // (matches Mono runtime behavior in metadata.c:parse_section_data).
                            let handler_count = method_data_section_size / 24;
                            let needed = 4 + handler_count as usize * 24;
                            if handler_count == 0 || data.len() < cursor + needed {
                                break;
                            }
                            if !Self::check_handler_count(handler_count, eh_mode)? {
                                break;
                            }

                            cursor += 4;

                            for handler_idx in 0..handler_count {
                                let flags_u32 = read_le_at::<u32>(data, &mut cursor)?;
                                if flags_u32 > 0xFFFF && eh_mode == EhValidationMode::Strict {
                                    return Err(malformed_error!(
                                        "Exception handler {} has invalid flags with upper bits set: 0x{:08X}",
                                        handler_idx,
                                        flags_u32
                                    ));
                                }
                                // In Filter/Raw mode, truncate to u16 and let push_handler
                                // validate via bounds checking — garbage flags typically
                                // accompany garbage offsets that will be rejected there.
                                #[allow(clippy::cast_possible_truncation)]
                                let flags = ExceptionHandlerFlags::new(flags_u32 as u16);

                                let handler = ExceptionHandler {
                                    flags,
                                    try_offset: read_le_at::<u32>(data, &mut cursor)?,
                                    try_length: read_le_at::<u32>(data, &mut cursor)?,
                                    handler_offset: read_le_at::<u32>(data, &mut cursor)?,
                                    handler_length: read_le_at::<u32>(data, &mut cursor)?,
                                    filter_offset: read_le_at::<u32>(data, &mut cursor)?,
                                    handler: None,
                                };

                                if !Self::push_handler(
                                    handler,
                                    handler_idx as usize,
                                    size_code,
                                    eh_mode,
                                    &mut exception_handlers,
                                    &mut filtered_count,
                                )? {
                                    break;
                                }
                            }
                        } else {
                            let method_data_section_size =
                                u32::from(read_le::<u8>(&data[cursor + 1..])?);

                            // ECMA-335 says DataSize includes the 4-byte section header,
                            // but some tools (e.g. AsmResolver used by BitMono) emit
                            // DataSize without the header. Using DataSize/12 handles both
                            // cases via integer division (matches Mono runtime behavior
                            // in metadata.c:parse_section_data).
                            let handler_count = method_data_section_size / 12;
                            let needed = 4 + handler_count as usize * 12;
                            if handler_count == 0 || data.len() < cursor + needed {
                                break;
                            }
                            if !Self::check_handler_count(handler_count, eh_mode)? {
                                break;
                            }

                            cursor += 4;
                            for handler_idx in 0..handler_count {
                                let handler = ExceptionHandler {
                                    flags: ExceptionHandlerFlags::new(read_le_at::<u16>(
                                        data,
                                        &mut cursor,
                                    )?),
                                    try_offset: u32::from(read_le_at::<u16>(data, &mut cursor)?),
                                    try_length: u32::from(read_le_at::<u8>(data, &mut cursor)?),
                                    handler_offset: u32::from(read_le_at::<u16>(
                                        data,
                                        &mut cursor,
                                    )?),
                                    handler_length: u32::from(read_le_at::<u8>(data, &mut cursor)?),
                                    filter_offset: read_le_at::<u32>(data, &mut cursor)?,
                                    handler: None,
                                };

                                if !Self::push_handler(
                                    handler,
                                    handler_idx as usize,
                                    size_code,
                                    eh_mode,
                                    &mut exception_handlers,
                                    &mut filtered_count,
                                )? {
                                    break;
                                }
                            }
                        }

                        if !method_data_section_flags.contains(SectionFlags::MORE_SECTS) {
                            break;
                        }
                    }
                }

                Ok((
                    MethodBody {
                        size_code: size_code as usize,
                        size_header: size_header as usize,
                        local_var_sig_token,
                        max_stack,
                        is_fat: true,
                        is_init_local,
                        is_exception_data: !exception_handlers.is_empty(),
                        exception_handlers,
                    },
                    filtered_count,
                ))
            }
            _ => Err(malformed_error!(
                "MethodHeader is neither FAT nor TINY - {}",
                first_byte
            )),
        }
    }

    /// Get the total serialized size including header, code, and exception handlers.
    ///
    /// This calculates the complete size of the method body as it appears in the
    /// assembly file, including:
    /// - Method header (1 byte for tiny, 12 bytes for fat)
    /// - IL code bytes
    /// - 4-byte alignment padding (for fat format with exception handlers)
    /// - Exception handler sections
    ///
    /// # Returns
    ///
    /// The total serialized size in bytes.
    #[must_use]
    pub fn size(&self) -> usize {
        let base_size = self.size_header + self.size_code;

        if self.exception_handlers.is_empty() {
            return base_size;
        }

        // Exception handlers require 4-byte alignment after the code
        let aligned_base = (base_size + 3) & !3;

        // Determine if we need fat or small exception handler format
        let needs_fat_format = self.exception_handlers.iter().any(|h| {
            h.try_offset > 0xFFFF
                || h.try_length > 0xFF
                || h.handler_offset > 0xFFFF
                || h.handler_length > 0xFF
        });

        let section_size = if needs_fat_format {
            // Fat format: 4-byte header + 24 bytes per handler
            4 + (self.exception_handlers.len() * 24)
        } else {
            // Small format: 4-byte header + 12 bytes per handler
            4 + (self.exception_handlers.len() * 12)
        };

        aligned_base + section_size
    }

    /// Writes the method body to a writer.
    ///
    /// Serializes the method header (tiny or fat format), IL code, and exception handlers
    /// directly to the provided writer. This avoids intermediate buffers for efficient
    /// streaming output.
    ///
    /// # Arguments
    ///
    /// * `writer` - Any type implementing [`std::io::Write`]
    /// * `il_code` - The IL bytecode for the method
    ///
    /// # Returns
    ///
    /// The total number of bytes written (header + code + exception handlers + padding).
    ///
    /// # Format Selection
    ///
    /// The format is automatically determined based on method characteristics:
    /// - **Tiny Format**: Used when code size ≤ 63 bytes, no local variables, and no exceptions
    /// - **Fat Format**: Used for all other methods
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::metadata::method::MethodBody;
    ///
    /// # fn example() -> dotscope::Result<()> {
    /// let body = MethodBody {
    ///     size_code: 2,
    ///     size_header: 1,
    ///     local_var_sig_token: 0,
    ///     max_stack: 8,
    ///     is_fat: false,
    ///     is_init_local: false,
    ///     is_exception_data: false,
    ///     exception_handlers: vec![],
    /// };
    ///
    /// let il_code = vec![0x17, 0x2A]; // ldc.i4.1, ret
    /// let mut buffer = Vec::new();
    /// let bytes_written = body.write_to(&mut buffer, &il_code)?;
    ///
    /// assert_eq!(bytes_written, 3); // 1-byte header + 2-byte code
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the writer fails or if the method body
    /// parameters are invalid (e.g., code size exceeds limits).
    pub fn write_to<W: Write>(&self, writer: &mut W, il_code: &[u8]) -> Result<u64> {
        let code_size = il_code.len();
        let has_exceptions = !self.exception_handlers.is_empty();

        // Determine format: use tiny if possible
        let use_tiny = code_size <= 63
            && self.max_stack <= 8
            && self.local_var_sig_token == 0
            && !has_exceptions;

        let mut bytes_written: u64 = 0;

        if use_tiny {
            // Tiny format: single byte header
            // Bits 7-2: code size (6 bits)
            // Bits 1-0: format (0x02 for tiny)
            let code_size_u8 = u8::try_from(code_size).map_err(|_| {
                malformed_error!("Code size {} exceeds tiny format limit", code_size)
            })?;
            let header_byte = (code_size_u8 << 2) | 0x02;
            writer.write_all(&[header_byte])?;
            bytes_written += 1;
        } else {
            // Fat format: 12-byte header
            let code_size_u32 = u32::try_from(code_size)
                .map_err(|_| malformed_error!("Code size {} exceeds u32 range", code_size))?;
            let max_stack_u16 = u16::try_from(self.max_stack)
                .map_err(|_| malformed_error!("Max stack {} exceeds u16 range", self.max_stack))?;

            // Flags layout (ECMA-335 II.25.4.4):
            // Bits 0-1: Format (0x03 for fat)
            // Bit 3: CorILMethod_MoreSects (0x08)
            // Bit 4: CorILMethod_InitLocals (0x10)
            // Bits 12-15: Size in dwords (3 for fat header = 12 bytes)
            let mut flags: u16 = 0x3003; // Size (3 << 12) | FAT_FORMAT (0x03)
            if has_exceptions {
                flags |= 0x0008; // MORE_SECTS
            }
            if self.is_init_local {
                flags |= 0x0010; // INIT_LOCALS
            }

            // Write header fields
            writer.write_all(&flags.to_le_bytes())?;
            writer.write_all(&max_stack_u16.to_le_bytes())?;
            writer.write_all(&code_size_u32.to_le_bytes())?;
            writer.write_all(&self.local_var_sig_token.to_le_bytes())?;
            bytes_written += 12;
        }

        // Write IL code
        writer.write_all(il_code)?;
        bytes_written += code_size as u64;

        // Write exception handlers if present
        if has_exceptions {
            // Align to 4-byte boundary
            let padding = (4 - (bytes_written % 4)) % 4;
            if padding > 0 {
                writer.write_all(&vec![0u8; padding as usize])?;
                bytes_written += padding;
            }

            // Use the shared exception handler encoding
            let exception_bytes = encode_exception_handlers(&self.exception_handlers)?;
            writer.write_all(&exception_bytes)?;
            bytes_written += exception_bytes.len() as u64;
        }

        Ok(bytes_written)
    }
}

#[cfg(test)]
mod tests {
    use crate::metadata::method::ExceptionHandlerFlags;

    use super::*;

    #[test]
    fn tiny() {
        /*
        WindowsBase.dll

        HeaderRVA:          0xF7358
        HeaderOffset:       0xF7358
        MaxStack:           8
        LocalVarSigToken:   0
        Locals:             0
        ExceptionHandlers:  0
        Instructions:       4
        CodeSize:           17
        Size:               18
        Flags:
            - InitLocals
        */

        let data = include_bytes!("../../../tests/samples/WB_METHOD_TINY_0600032D.bin");

        let method_header = MethodBody::from(data).unwrap();

        assert!(!method_header.is_fat);
        assert!(!method_header.is_exception_data);
        assert!(!method_header.is_init_local);
        assert_eq!(method_header.max_stack, 8);
        assert_eq!(method_header.size_code, 18);
        assert_eq!(method_header.size_header, 1);
        assert_eq!(method_header.size(), 19);
        assert_eq!(method_header.local_var_sig_token, 0);
    }

    #[test]
    fn fat() {
        /*
        WindowsBase.dll

        HeaderRVA:          0xF77D8
        HeaderOffset:       0xF77D8
        MaxStack:           5
        LocalVarSigToken:   0x11000059
        Locals:             4
        ExceptionHandlers:  0
        Instructions:       79
        CodeSize:           0x9B
        Flags:
            - InitLocals
        */

        let data = include_bytes!("../../../tests/samples/WB_METHOD_FAT_0600033E.bin");

        let method_header = MethodBody::from(data).unwrap();

        assert!(method_header.is_fat);
        assert!(!method_header.is_exception_data);
        assert!(method_header.is_init_local);
        assert_eq!(method_header.max_stack, 5);
        assert_eq!(method_header.size_code, 0x9B);
        assert_eq!(method_header.size_header, 12);
        assert_eq!(method_header.size(), 167);
        assert_eq!(method_header.local_var_sig_token, 0x11000059);
    }

    #[test]
    fn fat_exceptions_1() {
        /*
        WindowsBase.dll

        HeaderRVA:          0xF7898
        HeaderOffset:       0xF7898
        MaxStack:           1
        LocalVarSigToken:   0x11000003
        Locals:             1
        ExceptionHandlers:  1
        Instructions:       15
        CodeSize:           0x1C
        Flags:
            - InitLocals
        */

        let data = include_bytes!("../../../tests/samples/WB_METHOD_FAT_EXCEPTION_06000341.bin");

        let method_header = MethodBody::from(data).unwrap();

        assert!(method_header.is_fat);
        assert!(method_header.is_exception_data);
        assert!(method_header.is_init_local);
        assert_eq!(method_header.max_stack, 1);
        assert_eq!(method_header.size_code, 30);
        assert_eq!(method_header.size_header, 12);
        assert_eq!(method_header.size(), 60); // 44 (aligned base) + 16 (small exception section)
        assert_eq!(method_header.local_var_sig_token, 0x11000003);
        assert_eq!(method_header.exception_handlers.len(), 1);
        assert!(method_header.exception_handlers[0]
            .flags
            .contains(ExceptionHandlerFlags::EXCEPTION));
        assert_eq!(method_header.exception_handlers[0].try_offset, 0);
        assert_eq!(method_header.exception_handlers[0].try_length, 0xF);
        assert_eq!(method_header.exception_handlers[0].handler_offset, 0xF);
        assert_eq!(method_header.exception_handlers[0].handler_length, 0xD);
        assert_eq!(method_header.exception_handlers[0].filter_offset, 0x100003F);
    }

    #[test]
    fn fat_exceptions_tiny_section_2() {
        /*
        WindowsBase.dll

        HeaderRVA:          0xECC4C
        HeaderOffset:       0xECC4C
        MaxStack:           3
        LocalVarSigToken:   0x1100001A
        Locals:             2
        ExceptionHandlers:  1
        Instructions:       18
        CodeSize:           0x2D
        Flags:
            - InitLocals
        */

        let data = include_bytes!(
            "../../../tests/samples/WB_METHOD_FAT_EXCEPTION_N1_2LOCALS_060001AA.bin"
        );

        let method_header = MethodBody::from(data).unwrap();

        assert!(method_header.is_fat);
        assert!(method_header.is_exception_data);
        assert!(method_header.is_init_local);
        assert_eq!(method_header.max_stack, 3);
        assert_eq!(method_header.size_code, 0x2E);
        assert_eq!(method_header.size_header, 12);
        assert_eq!(method_header.size(), 76); // 60 (aligned base) + 16 (small exception section)
        assert_eq!(method_header.local_var_sig_token, 0x1100001A);
        assert_eq!(method_header.exception_handlers.len(), 1);
        assert!(method_header.exception_handlers[0]
            .flags
            .contains(ExceptionHandlerFlags::FINALLY));
        assert_eq!(method_header.exception_handlers[0].try_offset, 0x8);
        assert_eq!(method_header.exception_handlers[0].try_length, 0x1B);
        assert_eq!(method_header.exception_handlers[0].handler_offset, 0x23);
        assert_eq!(method_header.exception_handlers[0].handler_length, 0xA);
        assert_eq!(method_header.exception_handlers[0].filter_offset, 0);
    }

    #[test]
    fn fat_exceptions_fat_section_3() {
        /*
        WindowsBase.dll

        HeaderRVA:          0xF9839
        HeaderOffset:       0xF9839
        MaxStack:           5
        LocalVarSigToken:   0x11000070
        Locals:             10
        ExceptionHandlers:  2
        Instructions:       156
        CodeSize:           0x19F
        Flags:
            - InitLocals
        */

        let data = include_bytes!("../../../tests/samples/WB_METHOD_FAT_EXCEPTION_N2_06000421.bin");

        let method_header = MethodBody::from(data).unwrap();

        assert!(method_header.is_fat);
        assert!(method_header.is_exception_data);
        assert!(method_header.is_init_local);
        assert_eq!(method_header.max_stack, 5);
        assert_eq!(method_header.size_code, 0x19F);
        assert_eq!(method_header.size_header, 12);
        assert_eq!(method_header.size(), 480); // 428 (aligned base) + 52 (fat exception section with 2 handlers)
        assert_eq!(method_header.local_var_sig_token, 0x11000070);
        assert_eq!(method_header.exception_handlers.len(), 2);
        assert!(method_header.exception_handlers[0]
            .flags
            .contains(ExceptionHandlerFlags::FINALLY));
        assert_eq!(method_header.exception_handlers[0].try_offset, 0x145);
        assert_eq!(method_header.exception_handlers[0].try_length, 0x28);
        assert_eq!(method_header.exception_handlers[0].handler_offset, 0x16D);
        assert_eq!(method_header.exception_handlers[0].handler_length, 0xE);
        assert_eq!(method_header.exception_handlers[0].filter_offset, 0);
        assert!(method_header.exception_handlers[1]
            .flags
            .contains(ExceptionHandlerFlags::FINALLY));
        assert_eq!(method_header.exception_handlers[1].try_offset, 0x9);
        assert_eq!(method_header.exception_handlers[1].try_length, 0x18A);
        assert_eq!(method_header.exception_handlers[1].handler_offset, 0x193);
        assert_eq!(method_header.exception_handlers[1].handler_length, 0xA);
        assert_eq!(method_header.exception_handlers[1].filter_offset, 0);
    }

    #[test]
    fn fat_exceptions_multiple() {
        /*
        WindowsBase.dll

        HeaderRVA:          0x114140
        HeaderOffset:       0x114140
        MaxStack:           3
        LocalVarSigToken:   0x1100007C
        Locals:             2
        ExceptionHandlers:  2
        Instructions:       32
        CodeSize:           0x51
        Flags:
            - InitLocals
        */

        let data = include_bytes!("../../../tests/samples/WB_METHOD_FAT_EXCEPTION_N2_06000D54.bin");

        let method_header = MethodBody::from(data).unwrap();

        assert!(method_header.is_fat);
        assert!(method_header.is_exception_data);
        assert!(method_header.is_init_local);
        assert_eq!(method_header.max_stack, 3);
        assert_eq!(method_header.size_code, 81);
        assert_eq!(method_header.size_header, 12);
        assert_eq!(method_header.size(), 124); // 96 (aligned base) + 28 (small exception section with 2 handlers)
        assert_eq!(method_header.local_var_sig_token, 0x1100007C);

        assert_eq!(method_header.exception_handlers.len(), 2);
        assert!(method_header.exception_handlers[0]
            .flags
            .contains(ExceptionHandlerFlags::FINALLY));
        assert_eq!(method_header.exception_handlers[0].try_offset, 17);
        assert_eq!(method_header.exception_handlers[0].try_length, 48);
        assert_eq!(method_header.exception_handlers[0].handler_offset, 65);
        assert_eq!(method_header.exception_handlers[0].handler_length, 10);
        assert_eq!(method_header.exception_handlers[0].filter_offset, 0);

        assert!(method_header.exception_handlers[1]
            .flags
            .contains(ExceptionHandlerFlags::EXCEPTION));
        assert_eq!(method_header.exception_handlers[1].try_offset, 0);
        assert_eq!(method_header.exception_handlers[1].try_length, 77);
        assert_eq!(method_header.exception_handlers[1].handler_offset, 77);
        assert_eq!(method_header.exception_handlers[1].handler_length, 3);
        assert_eq!(method_header.exception_handlers[1].filter_offset, 0x100001D);
    }

    /// Helper: builds a fat method body with the given small-format EH clauses.
    /// Each clause is (flags_u16, try_offset_u16, try_length_u8, handler_offset_u16, handler_length_u8, filter_offset_u32).
    fn build_fat_body_with_small_eh(
        code_size: u32,
        clauses: &[(u16, u16, u8, u16, u8, u32)],
    ) -> Vec<u8> {
        let il_code = vec![0x00u8; code_size as usize];

        // Fat header: FAT_FORMAT | MORE_SECTS | INIT_LOCALS, size=3 dwords
        let flags: u16 = 0x3003 | 0x0008 | 0x0010;
        let max_stack: u16 = 8;
        let local_var_sig: u32 = 0;

        let mut data = Vec::new();
        data.extend_from_slice(&flags.to_le_bytes());
        data.extend_from_slice(&max_stack.to_le_bytes());
        data.extend_from_slice(&code_size.to_le_bytes());
        data.extend_from_slice(&local_var_sig.to_le_bytes());
        data.extend_from_slice(&il_code);

        // Align to 4 bytes
        let unaligned = 12 + code_size as usize;
        let aligned = (unaligned + 3) & !3;
        data.extend(std::iter::repeat_n(0x00, aligned - unaligned));

        // Small exception section header
        let section_size = (4 + clauses.len() * 12) as u8;
        data.push(0x01); // section flags: EHTABLE
        data.push(section_size);
        data.push(0x00); // padding
        data.push(0x00); // padding

        for &(flags, try_off, try_len, handler_off, handler_len, filter) in clauses {
            data.extend_from_slice(&flags.to_le_bytes());
            data.extend_from_slice(&try_off.to_le_bytes());
            data.push(try_len);
            data.extend_from_slice(&handler_off.to_le_bytes());
            data.push(handler_len);
            data.extend_from_slice(&filter.to_le_bytes());
        }

        data
    }

    #[test]
    fn from_lenient_filters_invalid_handlers() {
        // Build a fat method with 3 EH entries: 1 valid, 2 with out-of-bounds offsets.
        // Code size = 100 bytes
        let clauses = [
            // Valid handler: try=[0..10), handler=[10..20)
            (0x0000u16, 0u16, 10u8, 10u16, 10u8, 0x01000001u32),
            // Invalid: try_offset way beyond code
            (0x0000, 0xFFFF, 0xFF, 0xFFFF, 0xFF, 0x01000001),
            // Invalid: handler_offset beyond code
            (0x0000, 0, 5, 0xAAAA, 0xBB, 0x01000001),
        ];
        let data = build_fat_body_with_small_eh(100, &clauses);

        // Strict from() should fail
        assert!(MethodBody::from(&data).is_err());

        // Lenient should keep only the valid handler and report 2 filtered
        let (body, filtered) = MethodBody::from_lenient(&data).unwrap();
        assert!(body.is_fat);
        assert_eq!(body.size_code, 100);
        assert_eq!(body.exception_handlers.len(), 1);
        assert_eq!(filtered, 2);
        // The valid handler should be the one kept
        assert_eq!(body.exception_handlers[0].try_offset, 0);
        assert_eq!(body.exception_handlers[0].try_length, 10);
        assert_eq!(body.exception_handlers[0].handler_offset, 10);
        assert_eq!(body.exception_handlers[0].handler_length, 10);
    }

    #[test]
    fn from_raw_keeps_all_handlers() {
        // Same test data as above: 1 valid + 2 invalid handlers
        let clauses = [
            (0x0000u16, 0u16, 10u8, 10u16, 10u8, 0x01000001u32),
            (0x0000, 0xFFFF, 0xFF, 0xFFFF, 0xFF, 0x01000001),
            (0x0000, 0, 5, 0xAAAA, 0xBB, 0x01000001),
        ];
        let data = build_fat_body_with_small_eh(100, &clauses);

        // Raw should keep all 3 handlers
        let body = MethodBody::from_raw(&data).unwrap();
        assert_eq!(body.exception_handlers.len(), 3);
        // Verify the garbage handler is preserved
        assert_eq!(body.exception_handlers[1].try_offset, 0xFFFF);
    }

    #[test]
    fn from_strict_errors_on_max_exception_handlers() {
        // Build a method body with handler_count > MAX_EXCEPTION_HANDLERS (1024).
        // We use a fat EH section so we can declare a large handler count.
        let code_size: u32 = 100;
        let il_code = vec![0x00u8; code_size as usize];

        let flags: u16 = 0x3003 | 0x0008 | 0x0010;
        let max_stack: u16 = 8;
        let local_var_sig: u32 = 0;

        let mut data = Vec::new();
        data.extend_from_slice(&flags.to_le_bytes());
        data.extend_from_slice(&max_stack.to_le_bytes());
        data.extend_from_slice(&code_size.to_le_bytes());
        data.extend_from_slice(&local_var_sig.to_le_bytes());
        data.extend_from_slice(&il_code);

        // Align to 4 bytes
        let unaligned = 12 + code_size as usize;
        let aligned = (unaligned + 3) & !3;
        data.extend(std::iter::repeat_n(0x00, aligned - unaligned));

        // Fat exception section header
        let handler_count: u32 = 1025; // > MAX_EXCEPTION_HANDLERS
        let section_size: u32 = 4 + handler_count * 24;
        data.push(0x41); // section flags: EHTABLE | FAT_FORMAT
        let size_bytes = section_size.to_le_bytes();
        data.push(size_bytes[0]);
        data.push(size_bytes[1]);
        data.push(size_bytes[2]);

        // Write handler_count fat EH entries (24 bytes each, all zeros)
        for _ in 0..handler_count {
            data.extend_from_slice(&[0u8; 24]);
        }

        // Strict from() should error on too many handlers
        assert!(MethodBody::from(&data).is_err());
    }

    #[test]
    fn from_lenient_accepts_malformed_eh() {
        // Construct a fat method with a single exception handler whose
        // try region extends far beyond the code size (malformed).
        let clauses = [
            // Invalid: try_offset way beyond code
            (
                0x0000u16,
                0xFFFFu16,
                0xFFu8,
                0xFFFFu16,
                0xFFu8,
                0x01000001u32,
            ),
        ];
        let data = build_fat_body_with_small_eh(10, &clauses);

        // Strict from() should fail due to bad EH bounds
        assert!(MethodBody::from(&data).is_err());

        // Lenient from_lenient() should succeed, filtering out the invalid handler
        let (body, filtered) = MethodBody::from_lenient(&data).unwrap();
        assert!(body.is_fat);
        assert_eq!(body.size_code, 10);
        assert_eq!(filtered, 1);
        assert_eq!(body.exception_handlers.len(), 0);

        // Raw from_raw() should keep the handler
        let raw_body = MethodBody::from_raw(&data).unwrap();
        assert_eq!(raw_body.exception_handlers.len(), 1);
        assert_eq!(raw_body.exception_handlers[0].try_offset, 0xFFFF);
    }
}