/[RomCheater]/trunk/RomCheater/Serialization/SearchResultReader.cs
ViewVC logotype

Contents of /trunk/RomCheater/Serialization/SearchResultReader.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 686 - (show annotations) (download)
Mon Jun 17 09:31:52 2013 UTC (8 years, 4 months ago) by william
File size: 23968 byte(s)
+ massive move of source files

1 #define READ_RESULTS_ON_CREATION // when defined will call GetResults() from ReadHeader()
2 #region Logging Defines
3 // include this any class or method that required logging, and comment-out what is not needed
4
5 #region Enabled logging levels
6 #define LOGGING_ENABLE_INFO
7 #define LOGGING_ENABLE_WARN
8 #define LOGGING_ENABLE_DEBUG
9 #define LOGGING_ENABLE_VERBOSEDEBUG
10 #define LOGGING_ENABLE_ERROR
11 #define LOGGING_ENABLE_VERBOSEERROR
12 #define LOGGING_ENABLE_PROFILER
13 #endregion
14 #endregion
15 using System;
16 using System.Collections.Generic;
17 using System.Linq;
18 using System.Text;
19 using RomCheater.Docking.MemorySearch;
20 using RomCheater.Logging;
21 using System.IO;
22 using Utilities.TransparentControls;
23 using Sojaner.MemoryScanner.MemoryProviers;
24
25 using System.Windows.Forms;
26 using RomCheater.Core;
27 using System.Diagnostics;
28 using System.Collections;
29
30 namespace RomCheater.Serialization
31 {
32 public interface ISearchResultReader : ISerializedResult
33 {
34 //ResultType<TValue> GetNextResult<TValue>() where TValue : IConvertible;
35 }
36
37 public interface ISerializedResult : ISerializedResult<ulong> { }
38 public interface ISerializedResult<T> where T: IConvertible
39 {
40 //ResultReaderCollection GetResultCollection();
41 bool ContainsAddress(uint address);
42 bool ContainsAddress(uint address,out int index);
43 void GetResultAtIndex(int index, out StructResultType<T> result);
44 void UpdateResultValuesFromMemory(ref StructResultType<T>[] results, IAcceptsProcessAndConfig iapc);
45 }
46
47
48
49 #region public class ResultReaderEnumerator : IEnumerator<StructResultType<ulong>>
50 //public class ResultReaderEnumerator : IEnumerator<StructResultType<ulong>>
51 //{
52 // //private IEnumerator<StructResultType<ulong>> _enumerator;
53 // private int _index = 0;
54 // private int index { get { return _index; } set { _index = value; } }
55 // private SearchResultReader _reader;
56 // private SearchResultReader reader { get { CheckReaderNull(); return _reader; } set { _reader = value; CheckReaderNull(); } }
57 // private int MinimumIndex { get { return this.reader.MinimumIndex; } }
58 // private int MaximumIndex { get { return this.reader.MaximumIndex; } }
59 // #region Exceptions
60 // private void CheckReaderNull()
61 // {
62 // if (_reader == null)
63 // {
64 // throw new ArgumentNullException("reader", "Reader cannot be null");
65 // }
66 // }
67 // private void CheckIndexLessThanMin()
68 // {
69 // if (_index < MinimumIndex)
70 // {
71 // throw new ArgumentOutOfRangeException("index", string.Format("index cannot be less than {0}", MinimumIndex));
72 // }
73 // }
74 // private void CheckIndexGreaterThanMax()
75 // {
76 // if (_index > MaximumIndex)
77 // {
78 // throw new ArgumentOutOfRangeException("index", string.Format("index cannot be greater than {0}", MaximumIndex));
79 // }
80 // }
81 // #endregion
82 // public ResultReaderEnumerator(SearchResultReader reader)
83 // {
84 // this.reader = reader;
85 // this.index = -1;
86 // }
87 // public StructResultType<ulong> Current
88 // {
89 // get
90 // {
91 // // result the current entry (at position)
92 // //throw new NotImplementedException();
93 // CheckIndexLessThanMin();
94 // CheckIndexGreaterThanMax();
95 // StructResultType<ulong> result = StructResultType<ulong>.Empty;
96 // reader.GetResultAtIndex(this.index, out result);
97 // return result;
98 // }
99 // }
100 // public void Dispose()
101 // {
102 // //throw new NotImplementedException();
103 // }
104 // object System.Collections.IEnumerator.Current
105 // {
106 // get { return this.Current; }
107 // }
108 // public bool MoveNext()
109 // {
110 // this.index++; // increment after processing index at MinimumIndex
111 // if (this.index >= this.MinimumIndex && this.index <= this.MaximumIndex)
112 // {
113 // return true;
114 // }
115 // Reset();
116 // return false;
117 // }
118 // public void Reset()
119 // {
120 // this.index = -1;
121 // }
122 //}
123 #endregion
124
125 #region public class ResultReaderCollection : IEnumerable<StructResultType<ulong>>
126 //public class ResultReaderCollection : IEnumerable<StructResultType<ulong>>
127 //{
128 // private SearchResultReader _reader;
129 // private SearchResultReader reader { get { CheckReaderNull(); return _reader; } set { _reader = value; CheckReaderNull(); } }
130 // public ResultReaderCollection(SearchResultReader reader)
131 // {
132 // this.reader = reader;
133 // }
134 // #region Exceptions
135 // private void CheckReaderNull()
136 // {
137 // if (_reader == null)
138 // {
139 // throw new ArgumentNullException("reader", "Reader cannot be null");
140 // }
141 // }
142 // #endregion
143 // public IEnumerator<StructResultType<ulong>> GetEnumerator()
144 // {
145 // return new ResultReaderEnumerator(_reader);
146 // }
147 // System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
148 // {
149 // return GetEnumerator();
150 // }
151 //}
152 #endregion
153
154
155
156 #region public class SearchResultReader : SerializationReader, ISearchResultReader, ISerializedResult
157 public class SearchResultReader : SerializationReader, ISearchResultReader, ISerializedResult<ulong>, IEnumerator<StructResultType<ulong>>, IEnumerable<StructResultType<ulong>>
158 {
159 //private Guid _ResultGuid;
160 //private Guid ResultGuid { get { return _ResultGuid; } set { _ResultGuid = value; } }
161 public ulong MinimumIndex { get { return 0; } }
162 public ulong MaximumIndex { get { return this.ResultCount - 1; } }
163
164 private ulong ResultDataOffset = 0;
165 ////private long CurrentResultOffset = 0;
166 ////public SearchResultReader() : base() { ReadHeader(); }
167 //[Obsolete("SearchResultReader(Guid guid) should not be used")]
168 //public SearchResultReader(Guid guid) : base(guid, false) { ResultGuid = guid; ReadHeader(); }
169 //[Obsolete("SearchResultReader(Guid guid, bool delete) should not be used")]
170 //public SearchResultReader(Guid guid, bool delete) : base(guid, delete) { ResultGuid = guid; ReadHeader(); }
171
172 private void CheckIndexLessThanMin()
173 {
174 if (_index < MinimumIndex)
175 {
176 throw new ArgumentOutOfRangeException("index", string.Format("index cannot be less than {0}", MinimumIndex));
177 }
178 }
179 private void CheckIndexGreaterThanMax()
180 {
181 if (_index > MaximumIndex)
182 {
183 throw new ArgumentOutOfRangeException("index", string.Format("index cannot be greater than {0}", MaximumIndex));
184 }
185 }
186 private ulong _index = 0;
187 private ulong index { get { return _index; } set { _index = value; } }
188
189 #region IEnumerable<StructResultType<ulong>> members
190 public IEnumerator<StructResultType<ulong>> GetEnumerator()
191 {
192 return this; // we are implementing our own custom enumerator through use of: IEnumerator<StructResultType<ulong>>
193 }
194
195 IEnumerator IEnumerable.GetEnumerator()
196 {
197 return this.GetEnumerator();
198 }
199 #endregion
200
201 #region IEnumerator<StructResultType<ulong>> members
202 public StructResultType<ulong> Current
203 {
204 get
205 {
206 // result the current entry (at position)
207 //throw new NotImplementedException();
208 CheckIndexLessThanMin();
209 CheckIndexGreaterThanMax();
210 return results[index];
211 }
212 }
213 object IEnumerator.Current
214 {
215 get { return this.Current; }
216 }
217
218 public bool MoveNext()
219 {
220 this.index++; // increment after processing index at MinimumIndex
221 if (this.index >= this.MinimumIndex && this.index <= this.MaximumIndex)
222 {
223 return true;
224 }
225 Reset();
226 return false;
227 }
228
229 public void Reset()
230 {
231 this.index = 0;
232 }
233 #endregion
234
235 //#region IEnumerator<StructResultType<ulong>> members
236 //public IEnumerator<StructResultType<ulong>> GetEnumerator()
237 //{
238 // return (IEnumerator<StructResultType<ulong>>)results.GetEnumerator();
239 //}
240 //System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
241 //{
242 // return GetEnumerator();
243 //}
244 //#endregion
245 #region ISerializedResult<T> members
246 //public ResultReaderCollection GetResultCollection()
247 //{
248 // ResultReaderCollection collection = new ResultReaderCollection(this);
249 // return collection;
250 //}
251 public bool ContainsAddress(uint address)
252 {
253 int index = 0;
254 return ContainsAddress(address, out index);
255 }
256 public bool ContainsAddress(uint address, out int index)
257 {
258 bool contains = false;
259 index = 0;
260 foreach (var k in this.results)
261 {
262 if (k.Address == address)
263 {
264 contains = true;
265 break;
266 }
267 index++;
268 }
269 return contains;
270
271
272 //#error ContainsAddress - Not Implemented - need update for change to GetResults()
273
274 // foreach (var result in GetResults())
275 // {
276 // if (cancel_method.Invoke()) { break; }
277 // if (result.Address == address)
278 // {
279 // if (contains)
280 // {
281 // throw new ArgumentOutOfRangeException("address", string.Format("Found more than one result that matched address: 0x{0} - index={1}", address.ToString("X"), index));
282 // }
283 // contains = true;
284 // break; // should never throw the exception, if we break here (only returning/checking the first found address
285 // }
286 // index++;
287 // }
288
289 }
290 public void GetResultAtIndex(int index, out StructResultType<ulong> result)
291 {
292 result = StructResultType<ulong>.Empty;
293 result = this.results[index];
294 //#error GetResultAtIndex - Not Implemented - need update for change to GetResults()
295 // int count = 0;
296 // foreach (var entry in GetResults())
297 // {
298 // if (index == count)
299 // {
300 // result = entry;
301 // break;
302 // }
303 // count++;
304 // }
305 }
306
307 public void UpdateResultValuesFromMemory(ref StructResultType<ulong>[] results, IAcceptsProcessAndConfig iapc)
308 {
309 Stopwatch st = new Stopwatch();
310 st.Start();
311 List<ulong> addresses = new List<ulong>();
312 results.ToList().ForEach(s => addresses.Add(s.Address));
313 using (GenericMemoryProvider provider = new GenericMemoryProvider(iapc))
314 {
315 byte[][] values;
316 provider.OpenProvider();
317 provider.UpdateAddressArray(addresses.ToArray(), BitTools.SizeOf<uint>(datatype), out values);
318 provider.CloseProvider();
319
320 for (int i = 0; i < results.Length; i++)
321 {
322 if (this.cancel_method.Invoke())
323 {
324 logger.Warn.WriteLine("UpdateResultValuesFromMemory - operation cancelled at [ResultIndex=0x{0} ChunkCount=0x{1}]", i.ToString("X"), results.Length.ToString("X"));
325 break;
326 }
327 ulong value = 0;
328 byte[] data = values[i];
329 switch (datatype)
330 {
331 case SearchDataTypes._8bits: value = data[0]; break;
332 case SearchDataTypes._16bits: value = BitConverter.ToUInt16(data, 0); break;
333 case SearchDataTypes._32bits: value = BitConverter.ToUInt32(data, 0); break;
334 case SearchDataTypes._64bits: value = BitConverter.ToUInt64(data, 0); break;
335 }
336 results[i].Value = value;
337 logger.Profiler.WriteLine("UpdateResultValuesFromMemory [ResultIndex=0x{0} ChunkCount=0x{1}] has taken a total of {2} seconds to complete", i.ToString("X"), results.Length.ToString("X"), st.Elapsed.TotalSeconds.ToString());
338
339
340 string message = string.Format(" -> Updateing values [ResultIndex=0x{0} of ChunkCount=0x{1}]", i.ToString("X"), results.Length.ToString("X"));
341 double double_percent_done = 100.0 * (double)((double)i / (double)results.Length);
342 if (((double)i % ((double)results.Length) * 0.25) == 0)
343 {
344 update_progress.Invoke((int)double_percent_done, message);
345 }
346 }
347 st.Stop();
348 logger.Profiler.WriteLine("UpdateResultValuesFromMemory [ChunkCount=0x{0}] took a total of {1} seconds to complete", results.Length.ToString("X"), st.Elapsed.TotalSeconds.ToString());
349 }
350 }
351
352 #endregion
353
354 private StructResultType<ulong>[] results = new StructResultType<ulong>[0];
355
356 private bool _unsigned;
357 private bool unsigned { get { return _unsigned; } set { _unsigned = value; } }
358 private SearchDataTypes _datatype;
359 private SearchDataTypes datatype { get { return _datatype; } set { _datatype = value; } }
360 private Action<int, string> _update_progress;
361 private Action<int, string> update_progress { get { return _update_progress; } set { _update_progress = value; } }
362 private Func<bool> _cancel_method;
363 private Func<bool> cancel_method { get { return _cancel_method; } set { _cancel_method = value; } }
364
365 public SearchResultReader(Guid guid, bool unsigned, SearchDataTypes datatype, Action<int, string> update_progress, Func<bool> cancelmethod) : this(guid, false, unsigned, datatype, update_progress, cancelmethod) { }
366 public SearchResultReader(Guid guid, bool delete, bool unsigned, SearchDataTypes datatype, Action<int, string> update_progress, Func<bool> cancelmethod)
367 : base(guid, delete)
368 {
369 this.unsigned = unsigned;
370 this.datatype = datatype;
371 this.update_progress = update_progress;
372 this.cancel_method = cancel_method;
373 ReaderGuid = guid;
374 ReadHeader();
375 }
376
377
378 public void ReleaseMemory()
379 {
380 this.results = null;
381 }
382
383 protected override void Dispose(bool disposing)
384 {
385 base.Dispose(disposing);
386 this.ReleaseMemory();
387 }
388
389 protected override string TemporaryFolder { get { return SearchResultsConstants.SearchResultsFolder; } }
390 private void ReadHeader()
391 {
392 try
393 {
394 using (FileStream fs = CreateReader())
395 {
396 using (BinaryReader binReader = new BinaryReader(fs))
397 {
398 //int ResultsRead = 0;
399 // SRD (string)
400 string magic = Encoding.UTF8.GetString(binReader.ReadBytes(3));
401 string SRD = "SRD";
402 if (magic != SRD)
403 {
404 throw new InvalidOperationException(string.Format("Encountered unexpected magic: {0} expected: {1}", magic, SRD));
405 }
406 // version (int)
407 int version = binReader.ReadInt32();
408
409 if (version == 1)
410 {
411 // do nothing
412 }
413 else if (version == 2)
414 {
415 int guid_array_length = binReader.ReadInt32();
416 byte[] guid_array = new byte[guid_array_length];
417 binReader.Read(guid_array, 0, guid_array_length);
418 Guid g = new Guid(guid_array);
419 if (g != ReaderGuid)
420 {
421 throw new InvalidOperationException(string.Format("Encountered wrong search results guid: read '{1}' excpected '{2}'", g.ToString(), ReaderGuid.ToString()));
422 }
423 }
424 else
425 {
426 throw new InvalidOperationException(string.Format("Encountered unexpected version: {0} expected: {1} or {2}", version, 1, 2));
427 }
428 // resultcount
429 ulong resultcount = binReader.ReadUInt64();
430 if (resultcount == 0)
431 {
432 throw new InvalidOperationException(string.Format("Result Count is zero"));
433 }
434 ResultCount = resultcount;
435 ResultDataOffset = (ulong)binReader.BaseStream.Position;
436
437
438 #if READ_RESULTS_ON_CREATION
439 // this opperation may use alot of memory
440 GetResults(binReader);
441 #endif
442
443 binReader.Close();
444 }
445 fs.Close();
446 }
447 }
448 catch (System.IO.EndOfStreamException) { }
449 }
450 #region ISearchResultReader members
451 public bool ReadCurrentAddess { get; private set; }
452 public bool ReadCurrentValue { get; private set; }
453
454 //[Obsolete("GetNextResult has been replaced by GetResults")]
455 //public ResultType<TValue> GetNextResult<TValue>() where TValue : IConvertible
456 //{
457 // return new ResultType<TValue>();
458 //}
459 #endregion
460
461
462 #region
463 private void GetResults(BinaryReader br)
464 {
465 results = new StructResultType<ulong>[ResultCount];
466 try
467 {
468 for (ulong i = 0; i < ResultCount; i++)
469 {
470 StructResultType<ulong> result = StructResultType<ulong>.Empty;
471 ulong Address = br.ReadUInt64();
472 ulong Value = 0;
473 switch (datatype)
474 {
475 case SearchDataTypes._8bits:
476 if (unsigned) { Value = br.ReadByte(); } else { Value = (ulong)br.ReadSByte(); }
477 break;
478 case SearchDataTypes._16bits:
479 if (unsigned) { Value = br.ReadUInt16(); } else { Value = (ulong)br.ReadInt16(); }
480 break;
481 case SearchDataTypes._32bits:
482 if (unsigned) { Value = br.ReadUInt32(); } else { Value = (ulong)br.ReadInt32(); }
483 break;
484 case SearchDataTypes._64bits:
485 if (unsigned) { Value = br.ReadUInt64(); } else { Value = (ulong)br.ReadInt64(); }
486 break;
487 }
488 result = new StructResultType<ulong>(Address, Value);
489 results[i] = result;
490 }
491 //results.TrimExcess();
492 }
493 catch (Exception ex)
494 {
495 logger.Error.WriteLine("Failed to reader results...");
496 logger.VerboseError.WriteLine(ex.ToString());
497 results =new StructResultType<ulong>[0];
498 //results.TrimExcess();
499 throw ex;
500 }
501 }
502 #endregion
503
504 //#region private StructResultType<ulong> GetResultAtIndex(int index)
505 //private StructResultType<ulong> GetResultAtIndex(int index)
506 //{
507 // try
508 // {
509 // //update_progress.Invoke(0, string.Empty);
510 // int data_size = sizeof(uint); // address size ... should be 4 bytes (could be 8, if we have a 64-bit address)
511 // StructResultType<ulong> result = StructResultType<ulong>.Empty;
512 // if (cancel_method.Invoke()) { return result; }
513 // using (FileStream fs = this.CreateReader())
514 // {
515 // using (BinaryReader binReader = new BinaryReader(fs))
516 // {
517 // binReader.BaseStream.Seek(this.ResultDataOffset, SeekOrigin.Begin); // seek to start of result data
518 // data_size += (int)datatype / 8;
519 // long offset = data_size * index;
520 // binReader.BaseStream.Seek(offset, SeekOrigin.Current);
521 // uint Address = binReader.ReadUInt32();
522 // ulong Value = 0;
523 // switch (datatype)
524 // {
525 // case SearchDataTypes._8bits:
526 // if (unsigned) { Value = binReader.ReadByte(); } else { Value = (ulong)binReader.ReadSByte(); }
527 // break;
528 // case SearchDataTypes._16bits:
529 // if (unsigned) { Value = binReader.ReadUInt16(); } else { Value = (ulong)binReader.ReadInt16(); }
530 // break;
531 // case SearchDataTypes._32bits:
532 // if (unsigned) { Value = binReader.ReadUInt32(); } else { Value = (ulong)binReader.ReadInt32(); }
533 // break;
534 // case SearchDataTypes._64bits:
535 // if (unsigned) { Value = binReader.ReadUInt64(); } else { Value = (ulong)binReader.ReadInt64(); }
536 // break;
537 // }
538 // result = new StructResultType<ulong>(Address, Value);
539 // }
540 // }
541 // //double percent_done = 100.0 * ((double)index / (double)reader.ResultCount);
542 // //string message = string.Format("-> Reading Result at index: 0x{0}", index.ToString("X"));
543 // //update_progress((int)percent_done, message);
544 // return result;
545 // }
546 // catch (Exception ex)
547 // {
548 // logger.Error.WriteLine("GetResultAtIndex...Failed to read the stream at index: 0x{0}", index.ToString("X"));
549 // logger.VerboseError.WriteLine(ex.ToString());
550 // return StructResultType<ulong>.Empty;
551 // }
552 //}
553 //#endregion
554 }
555 #endregion
556 }

  ViewVC Help
Powered by ViewVC 1.1.22