forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStubHelpers.cs
More file actions
1303 lines (1078 loc) · 49.4 KB
/
StubHelpers.cs
File metadata and controls
1303 lines (1078 loc) · 49.4 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
namespace System.StubHelpers
{
internal static class AnsiCharMarshaler
{
// The length of the returned array is an approximation based on the length of the input string and the system
// character set. It is only guaranteed to be larger or equal to cbLength, don't depend on the exact value.
internal static unsafe byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength)
{
byte[] buffer = new byte[checked((str.Length + 1) * Marshal.SystemMaxDBCSCharSize)];
fixed (byte* bufferPtr = &buffer[0])
{
cbLength = Marshal.StringToAnsiString(str, bufferPtr, buffer.Length, fBestFit, fThrowOnUnmappableChar);
}
return buffer;
}
internal static unsafe byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar)
{
int cbAllocLength = (1 + 1) * Marshal.SystemMaxDBCSCharSize;
byte* bufferPtr = stackalloc byte[cbAllocLength];
int cbLength = Marshal.StringToAnsiString(managedChar.ToString(), bufferPtr, cbAllocLength, fBestFit, fThrowOnUnmappableChar);
Debug.Assert(cbLength > 0, "Zero bytes returned from DoAnsiConversion in AnsiCharMarshaler.ConvertToNative");
return bufferPtr[0];
}
internal static char ConvertToManaged(byte nativeChar)
{
var bytes = new ReadOnlySpan<byte>(in nativeChar);
string str = Encoding.Default.GetString(bytes);
return str[0];
}
} // class AnsiCharMarshaler
internal static class CSTRMarshaler
{
internal static unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
int nb;
byte* pbNativeBuffer = (byte*)pNativeBuffer;
if (pbNativeBuffer != null || Marshal.SystemMaxDBCSCharSize == 1)
{
// If we are marshaling into a stack buffer or we can accurately estimate the size of the required heap
// space, we will use a "1-pass" mode where we convert the string directly into the unmanaged buffer.
// + 1 for the null character from the user. + 1 for the null character we put in.
nb = checked((strManaged.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1);
bool didAlloc = false;
// Use the pre-allocated buffer (allocated by localloc IL instruction) if not NULL,
// otherwise fallback to AllocCoTaskMem
if (pbNativeBuffer == null)
{
pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb);
didAlloc = true;
}
try
{
nb = Marshal.StringToAnsiString(strManaged, pbNativeBuffer, nb,
bestFit: 0 != (flags & 0xFF), throwOnUnmappableChar: 0 != (flags >> 8));
}
catch (Exception) when (didAlloc)
{
Marshal.FreeCoTaskMem((IntPtr)pbNativeBuffer);
throw;
}
}
else
{
if (strManaged.Length == 0)
{
nb = 0;
pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(2);
}
else
{
// Otherwise we use a slower "2-pass" mode where we first marshal the string into an intermediate buffer
// (managed byte array) and then allocate exactly the right amount of unmanaged memory. This is to avoid
// wasting memory on systems with multibyte character sets where the buffer we end up with is often much
// smaller than the upper bound for the given managed string.
byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged,
fBestFit: 0 != (flags & 0xFF), fThrowOnUnmappableChar: 0 != (flags >> 8), out nb);
// + 1 for the null character from the user. + 1 for the null character we put in.
pbNativeBuffer = (byte*)Marshal.AllocCoTaskMem(nb + 2);
Buffer.Memmove(ref *pbNativeBuffer, ref MemoryMarshal.GetArrayDataReference(bytes), (nuint)nb);
}
}
pbNativeBuffer[nb] = 0x00;
pbNativeBuffer[nb + 1] = 0x00;
return (IntPtr)pbNativeBuffer;
}
internal static unsafe string? ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return null;
else
return new string((sbyte*)cstr);
}
internal static unsafe void ConvertFixedToNative(int flags, string strManaged, IntPtr pNativeBuffer, int length)
{
if (strManaged == null)
{
if (length > 0)
*(byte*)pNativeBuffer = 0;
return;
}
int numChars = strManaged.Length;
if (numChars >= length)
{
numChars = length - 1;
}
byte* buffer = (byte*)pNativeBuffer;
// Flags defined in ILFixedCSTRMarshaler::EmitConvertContentsCLRToNative(ILCodeStream* pslILEmit).
bool throwOnUnmappableChar = 0 != (flags >> 8);
bool bestFit = 0 != (flags & 0xFF);
Interop.BOOL defaultCharUsed = Interop.BOOL.FALSE;
int cbWritten;
fixed (char* pwzChar = strManaged)
{
#if TARGET_WINDOWS
cbWritten = Interop.Kernel32.WideCharToMultiByte(
Interop.Kernel32.CP_ACP,
bestFit ? 0 : Interop.Kernel32.WC_NO_BEST_FIT_CHARS,
pwzChar,
numChars,
buffer,
length,
null,
throwOnUnmappableChar ? &defaultCharUsed : null);
#else
cbWritten = Encoding.UTF8.GetBytes(pwzChar, numChars, buffer, length);
#endif
}
if (defaultCharUsed != Interop.BOOL.FALSE)
{
throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char);
}
if (cbWritten == (int)length)
{
cbWritten--;
}
buffer[cbWritten] = 0;
}
internal static unsafe string ConvertFixedToManaged(IntPtr cstr, int length)
{
int end = new ReadOnlySpan<byte>((byte*)cstr, length).IndexOf((byte)0);
if (end >= 0)
{
length = end;
}
return new string((sbyte*)cstr, 0, length);
}
} // class CSTRMarshaler
internal static class UTF8BufferMarshaler
{
internal static unsafe IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags)
{
if (null == sb)
{
return IntPtr.Zero;
}
// Convert to string first
string strManaged = sb.ToString();
// Get byte count
int nb = Encoding.UTF8.GetByteCount(strManaged);
// EmitConvertSpaceCLRToNative allocates memory
byte* pbNativeBuffer = (byte*)pNativeBuffer;
nb = strManaged.GetBytesFromEncoding(pbNativeBuffer, nb, Encoding.UTF8);
pbNativeBuffer[nb] = 0x0;
return (IntPtr)pbNativeBuffer;
}
internal static unsafe void ConvertToManaged(StringBuilder sb, IntPtr pNative)
{
if (pNative == IntPtr.Zero)
return;
byte* pBytes = (byte*)pNative;
int nbBytes = string.strlen(pBytes);
sb.ReplaceBufferUtf8Internal(new ReadOnlySpan<byte>(pBytes, nbBytes));
}
}
internal static class BSTRMarshaler
{
internal static unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
else
{
bool hasTrailByte = strManaged.TryGetTrailByte(out byte trailByte);
uint lengthInBytes = (uint)strManaged.Length * 2;
if (hasTrailByte)
{
// this is an odd-sized string with a trailing byte stored in its sync block
lengthInBytes++;
}
byte* ptrToFirstChar;
if (pNativeBuffer != IntPtr.Zero)
{
// If caller provided a buffer, construct the BSTR manually. The size
// of the buffer must be at least (lengthInBytes + 6) bytes.
#if DEBUG
uint length = *((uint*)pNativeBuffer);
Debug.Assert(length >= lengthInBytes + 6, "BSTR localloc'ed buffer is too small");
#endif
// set length
*((uint*)pNativeBuffer) = lengthInBytes;
ptrToFirstChar = (byte*)pNativeBuffer + 4;
}
else
{
// If not provided, allocate the buffer using Marshal.AllocBSTRByteLen so
// that odd-sized strings will be handled as well.
ptrToFirstChar = (byte*)Marshal.AllocBSTRByteLen(lengthInBytes);
}
// copy characters from the managed string
Buffer.Memmove(ref *(char*)ptrToFirstChar, ref strManaged.GetRawStringData(), (nuint)strManaged.Length + 1);
// copy the trail byte if present
if (hasTrailByte)
{
ptrToFirstChar[lengthInBytes - 1] = trailByte;
}
// return ptr to first character
return (IntPtr)ptrToFirstChar;
}
}
internal static unsafe string? ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
{
return null;
}
else
{
uint length = Marshal.SysStringByteLen(bstr);
// Intentionally checking the number of bytes not characters to match the behavior
// of ML marshalers. This prevents roundtripping of very large strings as the check
// in the managed->native direction is done on String length but considering that
// it's completely moot on 32-bit and not expected to be important on 64-bit either,
// the ability to catch random garbage in the BSTR's length field outweighs this
// restriction. If an ordinary null-terminated string is passed instead of a BSTR,
// chances are that the length field - possibly being unallocated memory - contains
// a heap fill pattern that will have the highest bit set, caught by the check.
StubHelpers.CheckStringLength(length);
string ret;
if (length == 1)
{
// In the empty string case, we need to use FastAllocateString rather than the
// String .ctor, since newing up a 0 sized string will always return String.Empty.
// When we marshal that out as a bstr, it can wind up getting modified which
// corrupts string.Empty.
ret = string.FastAllocateString(0);
}
else
{
ret = new string((char*)bstr, 0, (int)(length / 2));
}
if ((length & 1) == 1)
{
// odd-sized strings need to have the trailing byte saved in their sync block
ret.SetTrailByte(((byte*)bstr)[length - 1]);
}
return ret;
}
}
internal static void ClearNative(IntPtr pNative)
{
Marshal.FreeBSTR(pNative);
}
} // class BSTRMarshaler
internal static class VBByValStrMarshaler
{
internal static unsafe IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
byte* pNative;
cch = strManaged.Length;
// length field at negative offset + (# of characters incl. the terminator) * max ANSI char size
int nbytes = checked(sizeof(uint) + ((cch + 1) * Marshal.SystemMaxDBCSCharSize));
pNative = (byte*)Marshal.AllocCoTaskMem(nbytes);
int* pLength = (int*)pNative;
pNative += sizeof(uint);
if (0 == cch)
{
*pNative = 0;
*pLength = 0;
}
else
{
byte[] bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit, fThrowOnUnmappableChar, out int nbytesused);
Debug.Assert(nbytesused >= 0 && nbytesused < nbytes, "Insufficient buffer allocated in VBByValStrMarshaler.ConvertToNative");
Buffer.Memmove(ref *pNative, ref MemoryMarshal.GetArrayDataReference(bytes), (nuint)nbytesused);
pNative[nbytesused] = 0;
*pLength = nbytesused;
}
return new IntPtr(pNative);
}
internal static unsafe string? ConvertToManaged(IntPtr pNative, int cch)
{
if (IntPtr.Zero == pNative)
{
return null;
}
return new string((sbyte*)pNative, 0, cch);
}
internal static void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
{
Marshal.FreeCoTaskMem((IntPtr)(((long)pNative) - sizeof(uint)));
}
}
} // class VBByValStrMarshaler
internal static class AnsiBSTRMarshaler
{
internal static unsafe IntPtr ConvertToNative(int flags, string strManaged)
{
if (null == strManaged)
{
return IntPtr.Zero;
}
byte[]? bytes = null;
int nb = 0;
if (strManaged.Length > 0)
{
bytes = AnsiCharMarshaler.DoAnsiConversion(strManaged, 0 != (flags & 0xFF), 0 != (flags >> 8), out nb);
}
uint length = (uint)nb;
IntPtr bstr = Marshal.AllocBSTRByteLen(length);
if (bytes != null)
{
Buffer.Memmove(ref *(byte*)bstr, ref MemoryMarshal.GetArrayDataReference(bytes), length);
}
return bstr;
}
internal static unsafe string? ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
{
return null;
}
else
{
// We intentionally ignore the length field of the BSTR for back compat reasons.
// Unfortunately VB.NET uses Ansi BSTR marshaling when a string is passed ByRef
// and we cannot afford to break this common scenario.
return new string((sbyte*)bstr);
}
}
internal static void ClearNative(IntPtr pNative)
{
Marshal.FreeBSTR(pNative);
}
} // class AnsiBSTRMarshaler
internal static class FixedWSTRMarshaler
{
internal static unsafe void ConvertToNative(string? strManaged, IntPtr nativeHome, int length)
{
ReadOnlySpan<char> managed = strManaged;
Span<char> native = new Span<char>((char*)nativeHome, length);
int numChars = Math.Min(managed.Length, length - 1);
managed.Slice(0, numChars).CopyTo(native);
native[numChars] = '\0';
}
internal static unsafe string ConvertToManaged(IntPtr nativeHome, int length)
{
int end = new ReadOnlySpan<char>((char*)nativeHome, length).IndexOf('\0');
if (end >= 0)
{
length = end;
}
return new string((char*)nativeHome, 0, length);
}
} // class WSTRBufferMarshaler
#if FEATURE_COMINTEROP
internal static class ObjectMarshaler
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertToNative(object objSrc, IntPtr pDstVariant);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object ConvertToManaged(IntPtr pSrcVariant);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pVariant);
} // class ObjectMarshaler
#endif // FEATURE_COMINTEROP
internal sealed class HandleMarshaler
{
internal static unsafe IntPtr ConvertSafeHandleToNative(SafeHandle? handle, ref CleanupWorkListElement? cleanupWorkList)
{
if (Unsafe.IsNullRef(ref cleanupWorkList))
{
throw new InvalidOperationException(SR.Interop_Marshal_SafeHandle_InvalidOperation);
}
ArgumentNullException.ThrowIfNull(handle);
return StubHelpers.AddToCleanupList(ref cleanupWorkList, handle);
}
internal static unsafe void ThrowSafeHandleFieldChanged()
{
throw new NotSupportedException(SR.Interop_Marshal_CannotCreateSafeHandleField);
}
internal static unsafe void ThrowCriticalHandleFieldChanged()
{
throw new NotSupportedException(SR.Interop_Marshal_CannotCreateCriticalHandleField);
}
}
internal static class DateMarshaler
{
internal static double ConvertToNative(DateTime managedDate)
{
return managedDate.ToOADate();
}
internal static long ConvertToManaged(double nativeDate)
{
return DateTime.DoubleDateToTicks(nativeDate);
}
} // class DateMarshaler
#if FEATURE_COMINTEROP
internal static partial class InterfaceMarshaler
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr ConvertToNative(object objSrc, IntPtr itfMT, IntPtr classMT, int flags);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern object ConvertToManaged(ref IntPtr ppUnk, IntPtr itfMT, IntPtr classMT, int flags);
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "InterfaceMarshaler__ClearNative")]
internal static partial void ClearNative(IntPtr pUnk);
} // class InterfaceMarshaler
#endif // FEATURE_COMINTEROP
internal static class MngdNativeArrayMarshaler
{
// Needs to match exactly with MngdNativeArrayMarshaler in ilmarshalers.h
internal struct MarshalerState
{
#pragma warning disable CA1823 // not used by managed code
private IntPtr m_pElementMT;
private IntPtr m_Array;
private IntPtr m_pManagedNativeArrayMarshaler;
private int m_NativeDataValid;
private int m_BestFitMap;
private int m_ThrowOnUnmappableChar;
private short m_vt;
#pragma warning restore CA1823
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, IntPtr pManagedMarshaler);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome,
int cElements);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements);
} // class MngdNativeArrayMarshaler
internal static class MngdFixedArrayMarshaler
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, int cElements, IntPtr pManagedMarshaler);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdFixedArrayMarshaler
#if FEATURE_COMINTEROP
internal static class MngdSafeArrayMarshaler
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int iRank, int dwFlags, IntPtr pManagedMarshaler);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, object pOriginalManaged);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdSafeArrayMarshaler
#endif // FEATURE_COMINTEROP
internal static class MngdRefCustomMarshaler
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pCMHelper);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void ClearManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
} // class MngdRefCustomMarshaler
internal struct AsAnyMarshaler
{
private const ushort VTHACK_ANSICHAR = 253;
private const ushort VTHACK_WINBOOL = 254;
private enum BackPropAction
{
None,
Array,
Layout,
StringBuilderAnsi,
StringBuilderUnicode
}
// Pointer to MngdNativeArrayMarshaler, ownership not assumed.
private IntPtr pvArrayMarshaler;
// Type of action to perform after the CLR-to-unmanaged call.
private BackPropAction backPropAction;
// The managed layout type for BackPropAction.Layout.
private Type? layoutType;
// Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles).
private CleanupWorkListElement? cleanupWorkList;
[Flags]
internal enum AsAnyFlags
{
In = 0x10000000,
Out = 0x20000000,
IsAnsi = 0x00FF0000,
IsThrowOn = 0x0000FF00,
IsBestFit = 0x000000FF
}
private static bool IsIn(int dwFlags) => (dwFlags & (int)AsAnyFlags.In) != 0;
private static bool IsOut(int dwFlags) => (dwFlags & (int)AsAnyFlags.Out) != 0;
private static bool IsAnsi(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsAnsi) != 0;
private static bool IsThrowOn(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsThrowOn) != 0;
private static bool IsBestFit(int dwFlags) => (dwFlags & (int)AsAnyFlags.IsBestFit) != 0;
internal AsAnyMarshaler(IntPtr pvArrayMarshaler)
{
// we need this in case the value being marshaled turns out to be array
Debug.Assert(pvArrayMarshaler != IntPtr.Zero, "pvArrayMarshaler must not be null");
this.pvArrayMarshaler = pvArrayMarshaler;
backPropAction = BackPropAction.None;
layoutType = null;
cleanupWorkList = null;
}
#region ConvertToNative helpers
private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags)
{
Type elementType = pManagedHome.GetType().GetElementType()!;
VarEnum vt;
switch (Type.GetTypeCode(elementType))
{
case TypeCode.SByte: vt = VarEnum.VT_I1; break;
case TypeCode.Byte: vt = VarEnum.VT_UI1; break;
case TypeCode.Int16: vt = VarEnum.VT_I2; break;
case TypeCode.UInt16: vt = VarEnum.VT_UI2; break;
case TypeCode.Int32: vt = VarEnum.VT_I4; break;
case TypeCode.UInt32: vt = VarEnum.VT_UI4; break;
case TypeCode.Int64: vt = VarEnum.VT_I8; break;
case TypeCode.UInt64: vt = VarEnum.VT_UI8; break;
case TypeCode.Single: vt = VarEnum.VT_R4; break;
case TypeCode.Double: vt = VarEnum.VT_R8; break;
case TypeCode.Char: vt = (IsAnsi(dwFlags) ? (VarEnum)VTHACK_ANSICHAR : VarEnum.VT_UI2); break;
case TypeCode.Boolean: vt = (VarEnum)VTHACK_WINBOOL; break;
case TypeCode.Object:
{
if (elementType == typeof(IntPtr))
{
vt = (IntPtr.Size == 4 ? VarEnum.VT_I4 : VarEnum.VT_I8);
}
else if (elementType == typeof(UIntPtr))
{
vt = (IntPtr.Size == 4 ? VarEnum.VT_UI4 : VarEnum.VT_UI8);
}
else goto default;
break;
}
default:
throw new ArgumentException(SR.Arg_NDirectBadObject);
}
// marshal the object as C-style array (UnmanagedType.LPArray)
int dwArrayMarshalerFlags = (int)vt;
if (IsBestFit(dwFlags)) dwArrayMarshalerFlags |= (1 << 16);
if (IsThrowOn(dwFlags)) dwArrayMarshalerFlags |= (1 << 24);
MngdNativeArrayMarshaler.CreateMarshaler(
pvArrayMarshaler,
IntPtr.Zero, // not needed as we marshal primitive VTs only
dwArrayMarshalerFlags,
IntPtr.Zero); // not needed as we marshal primitive VTs only
IntPtr pNativeHome;
IntPtr pNativeHomeAddr = new IntPtr(&pNativeHome);
MngdNativeArrayMarshaler.ConvertSpaceToNative(
pvArrayMarshaler,
ref pManagedHome,
pNativeHomeAddr);
if (IsIn(dwFlags))
{
MngdNativeArrayMarshaler.ConvertContentsToNative(
pvArrayMarshaler,
ref pManagedHome,
pNativeHomeAddr);
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.Array;
}
return pNativeHome;
}
private static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags)
{
IntPtr pNativeHome;
// IsIn, IsOut are ignored for strings - they're always in-only
if (IsAnsi(dwFlags))
{
// marshal the object as Ansi string (UnmanagedType.LPStr)
pNativeHome = CSTRMarshaler.ConvertToNative(
dwFlags & 0xFFFF, // (throw on unmappable char << 8 | best fit)
pManagedHome, //
IntPtr.Zero); // unmanaged buffer will be allocated
}
else
{
// marshal the object as Unicode string (UnmanagedType.LPWStr)
int allocSize = (pManagedHome.Length + 1) * 2;
pNativeHome = Marshal.AllocCoTaskMem(allocSize);
unsafe
{
Buffer.Memmove(ref *(char*)pNativeHome, ref pManagedHome.GetRawStringData(), (nuint)pManagedHome.Length + 1);
}
}
return pNativeHome;
}
private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags)
{
IntPtr pNativeHome;
// P/Invoke can be used to call Win32 apis that don't strictly follow CLR in/out semantics and thus may
// leave garbage in the buffer in circumstances that we can't detect. To prevent us from crashing when
// converting the contents back to managed, put a hidden NULL terminator past the end of the official buffer.
// Unmanaged layout:
// +====================================+
// | Extra hidden NULL |
// +====================================+ \
// | | |
// | [Converted] NULL-terminated string | |- buffer that the target may change
// | | |
// +====================================+ / <-- native home
// Cache StringBuilder capacity and length to ensure we don't allocate a certain amount of
// native memory and then walk beyond its end if the StringBuilder concurrently grows erroneously.
int pManagedHomeCapacity = pManagedHome.Capacity;
int pManagedHomeLength = pManagedHome.Length;
if (pManagedHomeLength > pManagedHomeCapacity)
{
ThrowHelper.ThrowInvalidOperationException();
}
// Note that StringBuilder.Capacity is the number of characters NOT including any terminators.
if (IsAnsi(dwFlags))
{
StubHelpers.CheckStringLength(pManagedHomeCapacity);
// marshal the object as Ansi string (UnmanagedType.LPStr)
int allocSize = checked((pManagedHomeCapacity * Marshal.SystemMaxDBCSCharSize) + 4);
pNativeHome = Marshal.AllocCoTaskMem(allocSize);
byte* ptr = (byte*)pNativeHome;
*(ptr + allocSize - 3) = 0;
*(ptr + allocSize - 2) = 0;
*(ptr + allocSize - 1) = 0;
if (IsIn(dwFlags))
{
int length = Marshal.StringToAnsiString(pManagedHome.ToString(),
ptr, allocSize,
IsBestFit(dwFlags),
IsThrowOn(dwFlags));
Debug.Assert(length < allocSize, "Expected a length less than the allocated size");
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.StringBuilderAnsi;
}
}
else
{
// marshal the object as Unicode string (UnmanagedType.LPWStr)
int allocSize = checked((pManagedHomeCapacity * 2) + 4);
pNativeHome = Marshal.AllocCoTaskMem(allocSize);
byte* ptr = (byte*)pNativeHome;
*(ptr + allocSize - 1) = 0;
*(ptr + allocSize - 2) = 0;
if (IsIn(dwFlags))
{
pManagedHome.InternalCopy(pNativeHome, pManagedHomeLength);
// null-terminate the native string
int length = pManagedHomeLength * 2;
*(ptr + length + 0) = 0;
*(ptr + length + 1) = 0;
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.StringBuilderUnicode;
}
}
return pNativeHome;
}
private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags)
{
// Note that the following call will not throw exception if the type
// of pManagedHome is not marshalable. That's intentional because we
// want to maintain the original behavior where this was indicated
// by TypeLoadException during the actual field marshaling.
int allocSize = Marshal.SizeOfHelper(pManagedHome.GetType(), false);
IntPtr pNativeHome = Marshal.AllocCoTaskMem(allocSize);
// marshal the object as class with layout (UnmanagedType.LPStruct)
if (IsIn(dwFlags))
{
StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte*)pNativeHome, ref cleanupWorkList);
}
if (IsOut(dwFlags))
{
backPropAction = BackPropAction.Layout;
}
layoutType = pManagedHome.GetType();
return pNativeHome;
}
#endregion
internal IntPtr ConvertToNative(object pManagedHome, int dwFlags)
{
if (pManagedHome == null)
return IntPtr.Zero;
if (pManagedHome is ArrayWithOffset)
throw new ArgumentException(SR.Arg_MarshalAsAnyRestriction);
IntPtr pNativeHome;
if (pManagedHome.GetType().IsArray)
{
// array (LPArray)
pNativeHome = ConvertArrayToNative(pManagedHome, dwFlags);
}
else
{
if (pManagedHome is string strValue)
{
// string (LPStr or LPWStr)
pNativeHome = ConvertStringToNative(strValue, dwFlags);
}
else if (pManagedHome is StringBuilder sbValue)
{
// StringBuilder (LPStr or LPWStr)
pNativeHome = ConvertStringBuilderToNative(sbValue, dwFlags);
}
else if (pManagedHome.GetType().IsLayoutSequential || pManagedHome.GetType().IsExplicitLayout)
{
// layout (LPStruct)
pNativeHome = ConvertLayoutToNative(pManagedHome, dwFlags);
}
else
{
// this type is not supported for AsAny marshaling
throw new ArgumentException(SR.Arg_NDirectBadObject);
}
}
return pNativeHome;
}
internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome)
{
switch (backPropAction)
{
case BackPropAction.Array:
{
MngdNativeArrayMarshaler.ConvertContentsToManaged(
pvArrayMarshaler,
ref pManagedHome,
new IntPtr(&pNativeHome));
break;
}
case BackPropAction.Layout:
{
StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte*)pNativeHome);
break;
}
case BackPropAction.StringBuilderAnsi:
{
int length;
if (pNativeHome == IntPtr.Zero)
{
length = 0;
}
else
{
length = string.strlen((byte*)pNativeHome);
}
((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal((sbyte*)pNativeHome, length);
break;
}
case BackPropAction.StringBuilderUnicode:
{
int length;
if (pNativeHome == IntPtr.Zero)
{
length = 0;
}
else
{
length = string.wcslen((char*)pNativeHome);
}
((StringBuilder)pManagedHome).ReplaceBufferInternal((char*)pNativeHome, length);
break;
}
// nothing to do for BackPropAction.None
}
}
internal void ClearNative(IntPtr pNativeHome)
{
if (pNativeHome != IntPtr.Zero)
{
if (layoutType != null)
{
// this must happen regardless of BackPropAction
Marshal.DestroyStructure(pNativeHome, layoutType);
}
Marshal.FreeCoTaskMem(pNativeHome);
}
StubHelpers.DestroyCleanupList(ref cleanupWorkList);