-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathBytePattern.cs
More file actions
345 lines (295 loc) · 8.68 KB
/
BytePattern.cs
File metadata and controls
345 lines (295 loc) · 8.68 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
using ReClassNET.Extensions;
namespace ReClassNET.MemoryScanner
{
public enum PatternMaskFormat
{
/// <summary>
/// Example: AA BB ?? D? ?E FF
/// </summary>
Combined,
/// <summary>
/// Example: \xAA\xBB\x00\x00\x00\xFF xx???x
/// </summary>
Separated
}
public class BytePattern
{
private interface IPatternByte
{
/// <summary>
/// Gets the byte value of the pattern byte if possible.
/// </summary>
/// <returns></returns>
byte ToByte();
/// <summary>
/// Compares the pattern byte with the given byte.
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
bool Equals(byte b);
/// <summary>
/// Formats the pattern byte as string.
/// </summary>
/// <param name="format"></param>
/// <returns></returns>
Tuple<string, string> ToString(PatternMaskFormat format);
}
private class PatternByte : IPatternByte
{
private struct Nibble
{
public int Value;
public bool IsWildcard;
}
private Nibble nibble1;
private Nibble nibble2;
public bool HasWildcard => nibble1.IsWildcard || nibble2.IsWildcard;
public byte ToByte() => !HasWildcard ? (byte)((nibble1.Value << 4) + nibble2.Value) : throw new InvalidOperationException();
public static PatternByte NewWildcardByte()
{
var pb = new PatternByte
{
nibble1 = { IsWildcard = true },
nibble2 = { IsWildcard = true }
};
return pb;
}
private static bool IsHexValue(char c)
{
return '0' <= c && c <= '9'
|| 'A' <= c && c <= 'F'
|| 'a' <= c && c <= 'f';
}
private static int HexToInt(char c)
{
if ('0' <= c && c <= '9') return c - '0';
if ('A' <= c && c <= 'F') return c - 'A' + 10;
return c - 'a' + 10;
}
public bool TryRead(StringReader sr)
{
Contract.Requires(sr != null);
var temp = sr.ReadSkipWhitespaces();
if (temp == -1 || !IsHexValue((char)temp) && (char)temp != '?')
{
return false;
}
nibble1.Value = HexToInt((char)temp) & 0xF;
nibble1.IsWildcard = (char)temp == '?';
temp = sr.Read();
if (temp == -1 || char.IsWhiteSpace((char)temp) || (char)temp == '?')
{
nibble2.IsWildcard = true;
return true;
}
if (!IsHexValue((char)temp))
{
return false;
}
nibble2.Value = HexToInt((char)temp) & 0xF;
nibble2.IsWildcard = false;
return true;
}
public bool Equals(byte b)
{
if (nibble1.IsWildcard || ((b >> 4) & 0xF) == nibble1.Value)
{
if (nibble2.IsWildcard || (b & 0xF) == nibble2.Value)
{
return true;
}
}
return false;
}
public Tuple<string, string> ToString(PatternMaskFormat format)
{
switch (format)
{
case PatternMaskFormat.Separated:
return HasWildcard ? Tuple.Create("\\x00", "?") : Tuple.Create($"\\x{ToByte():X02}", "x");
case PatternMaskFormat.Combined:
var sb = new StringBuilder();
if (nibble1.IsWildcard) sb.Append('?');
else sb.AppendFormat("{0:X}", nibble1.Value);
if (nibble2.IsWildcard) sb.Append('?');
else sb.AppendFormat("{0:X}", nibble2.Value);
return Tuple.Create(sb.ToString(), (string)null);
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
public override string ToString() => ToString(PatternMaskFormat.Combined).Item1;
}
private class SimplePatternByte : IPatternByte
{
private readonly byte value;
public SimplePatternByte(byte value)
{
this.value = value;
}
public byte ToByte() => value;
public bool Equals(byte b) => value == b;
public Tuple<string, string> ToString(PatternMaskFormat format)
{
switch (format)
{
case PatternMaskFormat.Separated:
return Tuple.Create($"\\x{ToByte():X02}", "x");
case PatternMaskFormat.Combined:
return Tuple.Create($"{ToByte():X02}", (string)null);
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
}
private readonly List<IPatternByte> pattern = new List<IPatternByte>();
/// <summary>
/// Gets the length of the pattern in byte.
/// </summary>
public int Length => pattern.Count;
/// <summary>
/// Gets if the pattern contains wildcards.
/// </summary>
public bool HasWildcards => pattern.Any(pb => pb is PatternByte pb2 && pb2.HasWildcard);
private BytePattern()
{
}
/// <summary>
/// Parses the provided string for a byte pattern. Wildcards are supported by nibble.
/// </summary>
/// <example>
/// Valid patterns:
/// AA BB CC DD
/// AABBCCDD
/// aabb CCdd
/// A? ?B ?? DD
/// </example>
/// <exception cref="ArgumentException">Thrown if the provided string doesn't contain a valid byte pattern.</exception>
/// <param name="value">The byte pattern in hex format.</param>
/// <returns>The corresponding <see cref="BytePattern"/>.</returns>
public static BytePattern Parse(string value)
{
Contract.Requires(!string.IsNullOrEmpty(value));
Contract.Ensures(Contract.Result<BytePattern>() != null);
var pattern = new BytePattern();
using var sr = new StringReader(value);
while (true)
{
var pb = new PatternByte();
if (pb.TryRead(sr))
{
if (!pb.HasWildcard)
{
pattern.pattern.Add(new SimplePatternByte(pb.ToByte()));
}
else
{
pattern.pattern.Add(pb);
}
}
else
{
break;
}
}
// Check if we are not at the end of the stream
if (sr.Peek() != -1)
{
throw new ArgumentException($"'{value}' is not a valid byte pattern.");
}
return pattern;
}
/// <summary>
/// Creates a byte pattern from the provided bytes.
/// </summary>
/// <param name="data">The bytes to match.</param>
/// <returns></returns>
public static BytePattern From(IEnumerable<byte> data)
{
var pattern = new BytePattern();
pattern.pattern.AddRange(data.Select(b => new SimplePatternByte(b)));
return pattern;
}
/// <summary>
/// Creates a byte pattern with wildcard support from the provided bytes. The boolean tuple item signals a wildcard.
/// </summary>
/// <param name="data">The byte data or the wildcard flag.</param>
/// <returns></returns>
public static BytePattern From(IEnumerable<Tuple<byte, bool>> data)
{
var pattern = new BytePattern();
foreach (var (value, isWildcard) in data)
{
var pb = isWildcard ? (IPatternByte)PatternByte.NewWildcardByte() : new SimplePatternByte(value);
pattern.pattern.Add(pb);
}
return pattern;
}
/// <summary>
/// Tests if the provided byte array matches the byte pattern at the provided index.
/// </summary>
/// <param name="data">The byte array to be compared.</param>
/// <param name="index">The index into the byte array.</param>
/// <returns>True if the pattern matches, false if they are not.</returns>
public bool Equals(byte[] data, int index)
{
Contract.Requires(data != null);
for (var j = 0; j < pattern.Count; ++j)
{
if (!pattern[j].Equals(data[index + j]))
{
return false;
}
}
return true;
}
/// <summary>
/// Converts this <see cref="BytePattern"/> to a byte array.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the pattern contains wildcards.</exception>
/// <returns>The bytes of the pattern.
/// </returns>
public byte[] ToByteArray()
{
Contract.Ensures(Contract.Result<byte[]>() != null);
if (HasWildcards)
{
throw new InvalidOperationException();
}
return pattern.Select(pb => pb.ToByte()).ToArray();
}
/// <summary>
/// Formats the <see cref="BytePattern"/> in the specified <see cref="PatternMaskFormat"/>.
/// </summary>
/// <param name="format">The format of the pattern.</param>
/// <returns>A tuple containing the format. If <paramref name="format"/> is not <see cref="PatternMaskFormat.Separated"/> the second item is null.</returns>
public Tuple<string, string> ToString(PatternMaskFormat format)
{
switch (format)
{
case PatternMaskFormat.Separated:
var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
pattern
.Select(p => p.ToString(PatternMaskFormat.Separated))
.ForEach(t =>
{
sb1.Append(t.Item1);
sb2.Append(t.Item2);
});
return Tuple.Create(sb1.ToString(), sb2.ToString());
case PatternMaskFormat.Combined:
return Tuple.Create<string, string>(string.Join(" ", pattern.Select(p => p.ToString(PatternMaskFormat.Combined).Item1)), null);
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
public override string ToString() => ToString(PatternMaskFormat.Combined).Item1;
}
}