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
//! 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;

/// 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> {
        if data.is_empty() {
            return Err(malformed_error!("Provided data for body parsing is empty"));
        }

        let first_byte = read_le::<u8>(data)?;
        match MethodBodyFlags::from_bits_truncate(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(),
                })
            }
            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::from_bits_truncate(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();
                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::from_bits_truncate(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;
                            if method_data_section_size < 4
                                || data.len() < (cursor + method_data_section_size as usize)
                            {
                                break;
                            }

                            let handler_count = (method_data_section_size - 4) / 24;
                            if handler_count as usize > MAX_EXCEPTION_HANDLERS {
                                return Err(malformed_error!(
                                    "Method has too many exception handlers: {} (max: {})",
                                    handler_count,
                                    MAX_EXCEPTION_HANDLERS
                                ));
                            }

                            cursor += 4;

                            for handler_idx in 0..handler_count {
                                let flags_u32 = read_le_at::<u32>(data, &mut cursor)?;
                                if flags_u32 > 0xFFFF {
                                    return Err(malformed_error!(
                                        "Exception handler {} has invalid flags with upper bits set: 0x{:08X}",
                                        handler_idx,
                                        flags_u32
                                    ));
                                }
                                #[allow(clippy::cast_possible_truncation)]
                                let flags =
                                    ExceptionHandlerFlags::from_bits_truncate(flags_u32 as u16);

                                exception_handlers.push(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,
                                });
                            }
                        } else {
                            let method_data_section_size =
                                u32::from(read_le::<u8>(&data[cursor + 1..])?);
                            if method_data_section_size < 4
                                || data.len() < (cursor + method_data_section_size as usize)
                            {
                                break;
                            }

                            let handler_count = (method_data_section_size - 4) / 12;
                            if handler_count as usize > MAX_EXCEPTION_HANDLERS {
                                return Err(malformed_error!(
                                    "Method has too many exception handlers: {} (max: {})",
                                    handler_count,
                                    MAX_EXCEPTION_HANDLERS
                                ));
                            }

                            cursor += 4;
                            for _ in 0..handler_count {
                                exception_handlers.push(ExceptionHandler {
                                    flags: ExceptionHandlerFlags::from_bits_truncate(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 !method_data_section_flags.contains(SectionFlags::MORE_SECTS) {
                            break;
                        }
                    }
                }

                for (index, handler) in exception_handlers.iter().enumerate() {
                    validate_exception_handler_bounds(handler, size_code, index)?;
                }

                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,
                })
            }
            _ => 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);
    }
}