summaryrefslogtreecommitdiff
path: root/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs
blob: 5e1396b67078b8587c7defdd3710c5622ca75743 (plain)
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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32;
using System.Diagnostics;
using System.Runtime.InteropServices.ComTypes;
using System.StubHelpers;

using Internal.Runtime.CompilerServices;

#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif // BIT64

namespace System.Runtime.InteropServices
{
    /// <summary>
    /// This class contains methods that are mainly used to marshal between unmanaged
    /// and managed types.
    /// </summary>
    public static partial class Marshal
    {
#if FEATURE_COMINTEROP
        /// <summary>
        /// IUnknown is {00000000-0000-0000-C000-000000000046}
        /// </summary>
        internal static Guid IID_IUnknown = new Guid(0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46);
#endif //FEATURE_COMINTEROP

        private const int LMEM_FIXED = 0;
        private const int LMEM_MOVEABLE = 2;
#if !FEATURE_PAL
        private const long HiWordMask = unchecked((long)0xffffffffffff0000L);
#endif //!FEATURE_PAL

        // 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
        }

        /// <summary>
        /// The default character size for the system. This is always 2 because
        /// the framework only runs on UTF-16 systems.
        /// </summary>
        public static readonly int SystemDefaultCharSize = 2;

        /// <summary>
        /// The max DBCS character size for the system.
        /// </summary>
        public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();

        /// <summary>
        /// Helper method to retrieve the system's maximum DBCS character size.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern int GetSystemMaxDBCSCharSize();

        public static unsafe string PtrToStringAnsi(IntPtr ptr)
        {
            if (IntPtr.Zero == ptr)
            {
                return null;
            }
            else if (IsWin32Atom(ptr))
            {
                return null;
            }

            int nb = string.strlen((byte*)ptr);
            if (nb == 0)
            {
                return string.Empty;
            }

            return new string((sbyte*)ptr);
        }

        public static unsafe string PtrToStringAnsi(IntPtr ptr, int len)
        {
            if (ptr == IntPtr.Zero)
            {
                throw new ArgumentNullException(nameof(ptr));
            }
            if (len < 0)
            {
                throw new ArgumentException(null, nameof(len));
            }

            return new string((sbyte*)ptr, 0, len);
        }

        public static unsafe string PtrToStringUni(IntPtr ptr, int len)
        {
            if (ptr == IntPtr.Zero)
            {
                throw new ArgumentNullException(nameof(ptr));
            }
            if (len < 0)
            {
                throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(len));
            }

            return new string((char*)ptr, 0, len);
        }

        public static string PtrToStringAuto(IntPtr ptr, int len)
        {
            // Ansi platforms are no longer supported
            return PtrToStringUni(ptr, len);
        }

        public static unsafe string PtrToStringUni(IntPtr ptr)
        {
            if (IntPtr.Zero == ptr)
            {
                return null;
            }
            else if (IsWin32Atom(ptr))
            {
                return null;
            }

            return new string((char*)ptr);
        }

        public static string PtrToStringAuto(IntPtr ptr)
        {
            // Ansi platforms are no longer supported
            return PtrToStringUni(ptr);
        }

        public static unsafe string PtrToStringUTF8(IntPtr ptr)
        {
            if (IntPtr.Zero == ptr)
            {
                return null;
            }

            int nbBytes = string.strlen((byte*)ptr);
            return PtrToStringUTF8(ptr, nbBytes);
        }

        public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen)
        {
            if (byteLen < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(byteLen), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            else if (IntPtr.Zero == ptr)
            {
                return null;
            }
            else if (IsWin32Atom(ptr))
            {
                return null;
            }
            else if (byteLen == 0)
            {
                return string.Empty;
            }

            return Encoding.UTF8.GetString((byte*)ptr, byteLen);
        }

        public static int SizeOf(object structure)
        {
            if (structure == null)
            {
                throw new ArgumentNullException(nameof(structure));
            }

            return SizeOfHelper(structure.GetType(), true);
        }

        public static int SizeOf<T>(T structure) => SizeOf((object)structure);

        public static int SizeOf(Type t)
        {
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }
            if (!(t is RuntimeType))
            {
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
            }
            if (t.IsGenericType)
            {
                throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
            }

            return SizeOfHelper(t, throwIfNotMarshalable: true);
        }

        public static int SizeOf<T>() => SizeOf(typeof(T));

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);

        public static IntPtr OffsetOf(Type t, string fieldName)
        {
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }

            FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (f == null)
            {
                throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName));
            }

            if (!(f is RtFieldInfo rtField))
            {
                throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName));
            }

            return OffsetOfHelper(rtField);
        }

        public static IntPtr OffsetOf<T>(string fieldName) => OffsetOf(typeof(T), fieldName);

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f);

        /// <summary>
        /// IMPORTANT NOTICE: This method does not do any verification on the array.
        /// It must be used with EXTREME CAUTION since passing in invalid index or
        /// an array that is not pinned can cause unexpected results.
        /// </summary>
        public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
        {
            if (arr == null)
                throw new ArgumentNullException(nameof(arr));

            void* pRawData = Unsafe.AsPointer(ref arr.GetRawArrayData());
            return (IntPtr)((byte*)pRawData + (uint)index * (nuint)arr.GetElementSize());
        }

        public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
        {
            if (arr == null)
                throw new ArgumentNullException(nameof(arr));

            void* pRawData = Unsafe.AsPointer(ref arr.GetRawSzArrayData());
            return (IntPtr)((byte*)pRawData + (uint)index * (nuint)Unsafe.SizeOf<T>());
        }

        public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
        {
            CopyToNative(source, startIndex, destination, length);
        }

        private static unsafe void CopyToNative<T>(T[] source, int startIndex, IntPtr destination, int length)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            if (destination == IntPtr.Zero)
                throw new ArgumentNullException(nameof(destination));

            // The rest of the argument validation is done by CopyTo

            new Span<T>(source, startIndex, length).CopyTo(new Span<T>((void*)destination, length));
        }

        public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
        {
            CopyToManaged(source, destination, startIndex, length);
        }

        private static unsafe void CopyToManaged<T>(IntPtr source, T[] destination, int startIndex, int length)
        {
            if (source == IntPtr.Zero)
                throw new ArgumentNullException(nameof(source));
            if (destination == null)
                throw new ArgumentNullException(nameof(destination));
            if (startIndex < 0)
                throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
            if (length < 0)
                throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);

            // The rest of the argument validation is done by CopyTo

            new Span<T>((void*)source, length).CopyTo(new Span<T>(destination, startIndex, length));
        }

        public static byte ReadByte(object ptr, int ofs)
        {
            return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadByte(nativeHome, offset));
        }

        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();
            }
        }

        public static byte ReadByte(IntPtr ptr) => ReadByte(ptr, 0);

        public static short ReadInt16(object ptr, int ofs)
        {
            return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt16(nativeHome, offset));
        }

        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();
            }
        }

        public static short ReadInt16(IntPtr ptr) => ReadInt16(ptr, 0);

        public static int ReadInt32(object ptr, int ofs)
        {
            return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt32(nativeHome, offset));
        }

        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();
            }
        }

        public static int ReadInt32(IntPtr ptr) => ReadInt32(ptr, 0);

        public static IntPtr ReadIntPtr(object ptr, int ofs)
        {
#if BIT64
            return (IntPtr)ReadInt64(ptr, ofs);
#else // 32
            return (IntPtr)ReadInt32(ptr, ofs);
#endif
        }

        public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
        {
#if BIT64
            return (IntPtr)ReadInt64(ptr, ofs);
#else // 32
            return (IntPtr)ReadInt32(ptr, ofs);
#endif
        }

        public static IntPtr ReadIntPtr(IntPtr ptr) => ReadIntPtr(ptr, 0);

        public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] object ptr, int ofs)
        {
            return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt64(nativeHome, offset));
        }

        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();
            }
        }

        public static long ReadInt64(IntPtr ptr) => ReadInt64(ptr, 0);

        //====================================================================
        // Read value from marshaled object (marshaled using AsAny)
        // It's quite slow and can return back dangling pointers
        // It's only there for backcompact
        // People should instead use the IntPtr overloads
        //====================================================================
        private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper)
        {
            // Consumers of this method are documented to throw AccessViolationException on any AV
            if (ptr == null)
            {
                throw new AccessViolationException();
            }

            const int Flags = 
                (int)AsAnyMarshaler.AsAnyFlags.In | 
                (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | 
                (int)AsAnyMarshaler.AsAnyFlags.IsBestFit;

            MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
            AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));

            IntPtr pNativeHome = IntPtr.Zero;

            try
            {
                pNativeHome = marshaler.ConvertToNative(ptr, Flags);
                return readValueHelper(pNativeHome, ofs);
            }
            finally
            {
                marshaler.ClearNative(pNativeHome);
            }
        }

        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();
            }
        }

        public static void WriteByte(object ptr, int ofs, byte val)
        {
            WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, byte value) => WriteByte(nativeHome, offset, value));
        }

        public static void WriteByte(IntPtr ptr, byte val) => WriteByte(ptr, 0, val);

        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();
            }
        }

        public static void WriteInt16(object ptr, int ofs, short val)
        {
            WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, short value) => Marshal.WriteInt16(nativeHome, offset, value));
        }

        public static void WriteInt16(IntPtr ptr, short val) => WriteInt16(ptr, 0, val);

        public static void WriteInt16(IntPtr ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val);

        public static void WriteInt16([In, Out]object ptr, int ofs, char val) => WriteInt16(ptr, ofs, (short)val);

        public static void WriteInt16(IntPtr ptr, char val) => WriteInt16(ptr, 0, (short)val);

        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();
            }
        }

        public static void WriteInt32(object ptr, int ofs, int val)
        {
            WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, int value) => Marshal.WriteInt32(nativeHome, offset, value));
        }

        public static void WriteInt32(IntPtr ptr, int val) => WriteInt32(ptr, 0, val);

        public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
        {
#if BIT64
            WriteInt64(ptr, ofs, (long)val);
#else // 32
            WriteInt32(ptr, ofs, (int)val);
#endif
        }

        public static void WriteIntPtr(object ptr, int ofs, IntPtr val)
        {
#if BIT64
            WriteInt64(ptr, ofs, (long)val);
#else // 32
            WriteInt32(ptr, ofs, (int)val);
#endif
        }

        public static void WriteIntPtr(IntPtr ptr, IntPtr val) => WriteIntPtr(ptr, 0, val);

        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();
            }
        }

        public static void WriteInt64(object ptr, int ofs, long val)
        {
            WriteValueSlow(ptr, ofs, val, (IntPtr nativeHome, int offset, long value) => Marshal.WriteInt64(nativeHome, offset, value));
        }

        public static void WriteInt64(IntPtr ptr, long val) => WriteInt64(ptr, 0, val);

        /// <summary>
        /// Write value into marshaled object (marshaled using AsAny) and propagate the
        /// value back. This is quite slow and can return back dangling pointers. It is
        /// only here for backcompat. People should instead use the IntPtr overloads.
        /// </summary>
        private static unsafe void WriteValueSlow<T>(object ptr, int ofs, T val, Action<IntPtr, int, T> writeValueHelper)
        {
            // Consumers of this method are documented to throw AccessViolationException on any AV
            if (ptr == null)
            {
                throw new AccessViolationException();
            }

            const int Flags = 
                (int)AsAnyMarshaler.AsAnyFlags.In | 
                (int)AsAnyMarshaler.AsAnyFlags.Out | 
                (int)AsAnyMarshaler.AsAnyFlags.IsAnsi | 
                (int)AsAnyMarshaler.AsAnyFlags.IsBestFit;

            MngdNativeArrayMarshaler.MarshalerState nativeArrayMarshalerState = new MngdNativeArrayMarshaler.MarshalerState();
            AsAnyMarshaler marshaler = new AsAnyMarshaler(new IntPtr(&nativeArrayMarshalerState));

            IntPtr pNativeHome = IntPtr.Zero;

            try
            {
                pNativeHome = marshaler.ConvertToNative(ptr, Flags);
                writeValueHelper(pNativeHome, ofs, val);
                marshaler.ConvertToManaged(ptr, pNativeHome);
            }
            finally
            {
                marshaler.ClearNative(pNativeHome);
            }
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int GetLastWin32Error();

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern void SetLastWin32Error(int error);

        public static int GetHRForLastWin32Error()
        {
            int dwLastError = GetLastWin32Error();
            if ((dwLastError & 0x80000000) == 0x80000000)
            {
                return dwLastError;
            }
            
            return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
        }

        public static void Prelink(MethodInfo m)
        {
            if (m == null)
            {
                throw new ArgumentNullException(nameof(m));
            }
            if (!(m is RuntimeMethodInfo rmi))
            {
                throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(m));
            }

            InternalPrelink(rmi);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        private static extern void InternalPrelink(IRuntimeMethodInfo m);

        public static void PrelinkAll(Type c)
        {
            if (c == null)
            {
                throw new ArgumentNullException(nameof(c));
            }

            MethodInfo[] mi = c.GetMethods();
            if (mi != null)
            {
                for (int i = 0; i < mi.Length; i++)
                {
                    Prelink(mi[i]);
                }
            }
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
        
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int GetExceptionCode();

        /// <summary>
        /// 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. 
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public static extern void StructureToPtr(object structure, IntPtr ptr, bool fDeleteOld);

        public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
        {
            StructureToPtr((object)structure, ptr, fDeleteOld);
        }

        /// <summary>
        /// Marshals data from a native memory block to a preallocated structure class.
        /// </summary>
        public static void PtrToStructure(IntPtr ptr, object structure)
        {
            PtrToStructureHelper(ptr, structure, allowValueClasses: false);
        }

        public static void PtrToStructure<T>(IntPtr ptr, T structure)
        {
            PtrToStructure(ptr, (object)structure);
        }

        /// <summary>
        /// Creates a new instance of "structuretype" and marshals data from a
        /// native memory block to it.
        /// </summary>
        public static object PtrToStructure(IntPtr ptr, Type structureType)
        {
            if (ptr == IntPtr.Zero)
            {
                return null;
            }

            if (structureType == null)
            {
                throw new ArgumentNullException(nameof(structureType));
            }
            if (structureType.IsGenericType)
            {
                throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType));
            }
            if (!(structureType.UnderlyingSystemType is RuntimeType rt))
            {
                throw new ArgumentException(SR.Arg_MustBeType, nameof(structureType));
            }

            object structure = rt.CreateInstanceDefaultCtor(publicOnly: false, skipCheckThis: false, fillCache: false, wrapExceptions: true);
            PtrToStructureHelper(ptr, structure, allowValueClasses: true);
            return structure;
        }

        public static T PtrToStructure<T>(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T));

        /// <summary>
        /// Helper function to copy a pointer into a preallocated structure.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern void PtrToStructureHelper(IntPtr ptr, object structure, bool allowValueClasses);

        /// <summary>
        /// Frees all substructures pointed to by the native memory block.
        /// "structuretype" is used to provide layout information.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern void DestroyStructure(IntPtr ptr, Type structuretype);

        public static void DestroyStructure<T>(IntPtr ptr) => DestroyStructure(ptr, typeof(T));

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern bool IsPinnable(object obj);

#if FEATURE_COMINTEROP
        /// <summary>
        /// Returns the HInstance for this module.  Returns -1 if the module doesn't have
        /// an HInstance.  In Memory (Dynamic) Modules won't have an HInstance.
        /// </summary>
        public static IntPtr GetHINSTANCE(Module m)
        {
            if (m == null)
            {
                throw new ArgumentNullException(nameof(m));
            }

            if (m is RuntimeModule rtModule)
            {
                return GetHINSTANCE(rtModule.GetNativeHandle());
            }

            return (IntPtr)(-1);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        private static extern IntPtr GetHINSTANCE(RuntimeModule m);

#endif // FEATURE_COMINTEROP

        /// <summary>
        /// Throws a CLR exception based on the HRESULT.
        /// </summary>
        public static void ThrowExceptionForHR(int errorCode)
        {
            if (errorCode < 0)
            {
                ThrowExceptionForHRInternal(errorCode, IntPtr.Zero);
            }
        }

        public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
        {
            if (errorCode < 0)
            {
                ThrowExceptionForHRInternal(errorCode, errorInfo);
            }
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo);

        /// <summary>
        /// Converts the HRESULT to a CLR exception.
        /// </summary>
        public static Exception GetExceptionForHR(int errorCode)
        {
            if (errorCode >= 0)
            {
                return null;
            }

            return GetExceptionForHRInternal(errorCode, IntPtr.Zero);
        }
        public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
        {
            if (errorCode >= 0)
            {
                return null;
            }

            return GetExceptionForHRInternal(errorCode, errorInfo);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo);

        public static IntPtr AllocHGlobal(IntPtr cb)
        {
            // For backwards compatibility on 32 bit platforms, ensure we pass values between 
            // int.MaxValue and uint.MaxValue to Windows.  If the binary has had the 
            // LARGEADDRESSAWARE bit set in the PE header, it may get 3 or 4 GB of user mode
            // address space.  It is remotely that those allocations could have succeeded,
            // though I couldn't reproduce that.  In either case, that means we should continue
            // throwing an OOM instead of an ArgumentOutOfRangeException for "negative" amounts of memory.
            UIntPtr numBytes;
#if BIT64
            numBytes = new UIntPtr(unchecked((ulong)cb.ToInt64()));
#else // 32
            numBytes = new UIntPtr(unchecked((uint)cb.ToInt32()));
#endif

            IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes));
            if (pNewMem == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return pNewMem;
        }

        public static IntPtr AllocHGlobal(int cb) => AllocHGlobal((IntPtr)cb);

        public static void FreeHGlobal(IntPtr hglobal)
        {
            if (!IsWin32Atom(hglobal))
            {
                if (IntPtr.Zero != Win32Native.LocalFree(hglobal))
                {
                    ThrowExceptionForHR(GetHRForLastWin32Error());
                }
            }
        }

        public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
        {
            IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
            if (pNewMem == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return pNewMem;
        }
    
        public static unsafe IntPtr StringToHGlobalAnsi(string s)
        {
            if (s == null)
            {
                return IntPtr.Zero;
            }

            long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
            int nb = (int)lnb;

            // Overflow checking
            if (nb != lnb)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            UIntPtr len = new UIntPtr((uint)nb);
            IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
            if (hglobal == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            s.ConvertToAnsi((byte*)hglobal, nb, false, false);
            return hglobal;
        }

        public static unsafe IntPtr StringToHGlobalUni(string s)
        {
            if (s == null)
            {
                return IntPtr.Zero;
            }

            int nb = (s.Length + 1) * 2;

            // Overflow checking
            if (nb < s.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            UIntPtr len = new UIntPtr((uint)nb);
            IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
            if (hglobal == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            fixed (char* firstChar = s)
            {
                string.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
            }
            return hglobal;
        }

        public static IntPtr StringToHGlobalAuto(string s)
        {
            // Ansi platforms are no longer supported
            return StringToHGlobalUni(s);
        }

#if FEATURE_COMINTEROP
        /// <summary>
        /// Converts the CLR exception to an HRESULT. This function also sets
        /// up an IErrorInfo for the exception.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int GetHRForException(Exception e);

        /// <summary>
        /// Converts the CLR exception to an HRESULT. This function also sets
        /// up an IErrorInfo for the exception.
        /// This function is only used in WinRT and converts ObjectDisposedException
        /// to RO_E_CLOSED
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern int GetHRForException_WinRT(Exception e);

        /// <summary>
        /// Given a managed object that wraps an ITypeInfo, return its name.
        /// </summary>
        public static string GetTypeInfoName(ITypeInfo typeInfo)
        {
            if (typeInfo == null)
            {
                throw new ArgumentNullException(nameof(typeInfo));
            }

            typeInfo.GetDocumentation(-1, out string strTypeLibName, out _, out _, out _);
            return strTypeLibName;
        }

        // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
        // on Marshal for more consistent API surface.
        public static Type GetTypeFromCLSID(Guid clsid) => RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError: false);

        /// <summary>
        /// Return the IUnknown* for an Object if the current context is the one
        /// where the RCW was first seen. Will return null otherwise.
        /// </summary>
        public static IntPtr /* IUnknown* */ GetIUnknownForObject(object o)
        {
            return GetIUnknownForObjectNative(o, false);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(object o, bool onlyInContext);

        /// <summary>
        /// Return the raw IUnknown* for a COM Object not related to current.
        /// Does not call AddRef.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(object o);
#endif // FEATURE_COMINTEROP

        public static IntPtr /* IDispatch */ GetIDispatchForObject(object o) => throw new PlatformNotSupportedException();

#if FEATURE_COMINTEROP
        /// <summary>
        /// Return the IUnknown* representing the interface for the Object.
        /// Object o should support Type T
        /// </summary>
        public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T)
        {
            return GetComInterfaceForObjectNative(o, T, false, true);
        }

        public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) => GetComInterfaceForObject(o, typeof(TInterface));

        /// <summary>
        /// Return the IUnknown* representing the interface for the Object.
        /// Object o should support Type T, it refer the value of mode to
        /// invoke customized QueryInterface or not.
        /// </summary>
        public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
        {
            bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
            return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface);

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk);

        /// <summary>
        /// Return a unique Object given an IUnknown.  This ensures that you receive a fresh
        /// object (we will not look in the cache to match up this IUnknown to an already
        /// existing object). This is useful in cases where you want to be able to call
        /// ReleaseComObject on a RCW and not worry about other active uses ofsaid RCW.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern object GetUniqueObjectForIUnknown(IntPtr unknown);

        /// <summary>
        /// Return an Object for IUnknown, using the Type T.
        /// Type T should be either a COM imported Type or a sub-type of COM imported Type
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t);

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, object o);

        public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
        {
            return CreateAggregatedObject(pOuter, (object)o);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern void CleanupUnusedObjectsInCurrentContext();

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern bool AreComObjectsAvailableForCleanup();

        /// <summary>
        /// Checks if the object is classic COM component.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern bool IsComObject(object o);

#endif // FEATURE_COMINTEROP

        public static IntPtr AllocCoTaskMem(int cb)
        {
            IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));
            if (pNewMem == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return pNewMem;
        }

        public static unsafe IntPtr StringToCoTaskMemUni(string s)
        {
            if (s == null)
            {
                return IntPtr.Zero;
            }

            int nb = (s.Length + 1) * 2;

            // Overflow checking
            if (nb < s.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
            if (hglobal == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            fixed (char* firstChar = s)
            {
                string.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
            }
            return hglobal;
        }

        public static unsafe IntPtr StringToCoTaskMemUTF8(string s)
        {
            if (s == null)
            {
                return IntPtr.Zero;
            }

            int nb = Encoding.UTF8.GetMaxByteCount(s.Length);
            IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1));
            if (pMem == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            fixed (char* firstChar = s)
            {
                byte* pbMem = (byte*)pMem;
                int nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb);
                pbMem[nbWritten] = 0;
            }
            return pMem;
        }

        public static IntPtr StringToCoTaskMemAuto(string s)
        {
            // Ansi platforms are no longer supported
            return StringToCoTaskMemUni(s);
        }

        public static unsafe IntPtr StringToCoTaskMemAnsi(string s)
        {
            if (s == null)
            {
                return IntPtr.Zero;
            }

            long lnb = (s.Length + 1) * (long)SystemMaxDBCSCharSize;
            int nb = (int)lnb;

            // Overflow checking
            if (nb != lnb)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
            if (hglobal == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            s.ConvertToAnsi((byte*)hglobal, nb, false, false);
            return hglobal;
        }

        public static void FreeCoTaskMem(IntPtr ptr)
        {
            if (!IsWin32Atom(ptr))
            {
                Win32Native.CoTaskMemFree(ptr);
            }
        }

        public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
        {
            IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb));
            if (pNewMem == IntPtr.Zero && cb != 0)
            {
                throw new OutOfMemoryException();
            }

            return pNewMem;
        }

        internal static IntPtr AllocBSTR(int length)
        {
            IntPtr bstr = Win32Native.SysAllocStringLen(null, length);
            if (bstr == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }
            return bstr;
        }

        public static void FreeBSTR(IntPtr ptr)
        {
            if (!IsWin32Atom(ptr))
            {
                Win32Native.SysFreeString(ptr);
            }
        }

        public static IntPtr StringToBSTR(string s)
        {
            if (s == null)
            {
                return IntPtr.Zero;
            }

            // Overflow checking
            if (s.Length + 1 < s.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(s));
            }

            IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length);
            if (bstr == IntPtr.Zero)
            {
                throw new OutOfMemoryException();
            }

            return bstr;
        }

        public static string PtrToStringBSTR(IntPtr ptr)
        {
            return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr));
        }

#if FEATURE_COMINTEROP
        /// <summary>
        /// Release the COM component and if the reference hits 0 zombie this object.
        /// Further usage of this Object might throw an exception
        /// </summary>
        public static int ReleaseComObject(object o)
        {
            if (o == null)
            {
                // Match .NET Framework behaviour.
                throw new NullReferenceException();
            }
            if (!(o is __ComObject co))
            {
                throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
            }

            return co.ReleaseSelf();
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern int InternalReleaseComObject(object o);

        /// <summary>
        /// Release the COM component and zombie this object.
        /// Further usage of this Object might throw an exception
        /// </summary>
        public static int FinalReleaseComObject(object o)
        {
            if (o == null)
            {
                throw new ArgumentNullException(nameof(o));
            }
            if (!(o is __ComObject co))
            {
                throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
            }

            co.FinalReleaseSelf();
            return 0;
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern void InternalFinalReleaseComObject(object o);

        public static object GetComObjectData(object obj, object key)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (!(obj is __ComObject co))
            {
                throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj));
            }
            if (obj.GetType().IsWindowsRuntimeObject)
            {
                throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(obj));
            }

            // Retrieve the data from the __ComObject.
            return co.GetData(key);
        }

        /// <summary>
        /// Sets data on the COM object. The data can only be set once for a given key
        /// and cannot be removed. This function returns true if the data has been added,
        /// false if the data could not be added because there already was data for the
        /// specified key.
        /// </summary>
        public static bool SetComObjectData(object obj, object key, object data)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (!(obj is __ComObject co))
            {
                throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj));
            }
            if (obj.GetType().IsWindowsRuntimeObject)
            {
                throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(obj));
            }

            // Retrieve the data from the __ComObject.
            return co.SetData(key, data);
        }

        /// <summary>
        /// This method takes the given COM object and wraps it in an object
        /// of the specified type. The type must be derived from __ComObject.
        /// </summary>
        public static object CreateWrapperOfType(object o, Type t)
        {
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }
            if (!t.IsCOMObject)
            {
                throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t));
            }
            if (t.IsGenericType)
            {
                throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
            }
            if (t.IsWindowsRuntimeObject)
            {
                throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t));
            }

            if (o == null)
            {
                return null;
            }

            if (!o.GetType().IsCOMObject)
            {
                throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
            }
            if (o.GetType().IsWindowsRuntimeObject)
            {
                throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(o));
            }

            // Check to see if we have nothing to do.
            if (o.GetType() == t)
            {
                return o;
            }

            // Check to see if we already have a cached wrapper for this type.
            object Wrapper = GetComObjectData(o, t);
            if (Wrapper == null)
            {
                // Create the wrapper for the specified type.
                Wrapper = InternalCreateWrapperOfType(o, t);

                // Attempt to cache the wrapper on the object.
                if (!SetComObjectData(o, t, Wrapper))
                {
                    // Another thead already cached the wrapper so use that one instead.
                    Wrapper = GetComObjectData(o, t);
                }
            }

            return Wrapper;
        }

        public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
        {
            return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        private static extern object InternalCreateWrapperOfType(object o, Type t);

        /// <summary>
        /// check if the type is visible from COM.
        /// </summary>
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        public static extern bool IsTypeVisibleFromCom(Type t);

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk);

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk);

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern void GetNativeVariantForObject(object obj, /* VARIANT * */ IntPtr pDstNativeVariant);

        public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
        {
            GetNativeVariantForObject((object)obj, pDstNativeVariant);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant);

        public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
        {
            return (T)GetObjectForNativeVariant(pSrcNativeVariant);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars);

        public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
        {
            object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
            T[] result = null;

            if (objects != null)
            {
                result = new T[objects.Length];
                Array.Copy(objects, 0, result, 0, objects.Length);
            }

            return result;
        }

        /// <summary>
        /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
        /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int GetStartComSlot(Type t);

        /// <summary>
        /// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern int GetEndComSlot(Type t);
#endif // FEATURE_COMINTEROP

        /// <summary>
        /// Generates a GUID for the specified type. If the type has a GUID in the
        /// metadata then it is returned otherwise a stable guid is generated based
        /// on the fully qualified name of the type.
        /// </summary>
        public static Guid GenerateGuidForType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (!(type is RuntimeType))
            {
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
            }

            return type.GUID;
        }

        /// <summary>
        /// This method generates a PROGID for the specified type. If the type has
        /// a PROGID in the metadata then it is returned otherwise a stable PROGID
        /// is generated based on the fully qualified name of the type.
        /// </summary>
        public static string GenerateProgIdForType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (type.IsImport)
            {
                throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type));
            }
            if (type.IsGenericType)
            {
                throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
            }

            IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
            for (int i = 0; i < cas.Count; i++)
            {
                if (cas[i].Constructor.DeclaringType == typeof(ProgIdAttribute))
                {
                    // Retrieve the PROGID string from the ProgIdAttribute.
                    IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
                    Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");

                    CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
                    Debug.Assert(progIdConstructorArg.ArgumentType == typeof(string), "progIdConstructorArg.ArgumentType == typeof(String)");

                    string strProgId = (string)progIdConstructorArg.Value;

                    if (strProgId == null)
                        strProgId = string.Empty;

                    return strProgId;
                }
            }

            // If there is no prog ID attribute then use the full name of the type as the prog id.
            return type.FullName;
        }

#if FEATURE_COMINTEROP
        public static object BindToMoniker(string monikerName)
        {
            CreateBindCtx(0, out IBindCtx bindctx);

            MkParseDisplayName(bindctx, monikerName, out _, out IMoniker pmoniker);
            BindMoniker(pmoniker, 0, ref IID_IUnknown, out object obj);

            return obj;
        }

        [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
        private static extern void CreateBindCtx(uint reserved, out IBindCtx ppbc);

        [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
        private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] string szUserName, out uint pchEaten, out IMoniker ppmk);

        [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
        private static extern void BindMoniker(IMoniker pmk, uint grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult);

        /// <summary>
        /// Private method called from EE upon use of license/ICF2 marshaling.
        /// </summary>
        private static IntPtr LoadLicenseManager()
        {
            Type t = Type.GetType("System.ComponentModel.LicenseManager, System", throwOnError: true);
            return t.TypeHandle.Value;
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        public static extern void ChangeWrapperHandleStrength(object otp, bool fIsWeak);

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk);

#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
#endif

        /// <summary>
        /// Create activation factory and wraps it with a unique RCW.
        /// </summary>
        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern object GetNativeActivationFactory(Type type);

#endif // FEATURE_COMINTEROP

        public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
        {
            if (ptr == IntPtr.Zero)
            {
                throw new ArgumentNullException(nameof(ptr));
            }
            if (t == null)
            {
                throw new ArgumentNullException(nameof(t));
            }
            if (!(t is RuntimeType))
            {
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
            }
            if (t.IsGenericType)
            {
                throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
            }

            Type c = t.BaseType;
            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
            {
                throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t));
            }

            return GetDelegateForFunctionPointerInternal(ptr, t);
        }

        public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
        {
            return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t);

        public static IntPtr GetFunctionPointerForDelegate(Delegate d)
        {
            if (d == null)
            {
                throw new ArgumentNullException(nameof(d));
            }

            return GetFunctionPointerForDelegateInternal(d);
        }

        public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
        {
            return GetFunctionPointerForDelegate((Delegate)(object)d);
        }

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);

        public static IntPtr SecureStringToBSTR(SecureString s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            return s.MarshalToBSTR();
        }

        public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            return s.MarshalToString(globalAlloc: false, unicode: false);
        }

        public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            return s.MarshalToString(globalAlloc: false, unicode: true);
        }
        
        public static void ZeroFreeBSTR(IntPtr s)
        {
            if (s == IntPtr.Zero)
            {
                return;
            }
            RuntimeImports.RhZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
            FreeBSTR(s);
        }

        public unsafe static void ZeroFreeCoTaskMemAnsi(IntPtr s)
        {
            if (s == IntPtr.Zero)
            {
                return;
            }
            RuntimeImports.RhZeroMemory(s, (UIntPtr)string.strlen((byte*)s));
            FreeCoTaskMem(s);
        }

        public static unsafe void ZeroFreeCoTaskMemUnicode(IntPtr s)
        {
            if (s == IntPtr.Zero)
            {
                return;
            }
            RuntimeImports.RhZeroMemory(s, (UIntPtr)(string.wcslen((char*)s) * 2));
            FreeCoTaskMem(s);
        }

        public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s)
        {
            if (s == IntPtr.Zero)
            {
                return;
            }
            RuntimeImports.RhZeroMemory(s, (UIntPtr)string.strlen((byte*)s));
            FreeCoTaskMem(s);
        }

        public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            return s.MarshalToString(globalAlloc: true, unicode: false);
        }

        public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            return s.MarshalToString(globalAlloc: true, unicode: true); ;
        }

        public unsafe static void ZeroFreeGlobalAllocAnsi(IntPtr s)
        {
            if (s == IntPtr.Zero)
            {
                return;
            }
            RuntimeImports.RhZeroMemory(s, (UIntPtr)string.strlen((byte*)s));
            FreeHGlobal(s);
        }

        public static unsafe void ZeroFreeGlobalAllocUnicode(IntPtr s)
        {
            if (s == IntPtr.Zero)
            {
                return;
            }
            RuntimeImports.RhZeroMemory(s, (UIntPtr)(string.wcslen((char*)s) * 2));
            FreeHGlobal(s);
        }
    }
}