Merge pull request #1229 from andreiagaita/master
[mono.git] / mcs / class / corlib / System.Runtime.Serialization / FormatterServices.cs
1 //
2 // System.Runtime.Serialization.FormatterServices
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002 Ximian, Inc (http://www.ximian.com)
8 //
9
10 //
11 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32 using System;
33 using System.Collections;
34 using System.Reflection;
35 using System.Runtime.CompilerServices;
36 using System.Runtime.InteropServices;
37 using System.Runtime.Serialization.Formatters;
38 using System.Globalization;
39
40 namespace System.Runtime.Serialization
41 {
42         [System.Runtime.InteropServices.ComVisibleAttribute (true)]
43 #if NET_4_5
44         static
45 #else
46         sealed
47 #endif
48         public class FormatterServices
49         {
50                 private const BindingFlags fieldFlags = BindingFlags.Public |
51                                                         BindingFlags.Instance |
52                                                         BindingFlags.NonPublic |
53                                                         BindingFlags.DeclaredOnly;
54
55 #if !NET_4_5
56                 private FormatterServices ()
57                 {
58                 }
59 #endif
60
61                 public static object [] GetObjectData (object obj, MemberInfo [] members)
62                 {
63                         if (obj == null)
64                                 throw new ArgumentNullException ("obj");
65
66                         if (members == null)
67                                 throw new ArgumentNullException ("members");
68
69                         int n = members.Length;
70                         object [] result = new object [n];
71                         for (int i = 0; i < n; i++) {
72                                 MemberInfo member = members [i];
73                                 if (member == null)
74                                         throw new ArgumentNullException (String.Format ("members[{0}]", i));
75
76                                 if (member.MemberType != MemberTypes.Field)
77                                         throw new SerializationException (
78                                                         String.Format ("members [{0}] is not a field.", i));
79
80                                 FieldInfo fi = member as FieldInfo; // members must be fields
81                                 result [i] = fi.GetValue (obj);
82                         }
83
84                         return result;
85                 }
86
87                 public static MemberInfo [] GetSerializableMembers (Type type)
88                 {
89                         StreamingContext st = new StreamingContext (StreamingContextStates.All);
90                         return GetSerializableMembers (type, st);
91                 }
92
93                 public static MemberInfo [] GetSerializableMembers (Type type, StreamingContext context)
94                 {
95                         if (type == null)
96                                 throw new ArgumentNullException ("type");
97
98                         //FIXME: context?
99                         ArrayList fields = new ArrayList ();
100                         Type t = type;
101                         while (t != null) {
102                                 if (!t.IsSerializable) {
103                                         string msg = String.Format ("Type {0} in assembly {1} is not " +
104                                                                     "marked as serializable.",
105                                                                     t, t.Assembly.FullName);
106
107                                         throw new SerializationException (msg);
108                                 }
109
110                                 GetFields (type, t, fields);
111                                 t = t.BaseType;
112                         }
113
114                         MemberInfo [] result = new MemberInfo [fields.Count];
115                         fields.CopyTo (result);
116                         return result;
117                 }
118
119                 private static void GetFields (Type reflectedType, Type type, ArrayList fields)
120                 {
121                         FieldInfo [] fs = type.GetFields (fieldFlags);
122                         foreach (FieldInfo field in fs)
123                                 if (!(field.IsNotSerialized)) {
124                                         MonoField mf = field as MonoField;
125                                         if (mf != null && reflectedType != type && !mf.IsPublic) {
126                                                 string fname = type.Name + "+" + mf.Name;
127                                                 fields.Add (mf.Clone (fname));
128                                         }
129                                         else
130                                                 fields.Add (field);
131                                 }
132                 }
133
134                 public static Type GetTypeFromAssembly (Assembly assem, string name)
135                 {
136                         if (assem == null)
137                                 throw new ArgumentNullException ("assem");
138
139                         if (name == null)
140                                 throw new ArgumentNullException ("name");
141
142                         return assem.GetType (name);
143                 }
144
145                 public static object GetUninitializedObject (Type type)
146                 {
147                         if (type == null)
148                                 throw new ArgumentNullException ("type");
149
150                         if (type == typeof (string))
151                                 throw new ArgumentException ("Uninitialized Strings cannot be created.");
152
153                         return System.Runtime.Remoting.Activation.ActivationServices.AllocateUninitializedClassInstance (type);
154                 }
155
156                 public static object PopulateObjectMembers (object obj, MemberInfo [] members, object [] data)
157                 {
158                         if (obj == null)
159                                 throw new ArgumentNullException ("obj");
160
161                         if (members == null)
162                                 throw new ArgumentNullException ("members");
163
164                         if (data == null)
165                                 throw new ArgumentNullException ("data");
166
167                         int length = members.Length;
168                         if (length != data.Length)
169                                 throw new ArgumentException ("different length in members and data");
170
171                         for (int i = 0; i < length; i++) {
172                                 MemberInfo member = members [i];
173                                 if (member == null)
174                                         throw new ArgumentNullException (String.Format ("members[{0}]", i));
175                                         
176                                 if (member.MemberType != MemberTypes.Field)
177                                         throw new SerializationException (
178                                                         String.Format ("members [{0}] is not a field.", i));
179
180                                 FieldInfo fi = member as FieldInfo; // members must be fields
181                                 fi.SetValue (obj, data [i]);
182                         }
183
184                         return obj;
185                 }
186                 
187
188                 public static void CheckTypeSecurity (Type t, TypeFilterLevel securityLevel)
189                 {
190                         if (securityLevel == TypeFilterLevel.Full) return;
191                         CheckNotAssignable (typeof(System.DelegateSerializationHolder), t);
192                         CheckNotAssignable (typeof(System.Runtime.Remoting.Lifetime.ISponsor), t);
193                         CheckNotAssignable (typeof(System.Runtime.Remoting.IEnvoyInfo), t);
194                         CheckNotAssignable (typeof(System.Runtime.Remoting.ObjRef), t);
195                 }
196                 
197                 static void CheckNotAssignable (Type basetype, Type type)
198                 {
199                         if (basetype.IsAssignableFrom (type)) {
200                                 string msg = "Type " + basetype + " and the types derived from it";
201                                 msg += " (such as " + type + ") are not permitted to be deserialized at this security level";
202                                 throw new System.Security.SecurityException (msg);
203                         }
204                 }
205
206                 public static object GetSafeUninitializedObject (Type type)
207                 {
208                         // FIXME: MS.NET uses code access permissions to check if the caller is
209                         // allowed to create an instance of this type. We can't support this
210                         // because it is not implemented in mono.
211                         
212                         // In concrete, the it will request a SecurityPermission of 
213                         // type "Infrastructure".
214                         
215                         return GetUninitializedObject (type);
216                 }
217
218 #if NET_4_0
219                 // This method was introduced in .Net due to a bug serializing objects with circular references
220                 // which we don't appear to have, so we just return the same object.
221                 // See http://support.microsoft.com/kb/927495/en-us/ in case of doubt.
222                 [ComVisible (false)]
223                 public static ISerializationSurrogate GetSurrogateForCyclicalReference (ISerializationSurrogate innerSurrogate)
224                 {
225                         return innerSurrogate;
226                 }
227 #endif
228         }
229 }