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
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
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! FieldMarshalBuilder for creating P/Invoke marshaling specifications.
//!
//! This module provides [`crate::metadata::tables::fieldmarshal::FieldMarshalBuilder`] for creating FieldMarshal table entries
//! with a fluent API. Field marshaling defines how managed types are converted to and
//! from native types during P/Invoke calls, COM interop, and platform invoke scenarios,
//! enabling seamless interoperability between managed and unmanaged code.

use crate::{
    cilassembly::{ChangeRefRc, CilAssembly},
    metadata::{
        marshalling::{encode_marshalling_descriptor, MarshallingInfo, NativeType, NATIVE_TYPE},
        tables::{CodedIndex, CodedIndexType, FieldMarshalRaw, TableDataOwned, TableId},
        token::Token,
    },
    Error, Result,
};

/// Builder for creating FieldMarshal metadata entries.
///
/// `FieldMarshalBuilder` provides a fluent API for creating FieldMarshal table entries
/// with validation and automatic blob management. Field marshaling defines the conversion
/// rules between managed and native types for fields and parameters during interop
/// scenarios including P/Invoke calls, COM interop, and platform invoke operations.
///
/// # Marshaling Model
///
/// .NET marshaling follows a structured pattern:
/// - **Parent Entity**: The field or parameter that requires marshaling
/// - **Native Type**: How the managed type appears in native code
/// - **Conversion Rules**: Automatic conversion behavior during calls
/// - **Memory Management**: Responsibility for allocation and cleanup
///
/// # Coded Index Types
///
/// Field marshaling uses the `HasFieldMarshal` coded index to specify targets:
/// - **Field**: Marshaling for struct fields and class fields
/// - **Param**: Marshaling for method parameters and return values
///
/// # Marshaling Scenarios and Types
///
/// Different native types serve various interop scenarios:
/// - **Primitive Types**: Direct mapping for integers, floats, and booleans
/// - **String Types**: Character encoding and memory management (ANSI, Unicode)
/// - **Array Types**: Element type specification and size management
/// - **Pointer Types**: Memory layout and dereferencing behavior
/// - **Interface Types**: COM interface marshaling and reference counting
/// - **Custom Types**: User-defined marshaling with custom marshalers
///
/// # Marshaling Descriptors
///
/// Marshaling information is stored as binary descriptors in the blob heap:
/// - **Simple Types**: Single byte indicating native type (e.g., NATIVE_TYPE_I4)
/// - **Complex Types**: Multi-byte descriptors with parameters (arrays, strings)
/// - **Custom Marshalers**: Full type name and initialization parameters
/// - **Array Descriptors**: Element type, dimensions, and size specifications
///
/// # Examples
///
/// ```rust,no_run
/// # use dotscope::prelude::*;
/// # use std::path::Path;
/// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
/// let mut assembly = CilAssembly::new(view);
///
/// // Marshal a parameter as a null-terminated Unicode string
/// let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal); // String parameter
/// let unicode_string_descriptor = vec![NATIVE_TYPE::LPWSTR]; // Simple descriptor
///
/// let string_marshal = FieldMarshalBuilder::new()
///     .parent(param_ref)
///     .native_type(&unicode_string_descriptor)
///     .build(&mut assembly)?;
///
/// // Marshal a field as a fixed-size ANSI character array
/// let field_ref = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal); // Character array field
/// let fixed_array_descriptor = vec![
///     NATIVE_TYPE::ARRAY,
///     0x04, // Array element type (I1 - signed byte)
///     0x20, 0x00, 0x00, 0x00, // Array size (32 elements, little-endian)
/// ];
///
/// let array_marshal = FieldMarshalBuilder::new()
///     .parent(field_ref)
///     .native_type(&fixed_array_descriptor)
///     .build(&mut assembly)?;
///
/// // Marshal a parameter as a COM interface pointer
/// let interface_param = CodedIndex::new(TableId::Param, 2, CodedIndexType::HasFieldMarshal); // Interface parameter
/// let interface_descriptor = vec![NATIVE_TYPE::INTERFACE]; // COM interface
///
/// let interface_marshal = FieldMarshalBuilder::new()
///     .parent(interface_param)
///     .native_type(&interface_descriptor)
///     .build(&mut assembly)?;
///
/// // Marshal a return value as a platform-dependent integer
/// let return_param = CodedIndex::new(TableId::Param, 0, CodedIndexType::HasFieldMarshal); // Return value (sequence 0)
/// let platform_int_descriptor = vec![NATIVE_TYPE::INT]; // Platform IntPtr
///
/// let return_marshal = FieldMarshalBuilder::new()
///     .parent(return_param)
///     .native_type(&platform_int_descriptor)
///     .build(&mut assembly)?;
/// # Ok::<(), dotscope::Error>(())
/// ```
pub struct FieldMarshalBuilder {
    parent: Option<CodedIndex>,
    native_type: Option<Vec<u8>>,
    /// Stores encoding errors from `native_type_spec` or `marshalling_info` methods
    /// to be surfaced at `build()` time.
    encoding_error: Option<Error>,
}

impl Default for FieldMarshalBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl FieldMarshalBuilder {
    /// Creates a new FieldMarshalBuilder.
    ///
    /// # Returns
    ///
    /// A new [`crate::metadata::tables::fieldmarshal::FieldMarshalBuilder`] instance ready for configuration.
    #[must_use]
    pub fn new() -> Self {
        Self {
            parent: None,
            native_type: None,
            encoding_error: None,
        }
    }

    /// Sets the parent field or parameter that requires marshaling.
    ///
    /// The parent must be a valid `HasFieldMarshal` coded index that references
    /// either a field definition or parameter definition. This establishes which
    /// entity will have marshaling behavior applied during interop operations.
    ///
    /// Valid parent types include:
    /// - `Field` - Marshaling for struct fields in P/Invoke scenarios
    /// - `Param` - Marshaling for method parameters and return values
    ///
    /// Marshaling scope considerations:
    /// - **Field marshaling**: Applied when the containing struct crosses managed/native boundary
    /// - **Parameter marshaling**: Applied during each method call that crosses boundaries
    /// - **Return marshaling**: Applied to return values from native methods
    /// - **Array marshaling**: Applied to array elements and overall array structure
    ///
    /// # Arguments
    ///
    /// * `parent` - A `HasFieldMarshal` coded index pointing to the target field or parameter
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn parent(mut self, parent: CodedIndex) -> Self {
        self.parent = Some(parent);
        self
    }

    /// Sets the native type marshaling descriptor.
    ///
    /// The native type descriptor defines how the managed type should be represented
    /// and converted in native code. This binary descriptor is stored in the blob heap
    /// and follows .NET's marshaling specification format.
    ///
    /// Descriptor format varies by complexity:
    /// - **Simple types**: Single byte (e.g., `[NATIVE_TYPE::I4]` for 32-bit integer)
    /// - **String types**: May include encoding and length parameters
    /// - **Array types**: Include element type, dimensions, and size information
    /// - **Custom types**: Include full type names and initialization parameters
    ///
    /// Common descriptor patterns:
    /// - **Primitive**: `[NATIVE_TYPE::I4]` - 32-bit signed integer
    /// - **Unicode String**: `[NATIVE_TYPE_LPWSTR]` - Null-terminated wide string
    /// - **ANSI String**: `[NATIVE_TYPE_LPSTR]` - Null-terminated ANSI string
    /// - **Fixed Array**: `[NATIVE_TYPE_BYVALARRAY, element_type, size...]` - In-place array
    /// - **Interface**: `[NATIVE_TYPE_INTERFACE]` - COM interface pointer
    ///
    /// # Arguments
    ///
    /// * `native_type` - The binary marshaling descriptor specifying conversion behavior
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn native_type(mut self, native_type: &[u8]) -> Self {
        self.native_type = Some(native_type.to_vec());
        self
    }

    /// Sets a simple native type marshaling descriptor.
    ///
    /// This is a convenience method for common marshaling scenarios that require
    /// only a single native type identifier without additional parameters.
    ///
    /// # Arguments
    ///
    /// * `type_id` - The native type identifier from the NativeType constants
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn simple_native_type(mut self, type_id: u8) -> Self {
        self.native_type = Some(vec![type_id]);
        self
    }

    /// Sets Unicode string marshaling (LPWSTR).
    ///
    /// This convenience method configures marshaling for Unicode string parameters
    /// and fields, using null-terminated wide character representation.
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn unicode_string(self) -> Self {
        self.simple_native_type(NATIVE_TYPE::LPWSTR)
    }

    /// Sets ANSI string marshaling (LPSTR).
    ///
    /// This convenience method configures marshaling for ANSI string parameters
    /// and fields, using null-terminated single-byte character representation.
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn ansi_string(self) -> Self {
        self.simple_native_type(NATIVE_TYPE::LPSTR)
    }

    /// Sets fixed-size array marshaling.
    ///
    /// This convenience method configures marshaling for fixed-size arrays with
    /// specified element type and count. The array is marshaled in-place within
    /// the containing structure.
    ///
    /// # Arguments
    ///
    /// * `element_type` - The native type of array elements
    /// * `size` - The number of elements in the array
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn fixed_array(mut self, element_type: u8, size: u32) -> Self {
        let mut descriptor = vec![NATIVE_TYPE::ARRAY, element_type];
        descriptor.extend_from_slice(&size.to_le_bytes());
        self.native_type = Some(descriptor);
        self
    }

    /// Sets COM interface marshaling.
    ///
    /// This convenience method configures marshaling for COM interface pointers,
    /// enabling proper reference counting and interface negotiation.
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn com_interface(self) -> Self {
        self.simple_native_type(NATIVE_TYPE::INTERFACE)
    }

    /// Sets marshaling using a high-level NativeType specification.
    ///
    /// This method provides a type-safe way to configure marshaling using the
    /// structured `NativeType` enum rather than raw binary descriptors. It automatically
    /// encodes the native type specification to the correct binary format.
    ///
    /// # Arguments
    ///
    /// * `native_type` - The native type specification to marshal to
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    ///
    /// # Note
    ///
    /// If encoding fails, the error is stored and will be returned when `build()` is called.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::marshalling::NativeType;
    /// use dotscope::metadata::tables::FieldMarshalBuilder;
    ///
    /// // Unicode string with size parameter
    /// let marshal = FieldMarshalBuilder::new()
    ///     .parent(param_ref)
    ///     .native_type_spec(NativeType::LPWStr { size_param_index: Some(2) })
    ///     .build(&mut assembly)?;
    ///
    /// // Array of 32-bit integers
    /// let array_marshal = FieldMarshalBuilder::new()
    ///     .parent(field_ref)
    ///     .native_type_spec(NativeType::Array {
    ///         element_type: Box::new(NativeType::I4),
    ///         num_param: Some(1),
    ///         num_element: Some(10),
    ///     })
    ///     .build(&mut assembly)?;
    /// ```
    #[must_use]
    pub fn native_type_spec(mut self, native_type: NativeType) -> Self {
        let info = MarshallingInfo {
            primary_type: native_type,
            additional_types: vec![],
        };

        match encode_marshalling_descriptor(&info) {
            Ok(descriptor) => self.native_type = Some(descriptor),
            Err(e) => self.encoding_error = Some(e),
        }

        self
    }

    /// Sets marshaling using a complete marshalling descriptor.
    ///
    /// This method allows specifying complex marshalling scenarios with primary
    /// and additional types. This is useful for advanced marshalling cases that
    /// require multiple type specifications.
    ///
    /// # Arguments
    ///
    /// * `info` - The complete marshalling descriptor with primary and additional types
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    ///
    /// # Note
    ///
    /// If encoding fails, the error is stored and will be returned when `build()` is called.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use dotscope::metadata::marshalling::{NativeType, MarshallingInfo};
    /// use dotscope::metadata::tables::FieldMarshalBuilder;
    ///
    /// let complex_info = MarshallingInfo {
    ///     primary_type: NativeType::CustomMarshaler {
    ///         guid: "12345678-1234-5678-9ABC-DEF012345678".to_string(),
    ///         native_type_name: "NativeArray".to_string(),
    ///         cookie: "size=dynamic".to_string(),
    ///         type_reference: "MyAssembly.ArrayMarshaler".to_string(),
    ///     },
    ///     additional_types: vec![NativeType::I4], // Element type hint
    /// };
    ///
    /// let marshal = FieldMarshalBuilder::new()
    ///     .parent(param_ref)
    ///     .marshalling_info(complex_info)
    ///     .build(&mut assembly)?;
    /// ```
    #[must_use]
    pub fn marshalling_info(mut self, info: &MarshallingInfo) -> Self {
        match encode_marshalling_descriptor(info) {
            Ok(descriptor) => self.native_type = Some(descriptor),
            Err(e) => self.encoding_error = Some(e),
        }

        self
    }

    /// Sets marshaling for a pointer to a specific native type.
    ///
    /// This convenience method configures marshaling for pointer types with
    /// optional target type specification.
    ///
    /// # Arguments
    ///
    /// * `ref_type` - Optional type that the pointer references
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn pointer(self, ref_type: Option<NativeType>) -> Self {
        let ptr_type = NativeType::Ptr {
            ref_type: ref_type.map(Box::new),
        };
        self.native_type_spec(ptr_type)
    }

    /// Sets marshaling for a variable-length array.
    ///
    /// This convenience method configures marshaling for arrays with runtime
    /// size determination through parameter references.
    ///
    /// # Arguments
    ///
    /// * `element_type` - The type of array elements
    /// * `size_param` - Optional parameter index for array size
    /// * `element_count` - Optional fixed element count
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn variable_array(
        self,
        element_type: NativeType,
        size_param: Option<u32>,
        element_count: Option<u32>,
    ) -> Self {
        let array_type = NativeType::Array {
            element_type: Box::new(element_type),
            num_param: size_param,
            num_element: element_count,
        };
        self.native_type_spec(array_type)
    }

    /// Sets marshaling for a fixed-size array.
    ///
    /// This convenience method configures marshaling for arrays with compile-time
    /// known size embedded directly in structures.
    ///
    /// # Arguments
    ///
    /// * `element_type` - Optional type of array elements
    /// * `size` - Number of elements in the array
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn fixed_array_typed(self, element_type: Option<NativeType>, size: u32) -> Self {
        let array_type = NativeType::FixedArray {
            element_type: element_type.map(Box::new),
            size,
        };
        self.native_type_spec(array_type)
    }

    /// Sets marshaling for a native structure.
    ///
    /// This convenience method configures marshaling for native structures with
    /// optional packing and size specifications.
    ///
    /// # Arguments
    ///
    /// * `packing_size` - Optional structure packing alignment in bytes
    /// * `class_size` - Optional total structure size in bytes
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn native_struct(self, packing_size: Option<u8>, class_size: Option<u32>) -> Self {
        let struct_type = NativeType::Struct {
            packing_size,
            class_size,
        };
        self.native_type_spec(struct_type)
    }

    /// Sets marshaling for a COM safe array.
    ///
    /// This convenience method configures marshaling for COM safe arrays with
    /// variant type specification for element types.
    ///
    /// # Arguments
    ///
    /// * `variant_type` - VARIANT type constant for array elements
    /// * `user_defined_name` - Optional user-defined type name
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn safe_array(self, variant_type: u16, user_defined_name: Option<String>) -> Self {
        let array_type = NativeType::SafeArray {
            variant_type,
            user_defined_name,
        };
        self.native_type_spec(array_type)
    }

    /// Sets marshaling for a custom marshaler.
    ///
    /// This convenience method configures marshaling using a user-defined custom
    /// marshaler with GUID identification and initialization parameters.
    ///
    /// # Arguments
    ///
    /// * `guid` - GUID identifying the custom marshaler
    /// * `native_type_name` - Native type name for the marshaler
    /// * `cookie` - Cookie string passed to the marshaler for initialization
    /// * `type_reference` - Full type name of the custom marshaler class
    ///
    /// # Returns
    ///
    /// Self for method chaining.
    #[must_use]
    pub fn custom_marshaler(
        self,
        guid: &str,
        native_type_name: &str,
        cookie: &str,
        type_reference: &str,
    ) -> Self {
        let marshaler_type = NativeType::CustomMarshaler {
            guid: guid.to_string(),
            native_type_name: native_type_name.to_string(),
            cookie: cookie.to_string(),
            type_reference: type_reference.to_string(),
        };
        self.native_type_spec(marshaler_type)
    }

    /// Builds the field marshal entry and adds it to the assembly.
    ///
    /// This method validates all required fields are set, adds the marshaling
    /// descriptor to the blob heap, creates the raw field marshal structure,
    /// and adds it to the FieldMarshal table with proper token generation.
    ///
    /// # Arguments
    ///
    /// * `assembly` - The assembly being modified
    ///
    /// # Returns
    ///
    /// A [`crate::metadata::token::Token`] representing the newly created field marshal entry, or an error if
    /// validation fails or required fields are missing.
    ///
    /// # Errors
    ///
    /// - Returns error if encoding failed during `native_type_spec` or `marshalling_info`
    /// - Returns error if parent is not set
    /// - Returns error if native_type is not set or empty
    /// - Returns error if parent is not a valid HasFieldMarshal coded index
    /// - Returns error if blob operations fail
    /// - Returns error if table operations fail
    pub fn build(self, assembly: &mut CilAssembly) -> Result<ChangeRefRc> {
        if let Some(encoding_error) = self.encoding_error {
            return Err(encoding_error);
        }

        let parent = self
            .parent
            .ok_or_else(|| Error::ModificationInvalid("Marshal parent is required".to_string()))?;

        let native_type = self.native_type.ok_or_else(|| {
            Error::ModificationInvalid("Native type descriptor is required".to_string())
        })?;

        if native_type.is_empty() {
            return Err(Error::ModificationInvalid(
                "Native type descriptor cannot be empty".to_string(),
            ));
        }

        let valid_parent_tables = CodedIndexType::HasFieldMarshal.tables();
        if !valid_parent_tables.contains(&parent.tag) {
            return Err(Error::ModificationInvalid(format!(
                "Parent must be a HasFieldMarshal coded index (Field/Param), got {:?}",
                parent.tag
            )));
        }

        // Add native type descriptor to blob heap
        let native_type_index = assembly.blob_add(&native_type)?.placeholder();

        let rid = assembly.next_rid(TableId::FieldMarshal)?;

        let token = Token::from_parts(TableId::FieldMarshal, rid);

        let field_marshal_raw = FieldMarshalRaw {
            rid,
            token,
            offset: 0, // Will be set during binary generation
            parent,
            native_type: native_type_index,
        };

        assembly.table_row_add(
            TableId::FieldMarshal,
            TableDataOwned::FieldMarshal(field_marshal_raw),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        cilassembly::{ChangeRefKind, CilAssembly},
        metadata::cilassemblyview::CilAssemblyView,
    };
    use std::path::PathBuf;

    #[test]
    fn test_field_marshal_builder_basic() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Create a basic field marshal entry
            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal); // Parameter target
            let marshal_descriptor = vec![NATIVE_TYPE::I4]; // Simple integer marshaling

            let marshal_ref = FieldMarshalBuilder::new()
                .parent(param_ref)
                .native_type(&marshal_descriptor)
                .build(&mut assembly)
                .unwrap();

            // Verify ref is created correctly
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_different_parents() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let marshal_descriptor = vec![NATIVE_TYPE::I4];

            // Test Field parent
            let field_parent = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal);
            let field_marshal_ref = FieldMarshalBuilder::new()
                .parent(field_parent)
                .native_type(&marshal_descriptor)
                .build(&mut assembly)
                .unwrap();

            // Test Param parent
            let param_parent = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);
            let param_marshal_ref = FieldMarshalBuilder::new()
                .parent(param_parent)
                .native_type(&marshal_descriptor)
                .build(&mut assembly)
                .unwrap();

            // Both should succeed with correct kind
            assert_eq!(
                field_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                param_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert!(!std::sync::Arc::ptr_eq(
                &field_marshal_ref,
                &param_marshal_ref
            ));
        }
    }

    #[test]
    fn test_field_marshal_builder_different_native_types() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Test various native types
            let param_refs: Vec<_> = (1..=8)
                .map(|i| CodedIndex::new(TableId::Param, i, CodedIndexType::HasFieldMarshal))
                .collect();

            // Simple integer types
            let int_marshal_ref = FieldMarshalBuilder::new()
                .parent(param_refs[0].clone())
                .simple_native_type(NATIVE_TYPE::I4)
                .build(&mut assembly)
                .unwrap();

            // Unicode string
            let unicode_marshal_ref = FieldMarshalBuilder::new()
                .parent(param_refs[1].clone())
                .unicode_string()
                .build(&mut assembly)
                .unwrap();

            // ANSI string
            let ansi_marshal_ref = FieldMarshalBuilder::new()
                .parent(param_refs[2].clone())
                .ansi_string()
                .build(&mut assembly)
                .unwrap();

            // Fixed array
            let array_marshal_ref = FieldMarshalBuilder::new()
                .parent(param_refs[3].clone())
                .fixed_array(NATIVE_TYPE::I1, 32) // 32-byte array
                .build(&mut assembly)
                .unwrap();

            // COM interface
            let interface_marshal_ref = FieldMarshalBuilder::new()
                .parent(param_refs[4].clone())
                .com_interface()
                .build(&mut assembly)
                .unwrap();

            // All should succeed with FieldMarshal table kind
            assert_eq!(
                int_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                unicode_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                ansi_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                array_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                interface_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );

            // All should be different references
            let refs = [
                &int_marshal_ref,
                &unicode_marshal_ref,
                &ansi_marshal_ref,
                &array_marshal_ref,
                &interface_marshal_ref,
            ];
            for i in 0..refs.len() {
                for j in i + 1..refs.len() {
                    assert!(!std::sync::Arc::ptr_eq(refs[i], refs[j]));
                }
            }
        }
    }

    #[test]
    fn test_field_marshal_builder_complex_descriptors() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let field_ref = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal);

            // Complex array descriptor with multiple parameters
            let complex_array_descriptor = vec![
                NATIVE_TYPE::ARRAY,
                NATIVE_TYPE::I4, // Element type
                0x02,            // Array rank
                0x10,
                0x00,
                0x00,
                0x00, // Size parameter (16 elements)
                0x00,
                0x00,
                0x00,
                0x00, // Lower bound
            ];

            let marshal_ref = FieldMarshalBuilder::new()
                .parent(field_ref)
                .native_type(&complex_array_descriptor)
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_missing_parent() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let marshal_descriptor = vec![NATIVE_TYPE::I4];

            let result = FieldMarshalBuilder::new()
                .native_type(&marshal_descriptor)
                // Missing parent
                .build(&mut assembly);

            // Should fail because parent is required
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_field_marshal_builder_missing_native_type() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);

            let result = FieldMarshalBuilder::new()
                .parent(param_ref)
                // Missing native_type
                .build(&mut assembly);

            // Should fail because native type is required
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_field_marshal_builder_empty_native_type() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);
            let empty_descriptor = vec![]; // Empty descriptor

            let result = FieldMarshalBuilder::new()
                .parent(param_ref)
                .native_type(&empty_descriptor)
                .build(&mut assembly);

            // Should fail because native type cannot be empty
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_field_marshal_builder_invalid_parent_type() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Use a table type that's not valid for HasFieldMarshal
            let invalid_parent =
                CodedIndex::new(TableId::TypeDef, 1, CodedIndexType::HasFieldMarshal); // TypeDef not in HasFieldMarshal
            let marshal_descriptor = vec![NATIVE_TYPE::I4];

            let result = FieldMarshalBuilder::new()
                .parent(invalid_parent)
                .native_type(&marshal_descriptor)
                .build(&mut assembly);

            // Should fail because parent type is not valid for HasFieldMarshal
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_field_marshal_builder_all_primitive_types() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Test all primitive native types
            let primitive_types = [
                NATIVE_TYPE::BOOLEAN,
                NATIVE_TYPE::I1,
                NATIVE_TYPE::U1,
                NATIVE_TYPE::I2,
                NATIVE_TYPE::U2,
                NATIVE_TYPE::I4,
                NATIVE_TYPE::U4,
                NATIVE_TYPE::I8,
                NATIVE_TYPE::U8,
                NATIVE_TYPE::R4,
                NATIVE_TYPE::R8,
                NATIVE_TYPE::INT,
                NATIVE_TYPE::UINT,
            ];

            for (i, &native_type) in primitive_types.iter().enumerate() {
                let param_ref = CodedIndex::new(
                    TableId::Param,
                    (i + 1) as u32,
                    CodedIndexType::HasFieldMarshal,
                );

                let marshal_ref = FieldMarshalBuilder::new()
                    .parent(param_ref)
                    .simple_native_type(native_type)
                    .build(&mut assembly)
                    .unwrap();

                // All should succeed
                assert_eq!(
                    marshal_ref.kind(),
                    ChangeRefKind::TableRow(TableId::FieldMarshal)
                );
            }
        }
    }

    #[test]
    fn test_field_marshal_builder_string_types() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Test string marshaling types
            let param1 = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);
            let param2 = CodedIndex::new(TableId::Param, 2, CodedIndexType::HasFieldMarshal);
            let param3 = CodedIndex::new(TableId::Param, 3, CodedIndexType::HasFieldMarshal);
            let param4 = CodedIndex::new(TableId::Param, 4, CodedIndexType::HasFieldMarshal);

            // LPSTR (ANSI string)
            let ansi_marshal_ref = FieldMarshalBuilder::new()
                .parent(param1)
                .simple_native_type(NATIVE_TYPE::LPSTR)
                .build(&mut assembly)
                .unwrap();

            // LPWSTR (Unicode string)
            let unicode_marshal_ref = FieldMarshalBuilder::new()
                .parent(param2)
                .simple_native_type(NATIVE_TYPE::LPWSTR)
                .build(&mut assembly)
                .unwrap();

            // BSTR (COM string)
            let bstr_marshal_ref = FieldMarshalBuilder::new()
                .parent(param3)
                .simple_native_type(NATIVE_TYPE::BSTR)
                .build(&mut assembly)
                .unwrap();

            // BYVALSTR (fixed-length string)
            let byval_marshal_ref = FieldMarshalBuilder::new()
                .parent(param4)
                .simple_native_type(NATIVE_TYPE::BYVALSTR)
                .build(&mut assembly)
                .unwrap();

            // All should succeed
            assert_eq!(
                ansi_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                unicode_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                bstr_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                byval_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_realistic_pinvoke() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Realistic P/Invoke scenario: Win32 API function
            // BOOL CreateDirectory(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes);

            // Parameter 1: LPCWSTR (Unicode string path)
            let path_param = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);
            let path_marshal_ref = FieldMarshalBuilder::new()
                .parent(path_param)
                .unicode_string() // LPCWSTR
                .build(&mut assembly)
                .unwrap();

            // Parameter 2: LPSECURITY_ATTRIBUTES (structure pointer)
            let security_param =
                CodedIndex::new(TableId::Param, 2, CodedIndexType::HasFieldMarshal);
            let security_marshal_ref = FieldMarshalBuilder::new()
                .parent(security_param)
                .simple_native_type(NATIVE_TYPE::PTR) // Pointer to struct
                .build(&mut assembly)
                .unwrap();

            // Return value: BOOL (32-bit integer)
            let return_param = CodedIndex::new(TableId::Param, 0, CodedIndexType::HasFieldMarshal); // Return value
            let return_marshal_ref = FieldMarshalBuilder::new()
                .parent(return_param)
                .simple_native_type(NATIVE_TYPE::I4) // 32-bit bool
                .build(&mut assembly)
                .unwrap();

            // All should succeed
            assert_eq!(
                path_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                security_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                return_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );

            // All should be different references
            assert!(!std::sync::Arc::ptr_eq(
                &path_marshal_ref,
                &security_marshal_ref
            ));
            assert!(!std::sync::Arc::ptr_eq(
                &path_marshal_ref,
                &return_marshal_ref
            ));
            assert!(!std::sync::Arc::ptr_eq(
                &security_marshal_ref,
                &return_marshal_ref
            ));
        }
    }

    #[test]
    fn test_field_marshal_builder_struct_fields() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            // Realistic struct marshaling: POINT structure
            // struct POINT { LONG x; LONG y; };

            let x_field = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal);
            let y_field = CodedIndex::new(TableId::Field, 2, CodedIndexType::HasFieldMarshal);

            // X coordinate as 32-bit signed integer
            let x_marshal_ref = FieldMarshalBuilder::new()
                .parent(x_field)
                .simple_native_type(NATIVE_TYPE::I4)
                .build(&mut assembly)
                .unwrap();

            // Y coordinate as 32-bit signed integer
            let y_marshal_ref = FieldMarshalBuilder::new()
                .parent(y_field)
                .simple_native_type(NATIVE_TYPE::I4)
                .build(&mut assembly)
                .unwrap();

            // Both should succeed
            assert_eq!(
                x_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert_eq!(
                y_marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
            assert!(!std::sync::Arc::ptr_eq(&x_marshal_ref, &y_marshal_ref));
        }
    }

    #[test]
    fn test_field_marshal_builder_high_level_native_type_spec() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);

            // Test high-level NativeType specification
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(param_ref)
                .native_type_spec(NativeType::LPWStr {
                    size_param_index: Some(2),
                })
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_variable_array() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let field_ref = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal);

            // Test variable array marshaling
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(field_ref)
                .variable_array(NativeType::I4, Some(1), Some(10))
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_fixed_array_typed() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let field_ref = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal);

            // Test fixed array marshaling with type specification
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(field_ref)
                .fixed_array_typed(Some(NativeType::Boolean), 64)
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_native_struct() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let field_ref = CodedIndex::new(TableId::Field, 1, CodedIndexType::HasFieldMarshal);

            // Test native struct marshaling
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(field_ref)
                .native_struct(Some(4), Some(128))
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_pointer() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);

            // Test pointer marshaling
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(param_ref)
                .pointer(Some(NativeType::I4))
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_custom_marshaler() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);

            // Test custom marshaler
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(param_ref)
                .custom_marshaler(
                    "12345678-1234-5678-9ABC-DEF012345678",
                    "NativeType",
                    "cookie_data",
                    "MyAssembly.CustomMarshaler",
                )
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_safe_array() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);

            // Test safe array marshaling
            let marshal_ref = FieldMarshalBuilder::new()
                .parent(param_ref)
                .safe_array(crate::metadata::marshalling::VARIANT_TYPE::I4, None)
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }

    #[test]
    fn test_field_marshal_builder_marshalling_info() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(view) = CilAssemblyView::from_path(&path) {
            let mut assembly = CilAssembly::new(view);

            let param_ref = CodedIndex::new(TableId::Param, 1, CodedIndexType::HasFieldMarshal);

            // Test complex marshalling info
            let info = MarshallingInfo {
                primary_type: NativeType::LPStr {
                    size_param_index: Some(1),
                },
                additional_types: vec![NativeType::Boolean],
            };

            let marshal_ref = FieldMarshalBuilder::new()
                .parent(param_ref)
                .marshalling_info(&info)
                .build(&mut assembly)
                .unwrap();

            // Should succeed
            assert_eq!(
                marshal_ref.kind(),
                ChangeRefKind::TableRow(TableId::FieldMarshal)
            );
        }
    }
}