File: ImageReader.cs

package info (click to toggle)
cecil 0.4.3-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,348 kB
  • ctags: 6,289
  • sloc: cs: 14,484; xml: 663; ruby: 428; makefile: 74; sh: 52
file content (277 lines) | stat: -rw-r--r-- 9,152 bytes parent folder | download
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
//
// ImageReader.cs
//
// Author:
//   Jb Evain (jbevain@gmail.com)
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// <%=Time.now%>
//
// (C) 2005 Jb Evain
//
// 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.
//

namespace Mono.Cecil.Binary {

	using System;
	using System.IO;
	using System.Text;

	using Mono.Cecil.Metadata;

	class ImageReader : BaseImageVisitor {

		MetadataReader m_mdReader;
		BinaryReader m_binaryReader;
		Image m_image;

		public MetadataReader MetadataReader {
			get { return m_mdReader; }
		}

		public Image Image {
			get { return m_image; }
		}

		ImageReader (Image img, BinaryReader reader)
		{
			m_image = img;
			m_binaryReader = reader;
		}

		static ImageReader Read (Image img, Stream stream)
		{
			ImageReader reader = new ImageReader (img, new BinaryReader (stream));
			img.Accept (reader);
			return reader;
		}

		public static ImageReader Read (string file)
		{
			if (file == null)
				throw new ArgumentNullException ("file");

			FileInfo fi = new FileInfo (file);
			if (!File.Exists (fi.FullName))
			#if CF_1_0 || CF_2_0
				throw new FileNotFoundException (fi.FullName);
			#else
				throw new FileNotFoundException (string.Format ("File '{0}' not found.", fi.FullName), fi.FullName);
			#endif

			return Read (new Image (fi), new FileStream (
				fi.FullName, FileMode.Open,
				FileAccess.Read, FileShare.Read));
		}

		public static ImageReader Read (byte [] image)
		{
			if (image == null)
				throw new ArgumentNullException ("image");

			if (image.Length == 0)
				throw new ArgumentException ("Empty image array");

			return Read (new Image (), new MemoryStream (image));
		}

		public static ImageReader Read (Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException ("stream");

			if (!stream.CanRead)
				throw new ArgumentException ("Can not read from stream");

			return Read (new Image (), stream);
		}

		public BinaryReader GetReader ()
		{
			return m_binaryReader;
		}

		public override void VisitImage (Image img)
		{
			m_mdReader = new MetadataReader (this);
		}

		public override void VisitDOSHeader (DOSHeader header)
		{
			header.Start = m_binaryReader.ReadBytes (60);
			header.Lfanew = m_binaryReader.ReadUInt32 ();
			header.End = m_binaryReader.ReadBytes (64);

			m_binaryReader.BaseStream.Position = header.Lfanew;

			if (m_binaryReader.ReadUInt16 () != 0x4550 ||
				m_binaryReader.ReadUInt16 () != 0)

				throw new ImageFormatException ("Invalid PE File Signature");
		}
<% $headers.each { |name, header| if name != "Section" && name != "CLIHeader" && name != "DebugHeader" %>
		public override void Visit<%=name.index('.') ? name[(name.index('.') + 1)..name.length] : name%> (<%=name%> header)
		{<% header.fields.each { |field| %>
			header.<%=field.property_name%> = <%=field.read_binary("m_binaryReader")%>;<% } %>
		}
<% end } %>
		public override void VisitSectionCollection (SectionCollection coll)
		{
			for (int i = 0; i < m_image.PEFileHeader.NumberOfSections; i++)
				coll.Add (new Section ());
		}
<% cur_header = $headers["Section"] %>
		public override void VisitSection (Section sect)
		{
			char [] name, buffer = new char [8];
			int read = 0;
			while (read < 8) {
				char cur = (char) m_binaryReader.ReadSByte ();
				if (cur == '\0')
					break;
				buffer [read++] = cur;
			}
			name = new char [read];
			Array.Copy (buffer, 0, name, 0, read);
			sect.Name = read == 0 ? string.Empty : new string (name);
			if (sect.Name == Section.Text)
				m_image.TextSection = sect;
			m_binaryReader.BaseStream.Position += 8 - read - 1;
<% cur_header.fields.each { |field| %>			sect.<%=field.property_name%> = <%=field.read_binary("m_binaryReader")%>;
<% } %>
			long pos = m_binaryReader.BaseStream.Position;
			m_binaryReader.BaseStream.Position = sect.PointerToRawData;
			sect.Data = m_binaryReader.ReadBytes ((int) sect.SizeOfRawData);
			m_binaryReader.BaseStream.Position = pos;
		}

		public override void VisitImportAddressTable (ImportAddressTable iat)
		{
			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.PEOptionalHeader.DataDirectories.IAT.VirtualAddress);

			iat.HintNameTableRVA = new RVA (m_binaryReader.ReadUInt32 ());
		}
<% cur_header = $headers["CLIHeader"] %>
		public override void VisitCLIHeader (CLIHeader header)
		{
			if (m_image.PEOptionalHeader.DataDirectories.CLIHeader == DataDirectory.Zero)
				throw new ImageFormatException ("Non Pure CLI Image");

			if (m_image.PEOptionalHeader.DataDirectories.Debug != DataDirectory.Zero) {
				m_image.DebugHeader = new DebugHeader ();
				VisitDebugHeader (m_image.DebugHeader);
			}

			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.PEOptionalHeader.DataDirectories.CLIHeader.VirtualAddress);
<% cur_header.fields.each { |field| %>			header.<%=field.property_name%> = <%=field.read_binary("m_binaryReader")%>;
<% } %>
			if (header.StrongNameSignature != DataDirectory.Zero) {
				m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
					header.StrongNameSignature.VirtualAddress);
				header.ImageHash = m_binaryReader.ReadBytes ((int) header.StrongNameSignature.Size);
			} else {
				header.ImageHash = new byte [0];
			}
			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.CLIHeader.Metadata.VirtualAddress);
			m_image.MetadataRoot.Accept (m_mdReader);
		}
<% cur_header = $headers["DebugHeader"] %>
		public override void VisitDebugHeader (DebugHeader header)
		{
			if (m_image.PEOptionalHeader.DataDirectories.Debug == DataDirectory.Zero)
				return;

			long pos = m_binaryReader.BaseStream.Position;

			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.PEOptionalHeader.DataDirectories.Debug.VirtualAddress);
<% cur_header.fields.each { |field| %>			header.<%=field.property_name%> = <%=field.read_binary("m_binaryReader")%>;
<% } %>
			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.DebugHeader.AddressOfRawData);

			header.Magic = m_binaryReader.ReadUInt32 ();
			header.Signature = new Guid (m_binaryReader.ReadBytes (16));
			header.Age = m_binaryReader.ReadUInt32 ();

			StringBuilder buffer = new StringBuilder ();
			while (true) {
				byte cur =  m_binaryReader.ReadByte ();
				if (cur == 0)
					break;
				buffer.Append ((char) cur);
			}
			header.FileName = buffer.ToString ();

			m_binaryReader.BaseStream.Position = pos;
		}

		public override void VisitImportTable (ImportTable it)
		{
			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.PEOptionalHeader.DataDirectories.ImportTable.VirtualAddress);

			it.ImportLookupTable = new RVA (m_binaryReader.ReadUInt32 ());
			it.DateTimeStamp = m_binaryReader.ReadUInt32 ();
			it.ForwardChain = m_binaryReader.ReadUInt32 ();
			it.Name = new RVA (m_binaryReader.ReadUInt32 ());
			it.ImportAddressTable = new RVA (m_binaryReader.ReadUInt32 ());
		}

		public override void VisitImportLookupTable (ImportLookupTable ilt)
		{
			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.ImportTable.ImportLookupTable.Value);

			ilt.HintNameRVA = new RVA (m_binaryReader.ReadUInt32 ());
		}

		public override void VisitHintNameTable (HintNameTable hnt)
		{
			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.ImportAddressTable.HintNameTableRVA);

			hnt.Hint = m_binaryReader.ReadUInt16 ();

			byte [] bytes = m_binaryReader.ReadBytes (11);
			hnt.RuntimeMain = Encoding.ASCII.GetString (bytes, 0, bytes.Length);

			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.ImportTable.Name);

			bytes = m_binaryReader.ReadBytes (11);
			hnt.RuntimeLibrary = Encoding.ASCII.GetString (bytes, 0, bytes.Length);

			m_binaryReader.BaseStream.Position = m_image.ResolveVirtualAddress (
				m_image.PEOptionalHeader.StandardFields.EntryPointRVA);
			hnt.EntryPoint = m_binaryReader.ReadUInt16 ();
			hnt.RVA = new RVA (m_binaryReader.ReadUInt32 ());
		}

		public override void TerminateImage (Image img)
		{
			m_binaryReader.Close ();
		}
	}
}