/
marshal.cs
2784 lines (2419 loc) · 118 KB
/
marshal.cs
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
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: Marshal
**
**
** Purpose: This class contains methods that are mainly used to marshal
** between unmanaged and managed types.
**
**
=============================================================================*/
namespace System.Runtime.InteropServices
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Win32Native = Microsoft.Win32.Win32Native;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.ComTypes;
[Serializable]
public enum CustomQueryInterfaceMode
{
Ignore = 0,
Allow = 1
}
//========================================================================
// All public methods, including PInvoke, are protected with linkchecks.
// Remove the default demands for all PInvoke methods with this global
// declaration on the class.
//========================================================================
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public static partial class Marshal
{
//====================================================================
// Defines used inside the Marshal class.
//====================================================================
private const int LMEM_FIXED = 0;
#if !FEATURE_PAL
private const int LMEM_MOVEABLE = 2;
private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L);
#endif //!FEATURE_PAL
#if FEATURE_COMINTEROP
private static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
#endif //FEATURE_COMINTEROP
// Win32 has the concept of Atoms, where a pointer can either be a pointer
// or an int. If it's less than 64K, this is guaranteed to NOT be a
// pointer since the bottom 64K bytes are reserved in a process' page table.
// We should be careful about deallocating this stuff. Extracted to
// a function to avoid C# problems with lack of support for IntPtr.
// We have 2 of these methods for slightly different semantics for NULL.
private static bool IsWin32Atom(IntPtr ptr)
{
#if FEATURE_PAL
return false;
#else
long lPtr = (long)ptr;
return 0 == (lPtr & HIWORDMASK);
#endif
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static bool IsNotWin32Atom(IntPtr ptr)
{
#if FEATURE_PAL
return false;
#else
long lPtr = (long)ptr;
return 0 != (lPtr & HIWORDMASK);
#endif
}
//====================================================================
// The default character size for the system. This is always 2 because
// the framework only runs on UTF-16 systems.
//====================================================================
public static readonly int SystemDefaultCharSize = 2;
//====================================================================
// The max DBCS character size for the system.
//====================================================================
public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();
//====================================================================
// The name, title and description of the assembly that will contain
// the dynamically generated interop types.
//====================================================================
private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes";
private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types";
private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's";
private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes";
//====================================================================
// Helper method to retrieve the system's maximum DBCS character size.
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetSystemMaxDBCSCharSize();
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr)
{
if (IntPtr.Zero == ptr) {
return null;
}
else if (IsWin32Atom(ptr)) {
return null;
}
else {
int nb = Win32Native.lstrlenA(ptr);
if( nb == 0) {
return string.Empty;
}
else {
return new String((sbyte *)ptr);
}
}
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("ptr");
if (len < 0)
throw new ArgumentException("len");
return new String((sbyte *)ptr, 0, len);
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("ptr");
if (len < 0)
throw new ArgumentException("len");
return new String((char *)ptr, 0, len);
}
[System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringAuto(IntPtr ptr, int len)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr, len);
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUni(IntPtr ptr)
{
if (IntPtr.Zero == ptr) {
return null;
}
else if (IsWin32Atom(ptr)) {
return null;
}
else {
return new String((char *)ptr);
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringAuto(IntPtr ptr)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr);
}
//====================================================================
// SizeOf()
//====================================================================
[ResourceExposure(ResourceScope.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public static int SizeOf(Object structure)
{
if (structure == null)
throw new ArgumentNullException("structure");
// we never had a check for generics here
Contract.EndContractBlock();
return SizeOfHelper(structure.GetType(), true);
}
public static int SizeOf<T>(T structure)
{
return SizeOf((object)structure);
}
[ResourceExposure(ResourceScope.None)]
[Pure]
public static int SizeOf(Type t)
{
if (t == null)
throw new ArgumentNullException("t");
if (!(t is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
if (t.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
Contract.EndContractBlock();
return SizeOfHelper(t, true);
}
public static int SizeOf<T>()
{
return SizeOf(typeof(T));
}
#if !FEATURE_CORECLR || FEATURE_CORESYSTEM
/// <summary>
/// Returns the aligned size of an instance of a value type.
/// </summary>
/// <typeparam name="T">Provide a value type to figure out its size</typeparam>
/// <returns>The aligned size of T in bytes.</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static uint AlignedSizeOf<T>() where T : struct
{
uint size = SizeOfType(typeof(T));
if (size == 1 || size == 2)
{
return size;
}
if (IntPtr.Size == 8 && size == 4)
{
return size;
}
return AlignedSizeOfType(typeof(T));
}
// Type must be a value type with no object reference fields. We only
// assert this, due to the lack of a suitable generic constraint.
[MethodImpl(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern uint SizeOfType(Type type);
// Type must be a value type with no object reference fields. We only
// assert this, due to the lack of a suitable generic constraint.
[MethodImpl(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern uint AlignedSizeOfType(Type type);
#endif // !FEATURE_CORECLR || FEATURE_CORESYSTEM
#if !FEATURE_CORECLR // Marshal is critical in CoreCLR, so SafeCritical members trigger Annotator violations
[System.Security.SecuritySafeCritical]
#endif // !FEATURE_CORECLR
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);
//====================================================================
// OffsetOf()
//====================================================================
public static IntPtr OffsetOf(Type t, String fieldName)
{
if (t == null)
throw new ArgumentNullException("t");
Contract.EndContractBlock();
FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f == null)
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), "fieldName");
RtFieldInfo rtField = f as RtFieldInfo;
if (rtField == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "fieldName");
return OffsetOfHelper(rtField);
}
public static IntPtr OffsetOf<T>(string fieldName)
{
return OffsetOf(typeof(T), fieldName);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f);
//====================================================================
// UnsafeAddrOfPinnedArrayElement()
//
// IMPORTANT NOTICE: This method does not do any verification on the
// array. It must be used with EXTREME CAUTION since passing in
// an array that is not pinned or in the fixed heap can cause
// unexpected results !
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index);
[System.Security.SecurityCritical]
public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
}
//====================================================================
// Copy blocks from CLR arrays to native memory.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void CopyToNative(Object source, int startIndex, IntPtr destination, int length);
//====================================================================
// Copy blocks from native memory to CLR arrays
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void CopyToManaged(IntPtr source, Object destination, int startIndex, int length);
//====================================================================
// Read from memory
//====================================================================
[DllImport(Win32Native.SHIM, EntryPoint="ND_RU1")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
return *addr;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static byte ReadByte(IntPtr ptr)
{
return ReadByte(ptr,0);
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_RI2")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
return *((short *)addr);
}
else
{
// unaligned read
short val;
byte *valPtr = (byte *)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
return val;
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static short ReadInt16(IntPtr ptr)
{
return ReadInt16(ptr, 0);
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_RI4"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
return *((int *)addr);
}
else
{
// unaligned read
int val;
byte *valPtr = (byte *)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
return val;
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int ReadInt32(IntPtr ptr)
{
return ReadInt32(ptr,0);
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
#if WIN32
return (IntPtr) ReadInt32(ptr, ofs);
#else
return (IntPtr) ReadInt64(ptr, ofs);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#if WIN32
return (IntPtr) ReadInt32(ptr, ofs);
#else
return (IntPtr) ReadInt64(ptr, ofs);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr)
{
#if WIN32
return (IntPtr) ReadInt32(ptr, 0);
#else
return (IntPtr) ReadInt64(ptr, 0);
#endif
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_RI8"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
return *((long *)addr);
}
else
{
// unaligned read
long val;
byte *valPtr = (byte *)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
valPtr[4] = addr[4];
valPtr[5] = addr[5];
valPtr[6] = addr[6];
valPtr[7] = addr[7];
return val;
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long ReadInt64(IntPtr ptr)
{
return ReadInt64(ptr,0);
}
//====================================================================
// Write to memory
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
try
{
byte *addr = (byte *)ptr + ofs;
*addr = val;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WU1")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteByte(IntPtr ptr, byte val)
{
WriteByte(ptr, 0, val);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
*((short *)addr) = val;
}
else
{
// unaligned write
byte *valPtr = (byte *)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WI2")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, short val)
{
WriteInt16(ptr, 0, val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16([In,Out]Object ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, char val)
{
WriteInt16(ptr, 0, (short)val);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
*((int *)addr) = val;
}
else
{
// unaligned write
byte *valPtr = (byte *)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WI4")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt32(IntPtr ptr, int val)
{
WriteInt32(ptr,0,val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
#if WIN32
WriteInt32(ptr, ofs, (int)val);
#else
WriteInt64(ptr, ofs, (long)val);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)
{
#if WIN32
WriteInt32(ptr, ofs, (int)val);
#else
WriteInt64(ptr, ofs, (long)val);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
#if WIN32
WriteInt32(ptr, 0, (int)val);
#else
WriteInt64(ptr, 0, (long)val);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
*((long *)addr) = val;
}
else
{
// unaligned write
byte *valPtr = (byte *)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
addr[4] = valPtr[4];
addr[5] = valPtr[5];
addr[6] = valPtr[6];
addr[7] = valPtr[7];
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WI8")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt64(IntPtr ptr, long val)
{
WriteInt64(ptr, 0, val);
}
//====================================================================
// GetLastWin32Error
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int GetLastWin32Error();
//====================================================================
// SetLastWin32Error
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern void SetLastWin32Error(int error);
//====================================================================
// GetHRForLastWin32Error
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
return dwLastError;
else
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
//====================================================================
// Prelink
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void Prelink(MethodInfo m)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
InternalPrelink(rmi);
}
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[SecurityCritical]
private static extern void InternalPrelink(IRuntimeMethodInfo m);
[System.Security.SecurityCritical] // auto-generated_required
public static void PrelinkAll(Type c)
{
if (c == null)
throw new ArgumentNullException("c");
Contract.EndContractBlock();
MethodInfo[] mi = c.GetMethods();
if (mi != null)
{
for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
}
//====================================================================
// NumParamBytes
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static int NumParamBytes(MethodInfo m)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
return InternalNumParamBytes(rmi);
}
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[SecurityCritical]
private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
//====================================================================
// Win32 Exception stuff
// These are mostly interesting for Structured exception handling,
// but need to be exposed for all exceptions (not just SEHException).
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
//====================================================================
// Marshals data from a structure class to a native memory block.
// If the structure contains pointers to allocated blocks and
// "fDeleteOld" is true, this routine will call DestroyStructure() first.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
[System.Security.SecurityCritical]
public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure, ptr, fDeleteOld);
}
//====================================================================
// Marshals data from a native memory block to a preallocated structure class.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure(IntPtr ptr, Object structure)
{
PtrToStructureHelper(ptr, structure, false);
}
[System.Security.SecurityCritical]
public static void PtrToStructure<T>(IntPtr ptr, T structure)
{
PtrToStructure(ptr, (object)structure);
}
//====================================================================
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Object PtrToStructure(IntPtr ptr, Type structureType)
{
if (ptr == IntPtr.Zero) return null;
if (structureType == null)
throw new ArgumentNullException("structureType");
if (structureType.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "structureType");
RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, ref stackMark);
PtrToStructureHelper(ptr, structure, true);
return structure;
}
[System.Security.SecurityCritical]
public static T PtrToStructure<T>(IntPtr ptr)
{
return (T)PtrToStructure(ptr, typeof(T));
}