File: ResourceReader.cs

package info (click to toggle)
mono 1.2.2.1-1
  • links: PTS
  • area: main
  • in suites: etch-m68k
  • size: 142,728 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,304; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (522 lines) | stat: -rw-r--r-- 13,972 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
521
522
//
// System.Resources.ResourceReader.cs
//
// Authors: 
// 	Duncan Mak <duncan@ximian.com>
//	Nick Drochak <ndrochak@gol.com>
//	Dick Porter <dick@ximian.com>
//	Marek Safar <marek.safar@seznam.cz>
//
// (C) 2001, 2002 Ximian Inc, http://www.ximian.com
// Copyright (C) 2004-2005 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.Collections;
using System.Resources;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;

namespace System.Resources
{
	internal enum PredefinedResourceType
	{
		Null		= 0,
		String		= 1,
		Bool		= 2,
		Char		= 3,
		Byte		= 4,
		SByte		= 5,
		Int16		= 6,
		UInt16		= 7,
		Int32		= 8,
		UInt32		= 9,
		Int64		= 10,
		UInt64		= 11,
		Single		= 12,
		Double		= 13,
		Decimal		= 14,
		DateTime	= 15,
		TimeSpan	= 16,
		ByteArray	= 32,
		Stream		= 33,
		FistCustom	= 64
	}

	public sealed class ResourceReader : IResourceReader, IEnumerable, IDisposable
	{
		BinaryReader reader;
		IFormatter formatter;
		internal int resourceCount = 0;
		int typeCount = 0;
		Type[] types;
		int[] hashes;
		long[] positions;
		int dataSectionOffset;
		long nameSectionOffset;
		int resource_ver;
		
		// Constructors
		[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
		public ResourceReader (Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException ("Value cannot be null.");
			
			if (!stream.CanRead)
				throw new ArgumentException ("Stream was not readable.");

			reader = new BinaryReader(stream, Encoding.UTF8);
			formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File|StreamingContextStates.Persistence));
			
			ReadHeaders();
		}
		
		public ResourceReader (string fileName)
		{
			if (fileName == null)
				throw new ArgumentNullException ("Path cannot be null.");

			if (!System.IO.File.Exists (fileName)) 
				throw new FileNotFoundException ("Could not find file " + Path.GetFullPath(fileName));

			reader = new BinaryReader (new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read));
			formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File|StreamingContextStates.Persistence));

			ReadHeaders();
		}
		
		/* Read the ResourceManager header and the
		 * ResourceReader header.
		 */
		private void ReadHeaders()
		{
			try {
				int manager_magic = reader.ReadInt32();

				if(manager_magic != ResourceManager.MagicNumber) {
					throw new ArgumentException("Stream is not a valid .resources file!");
				}

				int manager_ver = reader.ReadInt32();
				int manager_len = reader.ReadInt32();
				
				/* We know how long the header is, even if
				 * the version number is too new
				 */
				if(manager_ver > ResourceManager.HeaderVersionNumber) {
					reader.BaseStream.Seek(manager_len, SeekOrigin.Current);
				} else {
					string reader_class=reader.ReadString();
					if(!reader_class.StartsWith("System.Resources.ResourceReader")) {
						throw new NotSupportedException("This .resources file requires reader class " + reader_class);
					}
					
					string set_class=reader.ReadString();
					if(!set_class.StartsWith(typeof(ResourceSet).FullName) && !set_class.StartsWith("System.Resources.RuntimeResourceSet")) {
						throw new NotSupportedException("This .resources file requires set class " + set_class);
					}
				}

				/* Now read the ResourceReader header */
				resource_ver = reader.ReadInt32();

				if(resource_ver != 1
#if NET_2_0
					&& resource_ver != 2
#endif
					) {
					throw new NotSupportedException("This .resources file requires unsupported set class version: " + resource_ver.ToString());
				}

				resourceCount = reader.ReadInt32();
				typeCount = reader.ReadInt32();
				
				types=new Type[typeCount];

				for(int i=0; i<typeCount; i++) {
					types[i]=Type.GetType(reader.ReadString(), true);
				}

				/* There are between 0 and 7 bytes of
				 * padding here, consisting of the
				 * letters PAD.  The next item (Hash
				 * values for each resource name) need
				 * to be aligned on an 8-byte
				 * boundary.
				 */

				int pad_align=(int)(reader.BaseStream.Position & 7);
				int pad_chars=0;

				if(pad_align!=0) {
					pad_chars=8-pad_align;
				}

				for(int i=0; i<pad_chars; i++) {
					byte pad_byte=reader.ReadByte();
					if(pad_byte!="PAD"[i%3]) {
						throw new ArgumentException("Malformed .resources file (padding values incorrect)");
					}
				}

				/* Read in the hash values for each
				 * resource name.  These can be used
				 * by ResourceSet (calling internal
				 * methods) to do a fast compare on
				 * resource names without doing
				 * expensive string compares (but we
				 * dont do that yet, so far we only
				 * implement the Enumerator interface)
				 */
				hashes=new int[resourceCount];
				for(int i=0; i<resourceCount; i++) {
					hashes[i]=reader.ReadInt32();
				}
				
				/* Read in the virtual offsets for
				 * each resource name
				 */
				positions=new long[resourceCount];
				for(int i=0; i<resourceCount; i++) {
					positions[i]=reader.ReadInt32();
				}
				
				dataSectionOffset = reader.ReadInt32();
				nameSectionOffset = reader.BaseStream.Position;
			} catch(EndOfStreamException e) {
				throw new ArgumentException("Stream is not a valied .resources file!  It was possibly truncated.", e);
			}
		}

		/* Cut and pasted from BinaryReader, because it's
		 * 'protected' there
		 */
		private int Read7BitEncodedInt() {
			int ret = 0;
			int shift = 0;
			byte b;

			do {
				b = reader.ReadByte();
				
				ret = ret | ((b & 0x7f) << shift);
				shift += 7;
			} while ((b & 0x80) == 0x80);

			return ret;
		}

		private string ResourceName(int index)
		{
			lock(this) 
			{
				long pos=positions[index]+nameSectionOffset;
				reader.BaseStream.Seek(pos, SeekOrigin.Begin);

				/* Read a 7-bit encoded byte length field */
				int len=Read7BitEncodedInt();
				byte[] str=new byte[len];

				reader.Read(str, 0, len);
				return Encoding.Unicode.GetString(str);
			}
		}

		// TODO: Read complex types
		object ReadValueVer2 (int type_index)
		{
			switch ((PredefinedResourceType)type_index)
			{
				case PredefinedResourceType.Null:
					return null;

				case PredefinedResourceType.String:
					return reader.ReadString();

				case PredefinedResourceType.Bool:
					return reader.ReadBoolean ();

				case PredefinedResourceType.Char:
					return (char)reader.ReadUInt16();

				case PredefinedResourceType.Byte:
					return reader.ReadByte();

				case PredefinedResourceType.SByte:
					return reader.ReadSByte();

				case PredefinedResourceType.Int16:
					return reader.ReadInt16();

				case PredefinedResourceType.UInt16:
					return reader.ReadUInt16();

				case PredefinedResourceType.Int32:
					return reader.ReadInt32();

				case PredefinedResourceType.UInt32:
					return reader.ReadUInt32();

				case PredefinedResourceType.Int64:
					return reader.ReadInt64();

				case PredefinedResourceType.UInt64:
					return reader.ReadUInt64();

				case PredefinedResourceType.Single:
					return reader.ReadSingle();

				case PredefinedResourceType.Double:
					return reader.ReadDouble();

				case PredefinedResourceType.Decimal:
					return reader.ReadDecimal();

				case PredefinedResourceType.DateTime:
					return new DateTime(reader.ReadInt64());

				case PredefinedResourceType.TimeSpan:
					return new TimeSpan(reader.ReadInt64());

				case PredefinedResourceType.ByteArray:
					throw new NotImplementedException (PredefinedResourceType.ByteArray.ToString ());

				case PredefinedResourceType.Stream:
					throw new NotImplementedException (PredefinedResourceType.Stream.ToString ());
			}

			type_index -= (int)PredefinedResourceType.FistCustom;
			return ReadNonPredefinedValue (types[type_index]);
		}

		object ReadValueVer1 (Type type)
		{
			// The most common first
			if (type==typeof(String))
				return reader.ReadString();
			if (type==typeof(Int32))
				return reader.ReadInt32();
			if (type==typeof(Byte))
				return(reader.ReadByte());
			if (type==typeof(Double))
				return(reader.ReadDouble());
			if (type==typeof(Int16))
				return(reader.ReadInt16());
			if (type==typeof(Int64))
				return(reader.ReadInt64());
			if (type==typeof(SByte))
				return(reader.ReadSByte());
			if (type==typeof(Single))
				return(reader.ReadSingle());
			if (type==typeof(TimeSpan))
				return(new TimeSpan(reader.ReadInt64()));
			if (type==typeof(UInt16))
				return(reader.ReadUInt16());
			if (type==typeof(UInt32))
				return(reader.ReadUInt32());
			if (type==typeof(UInt64))
				return(reader.ReadUInt64());
			if (type==typeof(Decimal))
				return(reader.ReadDecimal());
			if (type==typeof(DateTime))
				return(new DateTime(reader.ReadInt64()));

			return ReadNonPredefinedValue(type);
		}

		// TODO: Add security checks
		object ReadNonPredefinedValue (Type exp_type)
		{
			object obj=formatter.Deserialize(reader.BaseStream);
			if(obj.GetType() != exp_type) {
				/* We got a bogus
						 * object.  This
						 * exception is the
						 * best match I could
						 * find.  (.net seems
						 * to throw
						 * BadImageFormatException,
						 * which the docs
						 * state is used when
						 * file or dll images
						 * cant be loaded by
						 * the runtime.)
						 */
				throw new InvalidOperationException("Deserialized object is wrong type");
			}
			return obj;
		}

		private object ResourceValue(int index)
		{
			lock(this)
			{
				long pos=positions[index]+nameSectionOffset;
				reader.BaseStream.Seek(pos, SeekOrigin.Begin);

				/* Read a 7-bit encoded byte length field */
				long len=Read7BitEncodedInt();
				/* ... and skip that data to the info
				 * we want, the offset into the data
				 * section
				 */
				reader.BaseStream.Seek(len, SeekOrigin.Current);

				long data_offset=reader.ReadInt32();
				reader.BaseStream.Seek(data_offset+dataSectionOffset, SeekOrigin.Begin);
				int type_index=Read7BitEncodedInt();

#if NET_2_0
				if (resource_ver == 2)
					return ReadValueVer2 (type_index);
#endif
				if (type_index == -1)
					return null;

				return ReadValueVer1 (types[type_index]);
			}
		}

		public void Close ()
		{
			Dispose(true);
		}
		
		public IDictionaryEnumerator GetEnumerator () {
			if (reader == null){
				throw new InvalidOperationException("ResourceReader is closed.");
			}
			else {
				return new ResourceEnumerator (this);
			}
		}
		
		IEnumerator IEnumerable.GetEnumerator ()
		{
			return ((IResourceReader) this).GetEnumerator();
		}
		
		void IDisposable.Dispose ()
		{
			Dispose(true);
		}

		private void Dispose (bool disposing)
		{
			if(disposing) {
				if(reader!=null) {
					reader.Close();
				}
			}

			reader=null;
			hashes=null;
			positions=null;
			types=null;
		}
		
		internal class ResourceEnumerator : IDictionaryEnumerator
		{
			private ResourceReader reader;
			private int index = -1;
			private bool finished = false;
			
			internal ResourceEnumerator(ResourceReader readerToEnumerate){
				reader = readerToEnumerate;
			}

			public virtual DictionaryEntry Entry
			{
				get {
					if (reader.reader == null)
						throw new InvalidOperationException("ResourceReader is closed.");
					if (index < 0)
						throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");

					DictionaryEntry entry = new DictionaryEntry();
					entry.Key = Key;
					entry.Value = Value;
					return entry; 
				}
			}
			
			public virtual object Key
			{
				get { 
					if (reader.reader == null)
						throw new InvalidOperationException("ResourceReader is closed.");
					if (index < 0)
						throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
					return (reader.ResourceName(index)); 
				}
			}
			
			public virtual object Value
			{
				get { 
					if (reader.reader == null)
						throw new InvalidOperationException("ResourceReader is closed.");
					if (index < 0)
						throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
					return(reader.ResourceValue(index));
				}
			}
			
			public virtual object Current
			{
				get {
					/* Entry does the checking, no
					 * need to repeat it here
					 */
					return Entry; 
				}
			}
			
			public virtual bool MoveNext ()
			{
				if (reader.reader == null)
					throw new InvalidOperationException("ResourceReader is closed.");
				if (finished) {
					return false;
				}
				
				if (++index < reader.resourceCount){
					return true;
				}
				else {
					finished=true;
					return false;
				}
			}
			
			public void Reset () {
				if (reader.reader == null)
					throw new InvalidOperationException("ResourceReader is closed.");
				index = -1;
				finished = false;
			}
		} // internal class ResourceEnumerator
	}  // public sealed class ResourceReader
} // namespace System.Resources