4 // Dick Porter (dick@ximian.com)
5 // Lluis Sanchez Gual (lluis@ideary.com)
7 // (C) 2002 Ximian, Inc. http://www.ximian.com
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Collections;
32 using System.Reflection;
33 using System.Runtime.InteropServices;
34 using System.Runtime.Remoting.Messaging;
35 using System.Security.Permissions;
37 namespace System.Runtime.Serialization.Formatters.Binary {
40 public sealed class BinaryFormatter :
46 private FormatterAssemblyStyle assembly_format = FormatterAssemblyStyle.Simple;
47 private SerializationBinder binder;
48 private StreamingContext context;
49 private ISurrogateSelector surrogate_selector;
50 private FormatterTypeStyle type_format = FormatterTypeStyle.TypesAlways;
51 private TypeFilterLevel filter_level = TypeFilterLevel.Full;
53 public BinaryFormatter()
55 surrogate_selector=DefaultSurrogateSelector;
56 context=new StreamingContext(StreamingContextStates.All);
59 public BinaryFormatter(ISurrogateSelector selector, StreamingContext context)
61 surrogate_selector=selector;
66 // Deserializing objects of type Dictionary<,> List<> and friends does not work in a CoreCLR sandbox, because
67 // the default deserialization code uses reflection to do its job, and the fields being reflected on live in mscorlib.dll.
68 // DefaultSurrogateSelector enables embedders to provide an alternative method of deserializing specific types in a way
69 // that does not violate the CoreCLR rules. See https://gist.github.com/878267 for some actual code that provides CoreCLR safe
70 // deserialization code for List<> and Dictionary<,>.
71 // DefaultSurrogateSelector is private, and needs to be set by the embedder trough reflection, so we do not expose any public
72 // API point that is not present in .NET
73 static ISurrogateSelector DefaultSurrogateSelector { get; set; }
75 public FormatterAssemblyStyle AssemblyFormat
78 return(assembly_format);
81 assembly_format=value;
85 public SerializationBinder Binder
95 public StreamingContext Context
105 public ISurrogateSelector SurrogateSelector
108 return(surrogate_selector);
111 surrogate_selector=value;
115 public FormatterTypeStyle TypeFormat
125 public TypeFilterLevel FilterLevel
127 get { return filter_level; }
128 set { filter_level = value; }
131 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
132 public object Deserialize (Stream serializationStream)
134 return NoCheckDeserialize (serializationStream, null);
137 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
138 public object Deserialize (Stream serializationStream, HeaderHandler handler)
140 return NoCheckDeserialize (serializationStream, handler);
143 // shared by Deserialize and UnsafeDeserialize which both involve different security checks
144 private object NoCheckDeserialize (Stream serializationStream, HeaderHandler handler)
146 if(serializationStream==null)
148 throw new ArgumentNullException("serializationStream");
150 if(serializationStream.CanSeek &&
151 serializationStream.Length==0)
153 throw new SerializationException("serializationStream supports seeking, but its length is 0");
156 BinaryReader reader = new BinaryReader (serializationStream);
159 ReadBinaryHeader (reader, out hasHeader);
161 // Messages are read using a special static method, which does not use ObjectReader
162 // if it is not needed. This saves time and memory.
164 BinaryElement elem = (BinaryElement) reader.Read ();
166 if (elem == BinaryElement.MethodCall) {
167 return MessageFormatter.ReadMethodCall (elem, reader, hasHeader, handler, this);
169 else if (elem == BinaryElement.MethodResponse) {
170 return MessageFormatter.ReadMethodResponse (elem, reader, hasHeader, handler, null, this);
173 ObjectReader serializer = new ObjectReader (this);
177 serializer.ReadObjectGraph (elem, reader, hasHeader, out result, out headers);
178 if (handler != null) handler(headers);
183 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
184 public object DeserializeMethodResponse (Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage)
186 return NoCheckDeserializeMethodResponse (serializationStream, handler, methodCallMessage);
189 // shared by DeserializeMethodResponse and UnsafeDeserializeMethodResponse which both involve different security checks
190 private object NoCheckDeserializeMethodResponse (Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage)
192 if(serializationStream==null) {
193 throw new ArgumentNullException("serializationStream");
195 if(serializationStream.CanSeek &&
196 serializationStream.Length==0) {
197 throw new SerializationException("serializationStream supports seeking, but its length is 0");
200 BinaryReader reader = new BinaryReader (serializationStream);
203 ReadBinaryHeader (reader, out hasHeader);
204 return MessageFormatter.ReadMethodResponse (reader, hasHeader, handler, methodCallMessage, this);
207 public void Serialize(Stream serializationStream, object graph)
209 Serialize (serializationStream, graph, null);
212 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
213 public void Serialize(Stream serializationStream, object graph, Header[] headers)
215 if(serializationStream==null) {
216 throw new ArgumentNullException ("serializationStream");
219 BinaryWriter writer = new BinaryWriter (serializationStream);
220 WriteBinaryHeader (writer, headers!=null);
222 if (graph is IMethodCallMessage) {
223 MessageFormatter.WriteMethodCall (writer, graph, headers, this);
225 else if (graph is IMethodReturnMessage) {
226 MessageFormatter.WriteMethodResponse (writer, graph, headers, this);
229 ObjectWriter serializer = new ObjectWriter (this);
230 serializer.WriteObjectGraph (writer, graph, headers);
235 // faster version (under CAS) as this requires a LinkDemand versus full Demand (i.e. a stack-walk)
236 // shouldn't be called unless the code is intended to be executed at full-trust
238 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
239 public object UnsafeDeserialize (Stream serializationStream, HeaderHandler handler)
241 return NoCheckDeserialize (serializationStream, handler);
244 // faster version (under CAS) as this requires a LinkDemand versus full Demand (i.e. a stack-walk)
245 // shouldn't be called unless the code is intended to be executed at full-trust
247 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
248 public object UnsafeDeserializeMethodResponse (Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage)
250 return NoCheckDeserializeMethodResponse (serializationStream, handler, methodCallMessage);
253 private void WriteBinaryHeader (BinaryWriter writer, bool hasHeaders)
255 writer.Write ((byte)BinaryElement.Header);
256 writer.Write ((int)1);
257 if (hasHeaders) writer.Write ((int)2);
258 else writer.Write ((int)-1);
259 writer.Write ((int)1);
260 writer.Write ((int)0);
263 private void ReadBinaryHeader (BinaryReader reader, out bool hasHeaders)
267 int val = reader.ReadInt32();
268 hasHeaders = (val==2);