mscorlib(4.0.0.0) API with additions
FormatterServices.cs
1 using System.Collections;
5 using System.Reflection;
13 using System.Security;
14 using System.Text;
15 
17 {
19  [ComVisible(true)]
20  public static class FormatterServices
21  {
22  internal static ConcurrentDictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable;
23 
24  [SecurityCritical]
25  private static bool unsafeTypeForwardersIsEnabled;
26 
27  [SecurityCritical]
28  private static volatile bool unsafeTypeForwardersIsEnabledInitialized;
29 
30  private static readonly Type[] advancedTypes;
31 
32  private static Binder s_binder;
33 
34  [SecuritySafeCritical]
35  static FormatterServices()
36  {
37  m_MemberInfoTable = new ConcurrentDictionary<MemberHolder, MemberInfo[]>();
38  unsafeTypeForwardersIsEnabled = false;
39  unsafeTypeForwardersIsEnabledInitialized = false;
40  advancedTypes = new Type[4]
41  {
42  typeof(DelegateSerializationHolder),
43  typeof(ObjRef),
44  typeof(IEnvoyInfo),
45  typeof(ISponsor)
46  };
47  s_binder = Type.DefaultBinder;
48  }
49 
50  private static MemberInfo[] GetSerializableMembers(RuntimeType type)
51  {
52  FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
53  int num = 0;
54  for (int i = 0; i < fields.Length; i++)
55  {
56  if ((fields[i].Attributes & FieldAttributes.NotSerialized) != FieldAttributes.NotSerialized)
57  {
58  num++;
59  }
60  }
61  if (num != fields.Length)
62  {
63  FieldInfo[] array = new FieldInfo[num];
64  num = 0;
65  for (int j = 0; j < fields.Length; j++)
66  {
67  if ((fields[j].Attributes & FieldAttributes.NotSerialized) != FieldAttributes.NotSerialized)
68  {
69  array[num] = fields[j];
70  num++;
71  }
72  }
73  return array;
74  }
75  return fields;
76  }
77 
78  private static bool CheckSerializable(RuntimeType type)
79  {
80  if (type.IsSerializable)
81  {
82  return true;
83  }
84  return false;
85  }
86 
87  private static MemberInfo[] InternalGetSerializableMembers(RuntimeType type)
88  {
89  List<SerializationFieldInfo> list = null;
90  if (type.IsInterface)
91  {
92  return new MemberInfo[0];
93  }
94  if (!CheckSerializable(type))
95  {
96  throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", type.FullName, type.Module.Assembly.FullName));
97  }
98  MemberInfo[] array = GetSerializableMembers(type);
99  RuntimeType runtimeType = (RuntimeType)type.BaseType;
100  if (runtimeType != null && runtimeType != (RuntimeType)typeof(object))
101  {
102  RuntimeType[] parentTypes = null;
103  int parentTypeCount = 0;
104  bool parentTypes2 = GetParentTypes(runtimeType, out parentTypes, out parentTypeCount);
105  if (parentTypeCount > 0)
106  {
107  list = new List<SerializationFieldInfo>();
108  for (int i = 0; i < parentTypeCount; i++)
109  {
110  runtimeType = parentTypes[i];
111  if (!CheckSerializable(runtimeType))
112  {
113  throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", runtimeType.FullName, runtimeType.Module.Assembly.FullName));
114  }
115  FieldInfo[] fields = runtimeType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
116  string namePrefix = parentTypes2 ? runtimeType.Name : runtimeType.FullName;
117  FieldInfo[] array2 = fields;
118  foreach (FieldInfo fieldInfo in array2)
119  {
120  if (!fieldInfo.IsNotSerialized)
121  {
122  list.Add(new SerializationFieldInfo((RuntimeFieldInfo)fieldInfo, namePrefix));
123  }
124  }
125  }
126  if (list != null && list.Count > 0)
127  {
128  MemberInfo[] array3 = new MemberInfo[list.Count + array.Length];
129  Array.Copy(array, array3, array.Length);
130  ((ICollection)list).CopyTo((Array)array3, array.Length);
131  array = array3;
132  }
133  }
134  }
135  return array;
136  }
137 
138  private static bool GetParentTypes(RuntimeType parentType, out RuntimeType[] parentTypes, out int parentTypeCount)
139  {
140  parentTypes = null;
141  parentTypeCount = 0;
142  bool flag = true;
143  RuntimeType right = (RuntimeType)typeof(object);
144  RuntimeType runtimeType = parentType;
145  while (runtimeType != right)
146  {
147  if (!runtimeType.IsInterface)
148  {
149  string name = runtimeType.Name;
150  int num = 0;
151  while (flag && num < parentTypeCount)
152  {
153  string name2 = parentTypes[num].Name;
154  if (name2.Length == name.Length && name2[0] == name[0] && name == name2)
155  {
156  flag = false;
157  break;
158  }
159  num++;
160  }
161  if (parentTypes == null || parentTypeCount == parentTypes.Length)
162  {
163  RuntimeType[] array = new RuntimeType[Math.Max(parentTypeCount * 2, 12)];
164  if (parentTypes != null)
165  {
166  Array.Copy(parentTypes, 0, array, 0, parentTypeCount);
167  }
168  parentTypes = array;
169  }
170  parentTypes[parentTypeCount++] = runtimeType;
171  }
172  runtimeType = (RuntimeType)runtimeType.BaseType;
173  }
174  return flag;
175  }
176 
182  [SecurityCritical]
183  public static MemberInfo[] GetSerializableMembers(Type type)
184  {
185  return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All));
186  }
187 
194  [SecurityCritical]
196  {
197  if ((object)type == null)
198  {
199  throw new ArgumentNullException("type");
200  }
201  if (!(type is RuntimeType))
202  {
203  throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
204  }
205  MemberHolder key = new MemberHolder(type, context);
206  return m_MemberInfoTable.GetOrAdd(key, (MemberHolder _) => InternalGetSerializableMembers((RuntimeType)type));
207  }
208 
213  public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel)
214  {
215  if (securityLevel != TypeFilterLevel.Low)
216  {
217  return;
218  }
219  int num = 0;
220  while (true)
221  {
222  if (num < advancedTypes.Length)
223  {
224  if (advancedTypes[num].IsAssignableFrom(t))
225  {
226  break;
227  }
228  num++;
229  continue;
230  }
231  return;
232  }
233  throw new SecurityException(Environment.GetResourceString("Serialization_TypeSecurity", advancedTypes[num].FullName, t.FullName));
234  }
235 
241  [SecurityCritical]
242  public static object GetUninitializedObject(Type type)
243  {
244  if ((object)type == null)
245  {
246  throw new ArgumentNullException("type");
247  }
248  if (!(type is RuntimeType))
249  {
250  throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
251  }
252  return nativeGetUninitializedObject((RuntimeType)type);
253  }
254 
261  [SecurityCritical]
262  public static object GetSafeUninitializedObject(Type type)
263  {
264  if ((object)type == null)
265  {
266  throw new ArgumentNullException("type");
267  }
268  if (!(type is RuntimeType))
269  {
270  throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
271  }
272  if ((object)type == typeof(ConstructionCall) || (object)type == typeof(LogicalCallContext) || (object)type == typeof(SynchronizationAttribute))
273  {
274  return nativeGetUninitializedObject((RuntimeType)type);
275  }
276  try
277  {
278  return nativeGetSafeUninitializedObject((RuntimeType)type);
279  }
280  catch (SecurityException innerException)
281  {
282  throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), innerException);
283  }
284  }
285 
286  [MethodImpl(MethodImplOptions.InternalCall)]
287  [SecurityCritical]
288  private static extern object nativeGetSafeUninitializedObject(RuntimeType type);
289 
290  [MethodImpl(MethodImplOptions.InternalCall)]
291  [SecurityCritical]
292  private static extern object nativeGetUninitializedObject(RuntimeType type);
293 
294  [MethodImpl(MethodImplOptions.InternalCall)]
295  [SecurityCritical]
296  private static extern bool GetEnableUnsafeTypeForwarders();
297 
298  [SecuritySafeCritical]
299  internal static bool UnsafeTypeForwardersIsEnabled()
300  {
301  if (!unsafeTypeForwardersIsEnabledInitialized)
302  {
303  unsafeTypeForwardersIsEnabled = GetEnableUnsafeTypeForwarders();
304  unsafeTypeForwardersIsEnabledInitialized = true;
305  }
306  return unsafeTypeForwardersIsEnabled;
307  }
308 
309  [SecurityCritical]
310  internal static void SerializationSetValue(MemberInfo fi, object target, object value)
311  {
312  RtFieldInfo rtFieldInfo = fi as RtFieldInfo;
313  if (rtFieldInfo != null)
314  {
315  rtFieldInfo.CheckConsistency(target);
316  rtFieldInfo.UnsafeSetValue(target, value, BindingFlags.Default, s_binder, null);
317  return;
318  }
319  SerializationFieldInfo serializationFieldInfo = fi as SerializationFieldInfo;
320  if (serializationFieldInfo != null)
321  {
322  serializationFieldInfo.InternalSetValue(target, value, BindingFlags.Default, s_binder, null);
323  return;
324  }
325  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldInfo"));
326  }
327 
337  [SecurityCritical]
338  public static object PopulateObjectMembers(object obj, MemberInfo[] members, object[] data)
339  {
340  if (obj == null)
341  {
342  throw new ArgumentNullException("obj");
343  }
344  if (members == null)
345  {
346  throw new ArgumentNullException("members");
347  }
348  if (data == null)
349  {
350  throw new ArgumentNullException("data");
351  }
352  if (members.Length != data.Length)
353  {
354  throw new ArgumentException(Environment.GetResourceString("Argument_DataLengthDifferent"));
355  }
356  for (int i = 0; i < members.Length; i++)
357  {
358  MemberInfo memberInfo = members[i];
359  if (memberInfo == null)
360  {
361  throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i));
362  }
363  if (data[i] != null)
364  {
365  if (memberInfo.MemberType != MemberTypes.Field)
366  {
367  throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo"));
368  }
369  SerializationSetValue(memberInfo, obj, data[i]);
370  }
371  }
372  return obj;
373  }
374 
381  [SecurityCritical]
382  public static object[] GetObjectData(object obj, MemberInfo[] members)
383  {
384  if (obj == null)
385  {
386  throw new ArgumentNullException("obj");
387  }
388  if (members == null)
389  {
390  throw new ArgumentNullException("members");
391  }
392  int num = members.Length;
393  object[] array = new object[num];
394  for (int i = 0; i < num; i++)
395  {
396  MemberInfo memberInfo = members[i];
397  if (memberInfo == null)
398  {
399  throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i));
400  }
401  if (memberInfo.MemberType == MemberTypes.Field)
402  {
403  RtFieldInfo rtFieldInfo = memberInfo as RtFieldInfo;
404  if (rtFieldInfo != null)
405  {
406  rtFieldInfo.CheckConsistency(obj);
407  array[i] = rtFieldInfo.UnsafeGetValue(obj);
408  }
409  else
410  {
411  array[i] = ((SerializationFieldInfo)memberInfo).InternalGetValue(obj);
412  }
413  continue;
414  }
415  throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo"));
416  }
417  return array;
418  }
419 
423  [SecurityCritical]
424  [ComVisible(false)]
426  {
427  if (innerSurrogate == null)
428  {
429  throw new ArgumentNullException("innerSurrogate");
430  }
431  return new SurrogateForCyclicalReference(innerSurrogate);
432  }
433 
440  [SecurityCritical]
441  public static Type GetTypeFromAssembly(Assembly assem, string name)
442  {
443  if (assem == null)
444  {
445  throw new ArgumentNullException("assem");
446  }
447  return assem.GetType(name, throwOnError: false, ignoreCase: false);
448  }
449 
450  internal static Assembly LoadAssemblyFromString(string assemblyName)
451  {
452  return Assembly.Load(assemblyName);
453  }
454 
455  internal static Assembly LoadAssemblyFromStringNoThrow(string assemblyName)
456  {
457  try
458  {
459  return LoadAssemblyFromString(assemblyName);
460  }
461  catch (Exception)
462  {
463  }
464  return null;
465  }
466 
467  internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom)
468  {
469  if ((object)type == null)
470  {
471  throw new ArgumentNullException("type");
472  }
473  object[] customAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), inherit: false);
474  if (customAttributes != null && customAttributes.Length != 0)
475  {
476  hasTypeForwardedFrom = true;
477  TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)customAttributes[0];
478  return typeForwardedFromAttribute.AssemblyFullName;
479  }
480  hasTypeForwardedFrom = false;
481  return type.Assembly.FullName;
482  }
483 
484  internal static string GetClrTypeFullName(Type type)
485  {
486  if (type.IsArray)
487  {
488  return GetClrTypeFullNameForArray(type);
489  }
490  return GetClrTypeFullNameForNonArrayTypes(type);
491  }
492 
493  private static string GetClrTypeFullNameForArray(Type type)
494  {
495  int arrayRank = type.GetArrayRank();
496  if (arrayRank == 1)
497  {
498  return string.Format(CultureInfo.InvariantCulture, "{0}{1}", GetClrTypeFullName(type.GetElementType()), "[]");
499  }
500  StringBuilder stringBuilder = new StringBuilder(GetClrTypeFullName(type.GetElementType())).Append("[");
501  for (int i = 1; i < arrayRank; i++)
502  {
503  stringBuilder.Append(",");
504  }
505  stringBuilder.Append("]");
506  return stringBuilder.ToString();
507  }
508 
509  private static string GetClrTypeFullNameForNonArrayTypes(Type type)
510  {
511  if (!type.IsGenericType)
512  {
513  return type.FullName;
514  }
515  Type[] genericArguments = type.GetGenericArguments();
516  StringBuilder stringBuilder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("[");
517  Type[] array = genericArguments;
518  foreach (Type type2 in array)
519  {
520  stringBuilder.Append("[").Append(GetClrTypeFullName(type2)).Append(", ");
521  stringBuilder.Append(GetClrAssemblyName(type2, out bool _)).Append("],");
522  }
523  return stringBuilder.Remove(stringBuilder.Length - 1, 1).Append("]").ToString();
524  }
525  }
526 }
Obtains information about the attributes of a member and provides access to member metadata.
Definition: MemberInfo.cs:14
bool IsNotSerialized
Gets a value indicating whether this field has the NotSerialized attribute.
Definition: FieldInfo.cs:168
static CultureInfo InvariantCulture
Gets the T:System.Globalization.CultureInfo object that is culture-independent (invariant).
Definition: CultureInfo.cs:263
static object PopulateObjectMembers(object obj, MemberInfo[] members, object[] data)
Populates the specified object with values for each field drawn from the data array of objects.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
TypeFilterLevel
Specifies the level of automatic deserialization for .NET Framework remoting.
unsafe override string ToString()
Converts the value of this instance to a T:System.String.
Indicates that the implementer wants to be a lifetime lease sponsor.
Definition: ISponsor.cs:8
static Assembly Load(string assemblyString)
Loads an assembly given the long form of its name.
Definition: Assembly.cs:507
static object GetUninitializedObject(Type type)
Creates a new instance of the specified object type.
abstract string FullName
Gets the fully qualified name of the type, including its namespace but not its assembly.
Definition: Type.cs:153
static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate)
Returns a serialization surrogate for the specified T:System.Runtime.Serialization....
Discovers the attributes of a field and provides access to field metadata.
Definition: FieldInfo.cs:15
BindingFlags
Specifies flags that control binding and the way in which the search for members and types is conduct...
Definition: BindingFlags.cs:10
Definition: __Canon.cs:3
override string ToString()
Returns a String representing the name of the current Type.
Definition: Type.cs:2788
Stores all relevant information required to generate a proxy in order to communicate with a remote ob...
Definition: ObjRef.cs:19
string AssemblyFullName
Gets the assembly-qualified name of the source type.
Describes the source and destination of a given serialized stream, and provides an additional caller-...
static Binder DefaultBinder
Gets a reference to the default binder, which implements internal rules for selecting the appropriate...
Definition: Type.cs:109
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
Specifies a source T:System.Type in another assembly.
StringBuilder Append(char value, int repeatCount)
Appends a specified number of copies of the string representation of a Unicode character to this inst...
TValue GetOrAdd(TKey key, Func< TKey, TValue > valueFactory)
Adds a key/value pair to the T:System.Collections.Concurrent.ConcurrentDictionary`2 by using the spec...
static sbyte Max(sbyte val1, sbyte val2)
Returns the larger of two 8-bit signed integers.
Definition: Math.cs:581
FieldAttributes
Specifies flags that describe the attributes of a field.
int Length
Gets or sets the length of the current T:System.Text.StringBuilder object.
Opens the file if it exists and seeks to the end of the file, or creates a new file....
static MemberInfo [] GetSerializableMembers(Type type, StreamingContext context)
Gets all the serializable members for a class of the specified T:System.Type and in the provided T:Sy...
Represents an assembly, which is a reusable, versionable, and self-describing building block of a com...
Definition: Assembly.cs:22
Implements a serialization surrogate selector that allows one object to perform serialization and des...
static object [] GetObjectData(object obj, MemberInfo[] members)
Extracts the data from the specified object and returns it as an array of objects.
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the ba...
Definition: Array.cs:17
Represents type declarations: class types, interface types, array types, value types,...
Definition: Type.cs:18
The exception thrown when an error occurs during serialization or deserialization.
static Type GetTypeFromAssembly(Assembly assem, string name)
Looks up the T:System.Type of the specified object in the provided T:System.Reflection....
MethodImplOptions
Defines the details of how a method is implemented.
abstract string Name
Gets the name of the current member.
Definition: MemberInfo.cs:27
static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel)
Determines whether the specified T:System.Type can be deserialized with the T:System....
Provides a set of properties that are carried with the execution code path during remote method calls...
Selects a member from a list of candidates, and performs type conversion from actual argument type to...
Definition: Binder.cs:10
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
The exception that is thrown when one of the arguments provided to a method is not valid.
static void Copy(Array sourceArray, Array destinationArray, int length)
Copies a range of elements from an T:System.Array starting at the first element and pastes them into ...
Definition: Array.cs:1275
Provides envoy information.
Definition: IEnvoyInfo.cs:9
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search...
Definition: List.cs:14
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
static object GetSafeUninitializedObject(Type type)
Creates a new instance of the specified object type.
static MemberInfo [] GetSerializableMembers(Type type)
Gets all the serializable members for a class of the specified T:System.Type.
abstract MemberTypes MemberType
When overridden in a derived class, gets a T:System.Reflection.MemberTypes value indicating the type ...
Definition: MemberInfo.cs:19
StreamingContextStates
Defines a set of flags that specifies the source or destination context for the stream during seriali...
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
Provides constants and static methods for trigonometric, logarithmic, and other common mathematical f...
Definition: Math.cs:10
Defines size, enumerators, and synchronization methods for all nongeneric collections.
Definition: ICollection.cs:8
MemberTypes
Marks each type of member that is defined as a derived class of T:System.Reflection....
Definition: MemberTypes.cs:9
Provides static methods to aid with the implementation of a T:System.Runtime.Serialization....
Implements the T:System.Runtime.Remoting.Activation.IConstructionCallMessage interface to create a re...
The exception that is thrown when a security error is detected.
Enforces a synchronization domain for the current context and all contexts that share the same instan...
StringBuilder Remove(int startIndex, int length)
Removes the specified range of characters from this instance.