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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 554 - (show annotations) (download)
Thu Jun 6 02:26:28 2013 UTC (8 years, 7 months ago) by william
File size: 21797 byte(s)

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

  ViewVC Help
Powered by ViewVC 1.1.22