-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathExecutableReader.cs
101 lines (89 loc) · 2.64 KB
/
ExecutableReader.cs
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
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
namespace PEUtility
{
public sealed class ExecutableReader : IDisposable
{
private readonly string _fileName;
private MemoryMappedFile _file;
public ExecutableReader(string fileName)
{
_fileName = fileName;
}
private MemoryMappedFile File
{
get
{
if (_file == null)
{
_file = MemoryMappedFile.CreateFromFile(_fileName, FileMode.Open);
}
return _file;
}
}
public MemoryMappedViewAccessor GetAccessor(long offset, long size)
{
return File.CreateViewAccessor(offset, size, MemoryMappedFileAccess.Read);
}
public T ReadStruct<T>(long offset) where T : struct
{
T structure;
using (var accessor = GetAccessor(offset, Marshal.SizeOf(typeof(T))))
{
accessor.Read(0, out structure);
}
return structure;
}
public T[] ReadStructArray<T>(long offset, int count) where T : struct
{
T[] structArray = new T[count];
using (var accessor = GetAccessor(offset, count * Marshal.SizeOf(typeof(T))))
{
accessor.ReadArray(0, structArray, 0, count);
}
return structArray;
}
public ushort ReadUInt16(long address)
{
using (var accessor = GetAccessor(address, sizeof(short)))
{
return accessor.ReadUInt16(0);
}
}
public uint ReadUInt32(long address)
{
using (var accessor = GetAccessor(address, sizeof(uint)))
{
return accessor.ReadUInt32(0);
}
}
private long ReadInt64(long address)
{
using (var accessor = GetAccessor(address, sizeof(long)))
{
return accessor.ReadInt64(0);
}
}
public ulong ReadUInt64(long address)
{
using (var accessor = GetAccessor(address, sizeof(ulong)))
{
return accessor.ReadUInt64(0);
}
}
public void Dispose()
{
Close();
}
public void Close()
{
if (_file != null)
{
_file.Dispose();
_file = null;
}
}
}
}