3 // Copyright (c) Microsoft Corporation. All rights reserved.
7 // <OWNER>GPaperin</OWNER>
8 // <OWNER>Microsoft</OWNER>
12 using System.Security;
13 using System.Collections;
14 using System.Collections.Generic;
15 using System.Diagnostics.Contracts;
16 using System.Runtime.InteropServices;
17 using System.Runtime.CompilerServices;
19 namespace System.Runtime.InteropServices.WindowsRuntime
21 // This is a set of stub methods implementing the support for the ICollection interface on WinRT
22 // objects that support IBindableVector. Used by the interop mashaling infrastructure.
24 // The methods on this class must be written VERY carefully to avoid introducing security holes.
25 // That's because they are invoked with special "this"! The "this" object
26 // for all of these methods are not BindableVectorToCollectionAdapter objects. Rather, they are
27 // of type IBindableVector. No actual BindableVectorToCollectionAdapter object is ever instantiated.
28 // Thus, you will see a lot of expressions that cast "this" to "IBindableVector".
29 internal sealed class BindableVectorToCollectionAdapter
31 private BindableVectorToCollectionAdapter()
33 Contract.Assert(false, "This class is never instantiated");
41 IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
42 uint size = _this.Size;
43 if (((uint)Int32.MaxValue) < size)
45 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
51 // bool IsSynchronized { get }
54 internal bool IsSynchronized()
59 // object SyncRoot { get }
62 internal object SyncRoot()
67 // void CopyTo(Array array, int index)
70 internal void CopyTo(Array array, int arrayIndex)
73 throw new ArgumentNullException("array");
75 // ICollection expects the destination array to be single-dimensional.
77 throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
79 int destLB = array.GetLowerBound(0);
82 int destLen = array.GetLength(0);
84 if (arrayIndex < destLB)
85 throw new ArgumentOutOfRangeException("arrayIndex");
87 // Does the dimension in question have sufficient space to copy the expected number of entries?
88 // We perform this check before valid index check to ensure the exception message is in sync with
89 // the following snippet that uses regular framework code:
91 // ArrayList list = new ArrayList();
93 // Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 });
94 // list.CopyTo(items, 0);
96 if(srcLen > (destLen - (arrayIndex - destLB)))
97 throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
99 if(arrayIndex - destLB > destLen)
100 throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
102 // We need to verify the index as we;
103 IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
105 for (uint i = 0; i < srcLen; i++)
107 array.SetValue(_this.GetAt(i), i + arrayIndex);