File: MessageFormatter.cs

package info (click to toggle)
mono 2.6.7-5.1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 327,344 kB
  • ctags: 413,649
  • sloc: cs: 2,471,883; xml: 1,768,594; ansic: 350,665; sh: 13,644; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (520 lines) | stat: -rw-r--r-- 16,678 bytes parent folder | download | duplicates (2)
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
//
// System.Runtime.Remoting.MessageFormatter.cs
//
// Author: Lluis Sanchez Gual (lluis@ideary.com)
//
// (C) 2003, Lluis Sanchez Gual
//

//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Runtime.Remoting.Messaging;

namespace System.Runtime.Serialization.Formatters.Binary
{
	internal class MessageFormatter
	{
		public static void WriteMethodCall (BinaryWriter writer, object obj, Header[] headers, ISurrogateSelector surrogateSelector, StreamingContext context, FormatterAssemblyStyle assemblyFormat, FormatterTypeStyle typeFormat)
		{
			IMethodCallMessage call = (IMethodCallMessage)obj;
			writer.Write ((byte) BinaryElement.MethodCall);

			MethodFlags methodFlags;
			int infoArraySize = 0;
			object info = null;
			object[] extraProperties = null;

			if (call.LogicalCallContext != null && call.LogicalCallContext.HasInfo)
			{
				methodFlags = MethodFlags.IncludesLogicalCallContext;
				infoArraySize++;
			}
			else
				methodFlags = MethodFlags.ExcludeLogicalCallContext;

			if (RemotingServices.IsMethodOverloaded (call))
			{
				infoArraySize++;
				methodFlags |= MethodFlags.IncludesSignature;
			}

			if (call.Properties.Count > MethodCallDictionary.InternalKeys.Length)
			{
				extraProperties = GetExtraProperties (call.Properties, MethodCallDictionary.InternalKeys);
				infoArraySize++;
			}

#if NET_2_0
			if (call.MethodBase.IsGenericMethod) {
				infoArraySize++;
				methodFlags |= MethodFlags.GenericArguments;
			}
#endif
			if (call.ArgCount == 0)
				methodFlags |= MethodFlags.NoArguments;
			else {
				if (AllTypesArePrimitive (call.Args)) 
					methodFlags |= MethodFlags.PrimitiveArguments;
				else {
					if (infoArraySize == 0)
						methodFlags |= MethodFlags.ArgumentsInSimpleArray;
					else {
						methodFlags |= MethodFlags.ArgumentsInMultiArray;
						infoArraySize++;
					}
				}
			}

			writer.Write ((int) methodFlags);

			// Method name
			writer.Write ((byte) BinaryTypeCode.String);
			writer.Write (call.MethodName);

			// Class name
			writer.Write ((byte) BinaryTypeCode.String);
			writer.Write (call.TypeName);

			// Arguments

			if ((methodFlags & MethodFlags.PrimitiveArguments) > 0)
			{
				writer.Write ((uint)call.Args.Length);
				for (int n=0; n<call.ArgCount; n++)
				{
					object arg = call.GetArg(n);
					if (arg != null) {
						writer.Write (BinaryCommon.GetTypeCode (arg.GetType()));
						ObjectWriter.WritePrimitiveValue (writer, arg);
					}
					else
						writer.Write ((byte)BinaryTypeCode.Null);
				}
			}

			if ( infoArraySize > 0)
			{
				object[] ainfo = new object[infoArraySize];
				int n=0;
				if ((methodFlags & MethodFlags.ArgumentsInMultiArray) > 0) ainfo[n++] = call.Args;

#if NET_2_0
				if ((methodFlags & MethodFlags.GenericArguments) > 0) ainfo[n++] = call.MethodBase.GetGenericArguments ();
#endif

				if ((methodFlags & MethodFlags.IncludesSignature) > 0) ainfo[n++] = call.MethodSignature;
				if ((methodFlags & MethodFlags.IncludesLogicalCallContext) > 0) ainfo[n++] = call.LogicalCallContext;
				if (extraProperties != null) ainfo[n++] = extraProperties;
				info = ainfo;
			}
			else if ((methodFlags & MethodFlags.ArgumentsInSimpleArray) > 0)
				info = call.Args;

			if (info != null)
			{
				ObjectWriter objectWriter = new ObjectWriter (surrogateSelector, context, assemblyFormat, typeFormat);
				objectWriter.WriteObjectGraph (writer, info, headers);
			}
			else
				writer.Write ((byte) BinaryElement.End);
		}

		public static void WriteMethodResponse (BinaryWriter writer, object obj, Header[] headers, ISurrogateSelector surrogateSelector, StreamingContext context, FormatterAssemblyStyle assemblyFormat, FormatterTypeStyle typeFormat)
		{
			IMethodReturnMessage resp = (IMethodReturnMessage)obj;
			writer.Write ((byte) BinaryElement.MethodResponse);

			string[] internalProperties = MethodReturnDictionary.InternalReturnKeys;

			int infoArrayLength = 0;
			object info = null;
			object[] extraProperties = null;

			// Type of return value

			ReturnTypeTag returnTypeTag;
			MethodFlags contextFlag = MethodFlags.ExcludeLogicalCallContext;

			if (resp.Exception != null) {
				returnTypeTag = ReturnTypeTag.Exception | ReturnTypeTag.Null;
				internalProperties = MethodReturnDictionary.InternalExceptionKeys;
				infoArrayLength = 1;
			}
			else if (resp.ReturnValue == null) {
				returnTypeTag = ReturnTypeTag.Null;
			}
			else if (IsMethodPrimitive(resp.ReturnValue.GetType())) {
				returnTypeTag = ReturnTypeTag.PrimitiveType;
			}
			else {
				returnTypeTag = ReturnTypeTag.ObjectType;
				infoArrayLength++;
			}

			// Message flags

			MethodFlags formatFlag;

			if ((resp.LogicalCallContext != null) && resp.LogicalCallContext.HasInfo) 
			{
				contextFlag = MethodFlags.IncludesLogicalCallContext;
				infoArrayLength++;
			}

			if (resp.Properties.Count > internalProperties.Length && ((returnTypeTag & ReturnTypeTag.Exception) == 0))
			{
				extraProperties = GetExtraProperties (resp.Properties, internalProperties);
				infoArrayLength++;
			}

			if (resp.OutArgCount == 0)
				formatFlag = MethodFlags.NoArguments;
			else 
			{
				if (AllTypesArePrimitive (resp.Args)) 
					formatFlag = MethodFlags.PrimitiveArguments;
				else 
				{
					if (infoArrayLength == 0)
						formatFlag = MethodFlags.ArgumentsInSimpleArray; 
					else {
						formatFlag = MethodFlags.ArgumentsInMultiArray;
						infoArrayLength++;
					}
				}
			}

			writer.Write ((byte) (contextFlag | formatFlag));
			writer.Write ((byte) returnTypeTag);

			// FIXME: what are the following 2 bytes for?
			writer.Write ((byte) 0);
			writer.Write ((byte) 0);

			// Arguments

			if (returnTypeTag == ReturnTypeTag.PrimitiveType)
			{
				writer.Write (BinaryCommon.GetTypeCode (resp.ReturnValue.GetType()));
				ObjectWriter.WritePrimitiveValue (writer, resp.ReturnValue);
			}

			if (formatFlag == MethodFlags.PrimitiveArguments)
			{
				writer.Write ((uint)resp.ArgCount);
				for (int n=0; n<resp.ArgCount; n++)
				{
					object val = resp.GetArg(n);
					if (val != null) {
						writer.Write (BinaryCommon.GetTypeCode (val.GetType()));
						ObjectWriter.WritePrimitiveValue (writer, val);
					}
					else
						writer.Write ((byte)BinaryTypeCode.Null);
				}
			}

			if (infoArrayLength > 0)
			{
				object[] infoArray = new object[infoArrayLength];
				int n = 0;

				if ((returnTypeTag & ReturnTypeTag.Exception) != 0)
					infoArray[n++] = resp.Exception;
				
				if (formatFlag == MethodFlags.ArgumentsInMultiArray)
					infoArray[n++] = resp.Args;

				if (returnTypeTag == ReturnTypeTag.ObjectType)
					infoArray[n++] = resp.ReturnValue;

				if (contextFlag == MethodFlags.IncludesLogicalCallContext)
					infoArray[n++] = resp.LogicalCallContext;

				if (extraProperties != null)
					infoArray[n++] = extraProperties;

				info = infoArray;
			}
			else if ((formatFlag & MethodFlags.ArgumentsInSimpleArray) > 0)
				info = resp.Args;

			if (info != null)
			{
				ObjectWriter objectWriter = new ObjectWriter (surrogateSelector, context, assemblyFormat, typeFormat);
				objectWriter.WriteObjectGraph (writer, info, headers);
			}
			else
				writer.Write ((byte) BinaryElement.End);
		}

		public static object ReadMethodCall (BinaryReader reader, bool hasHeaders, HeaderHandler headerHandler, BinaryFormatter formatter)
		{
			BinaryElement elem = (BinaryElement)reader.ReadByte();	// The element code
			return ReadMethodCall (elem, reader, hasHeaders, headerHandler, formatter);
		}

		public static object ReadMethodCall (BinaryElement elem, BinaryReader reader, bool hasHeaders, HeaderHandler headerHandler, BinaryFormatter formatter)
		{
			if (elem != BinaryElement.MethodCall) throw new SerializationException("Invalid format. Expected BinaryElement.MethodCall, found " +  elem);

			MethodFlags flags = (MethodFlags) reader.ReadInt32();

			if (((BinaryTypeCode)reader.ReadByte()) != BinaryTypeCode.String) throw new SerializationException ("Invalid format");
			string methodName = reader.ReadString();

			if (((BinaryTypeCode)reader.ReadByte()) != BinaryTypeCode.String) throw new SerializationException ("Invalid format");
			string className = reader.ReadString();

			//bool hasContextInfo = (flags & MethodFlags.IncludesLogicalCallContext) > 0;

			object[] arguments = null;
			object methodSignature = null;
			object callContext = null;
			object[] extraProperties = null;
			Header[] headers = null;
#if NET_2_0
			Type[] genericArguments = null;
#endif

			if ((flags & MethodFlags.PrimitiveArguments) > 0)
			{
				uint count = reader.ReadUInt32();
				arguments = new object[count];
				for (int n=0; n<count; n++)
				{
					Type type = BinaryCommon.GetTypeFromCode (reader.ReadByte());
					arguments[n] = ObjectReader.ReadPrimitiveTypeValue (reader, type);
				}
			}

			if ((flags & MethodFlags.NeedsInfoArrayMask) > 0)
			{
				ObjectReader objectReader = new ObjectReader (formatter);

				object result;
				objectReader.ReadObjectGraph (reader, hasHeaders, out result, out headers);
				object[] msgInfo = (object[]) result;

				if ((flags & MethodFlags.ArgumentsInSimpleArray) > 0) {
					arguments = msgInfo;
				}
				else
				{
					int n = 0;
					if ((flags & MethodFlags.ArgumentsInMultiArray) > 0) {
						if (msgInfo.Length > 1) arguments = (object[]) msgInfo[n++];
						else arguments = new object[0];
					}

#if NET_2_0
					if ((flags & MethodFlags.GenericArguments) > 0)
						genericArguments = (Type[]) msgInfo[n++];
#endif

					if ((flags & MethodFlags.IncludesSignature) > 0)
						methodSignature = msgInfo[n++];

					if ((flags & MethodFlags.IncludesLogicalCallContext) > 0) 
						callContext = msgInfo[n++];

					if (n < msgInfo.Length)
						extraProperties = (object[]) msgInfo[n];
				}
			}
			else {
				reader.ReadByte ();	// Reads the stream ender
			}

			if (arguments == null) arguments = new object[0];

			string uri = null;
			if (headerHandler != null)
				uri = headerHandler(headers) as string;

#if NET_2_0
			Header[] methodInfo = new Header[7];
#else
			Header[] methodInfo = new Header[6];
#endif
			methodInfo[0] = new Header("__MethodName", methodName);
			methodInfo[1] = new Header("__MethodSignature", methodSignature);
			methodInfo[2] = new Header("__TypeName", className);
			methodInfo[3] = new Header("__Args", arguments);
			methodInfo[4] = new Header("__CallContext", callContext);
			methodInfo[5] = new Header("__Uri", uri);
#if NET_2_0
			methodInfo[6] = new Header("__GenericArguments", genericArguments);
#endif

			MethodCall call = new MethodCall (methodInfo);

			if (extraProperties != null) {
				foreach (DictionaryEntry entry in extraProperties)
					call.Properties [(string)entry.Key] = entry.Value;
			}

			return call;
		}

		public static object ReadMethodResponse (BinaryReader reader, bool hasHeaders, HeaderHandler headerHandler, IMethodCallMessage methodCallMessage, BinaryFormatter formatter)
		{
			BinaryElement elem = (BinaryElement) reader.ReadByte ();
			return ReadMethodResponse (elem, reader, hasHeaders, headerHandler, methodCallMessage, formatter);
		}

		public static object ReadMethodResponse (BinaryElement elem, BinaryReader reader, bool hasHeaders, HeaderHandler headerHandler, IMethodCallMessage methodCallMessage, BinaryFormatter formatter)
		{
			if (elem != BinaryElement.MethodResponse) throw new SerializationException("Invalid format. Expected BinaryElement.MethodResponse, found " +  elem);

			MethodFlags flags = (MethodFlags) reader.ReadByte ();
			ReturnTypeTag typeTag = (ReturnTypeTag) reader.ReadByte ();
			bool hasContextInfo = (flags & MethodFlags.IncludesLogicalCallContext) > 0;

			// FIXME: find a meaning for those 2 bytes
			reader.ReadByte();
			reader.ReadByte();

			object returnValue = null;
			object[] outArgs = null;
			LogicalCallContext callContext = null;
			Exception exception = null;
			object[] extraProperties = null;
			Header[] headers = null;

			if ((typeTag & ReturnTypeTag.PrimitiveType) > 0)
			{
				Type type = BinaryCommon.GetTypeFromCode (reader.ReadByte());
				returnValue = ObjectReader.ReadPrimitiveTypeValue (reader, type);
			}

			if ((flags & MethodFlags.PrimitiveArguments) > 0)
			{
				uint count = reader.ReadUInt32();
				outArgs = new object[count];
				for (int n=0; n<count; n++) {
					Type type = BinaryCommon.GetTypeFromCode (reader.ReadByte());
					outArgs[n] = ObjectReader.ReadPrimitiveTypeValue (reader, type);
				}
			}

			if (hasContextInfo || (typeTag & ReturnTypeTag.ObjectType) > 0 || 
				(typeTag & ReturnTypeTag.Exception) > 0 ||
				(flags & MethodFlags.ArgumentsInSimpleArray) > 0 || 
				(flags & MethodFlags.ArgumentsInMultiArray) > 0)
			{
				// There objects that need to be deserialized using an ObjectReader

				ObjectReader objectReader = new ObjectReader (formatter);
				object result;
				objectReader.ReadObjectGraph (reader, hasHeaders, out result, out headers);
				object[] msgInfo = (object[]) result;

				if ((typeTag & ReturnTypeTag.Exception) > 0) {
					exception = (Exception) msgInfo[0];
					if (hasContextInfo) callContext = (LogicalCallContext)msgInfo[1];
				}
				else if ((flags & MethodFlags.NoArguments) > 0 || (flags & MethodFlags.PrimitiveArguments) > 0) {
					int n = 0;
					if ((typeTag & ReturnTypeTag.ObjectType) > 0) returnValue = msgInfo [n++];
					if (hasContextInfo) callContext = (LogicalCallContext)msgInfo[n++];
					if (n < msgInfo.Length) extraProperties = (object[]) msgInfo[n];
				}
				else if ((flags & MethodFlags.ArgumentsInSimpleArray) > 0) {
					outArgs = msgInfo;
				}
				else {
					int n = 0;
					outArgs = (object[]) msgInfo[n++];
					if ((typeTag & ReturnTypeTag.ObjectType) > 0) returnValue = msgInfo[n++];
					if (hasContextInfo) callContext = (LogicalCallContext)msgInfo[n++];
					if (n < msgInfo.Length) extraProperties = (object[]) msgInfo[n];
				}
			}
			else {
				reader.ReadByte ();	// Reads the stream ender
			}

			if (headerHandler != null) 
				headerHandler(headers);

			if (exception != null)
				return new ReturnMessage (exception, methodCallMessage);
			else
			{
				int argCount = (outArgs!=null) ? outArgs.Length : 0;
				ReturnMessage result = new ReturnMessage (returnValue, outArgs, argCount, callContext, methodCallMessage);

				if (extraProperties != null) {
					foreach (DictionaryEntry entry in extraProperties)
						result.Properties [(string)entry.Key] = entry.Value;
				}

				return result;
			}
		}

		private static bool AllTypesArePrimitive(object[] objects)
		{
			foreach (object ob in objects) 
			{
				if (ob != null && !IsMethodPrimitive(ob.GetType())) 
					return false;
			}
			return true;
		}

		// When serializing methods, string are considered primitive types
		public static bool IsMethodPrimitive (Type type)
		{
			return type.IsPrimitive || type == typeof(string) || type == typeof (DateTime) || type == typeof (Decimal);
		}

		static object[] GetExtraProperties (IDictionary properties, string[] internalKeys)
		{
			object[] extraProperties = new object [properties.Count - internalKeys.Length];
			
			int n = 0;
			IDictionaryEnumerator e = properties.GetEnumerator();
			while (e.MoveNext())
				if (!IsInternalKey ((string) e.Entry.Key, internalKeys)) extraProperties [n++] = e.Entry;

			return extraProperties;
		}

		static bool IsInternalKey (string key, string[] internalKeys)
		{
			foreach (string ikey in internalKeys)
				if (key == ikey) return true;
			return false;
		}

	}
}