/[RomCheater]/trunk/RomCheater/Docking/FloatingMemorySearcher.cs
ViewVC logotype

Annotation of /trunk/RomCheater/Docking/FloatingMemorySearcher.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 565 - (hide annotations) (download)
Thu Jun 6 05:08:26 2013 UTC (7 years, 4 months ago) by william
File size: 146793 byte(s)

1 william 414 #region Logging Defines
2     // include this any class or method that required logging, and comment-out what is not needed
3 william 415
4 william 414 #region Enabled logging levels
5     #define LOGGING_ENABLE_INFO
6     #define LOGGING_ENABLE_WARN
7     #define LOGGING_ENABLE_DEBUG
8     #define LOGGING_ENABLE_VERBOSEDEBUG
9     #define LOGGING_ENABLE_ERROR
10     #define LOGGING_ENABLE_VERBOSEERROR
11     #define LOGGING_ENABLE_PROFILER
12     #endregion
13     #endregion
14     //#define USE_AUTOMATIC_MEMORY_SEARCH_RANGE // when defined will automatically choose the best starting address and size for memory search otherwise it will use the constants defined in MemorySizeConstants
15 william 289 #if !USE_AUTOMATIC_MEMORY_SEARCH_RANGE
16 william 287 #define FORCE_USE_OF_MEMORYSIZECONSTANTS // when defined wil force the use of the constants defined in MemorySizeConstants for memory search range
17 william 289 #endif
18 william 452 #define DONOT_HAVE_RANGED_SEARCH_SUPPORT // when defined, indicates that ranged searches have not been implemented
19 william 280 #define INCREASE_NUMBER_OF_RESULTS_BEFORE_DISPLAY // when defined will set MIN RESULTS to 0x2701 otherwise 0x03e8
20     //#define DO_NOT_SUSPEND_RESUME_THREAD_ON_FREEZE // when defined will not freeze/resume thread on freeze
21 william 229 using System;
22 william 227 using System.Collections.Generic;
23     using System.ComponentModel;
24     using System.Data;
25     using System.Drawing;
26     using System.Linq;
27     using System.Text;
28     using System.Windows.Forms;
29     using WeifenLuo.WinFormsUI.Docking;
30     using RomCheater.PluginFramework.Interfaces;
31     using System.Diagnostics;
32 william 229 using RomCheater.Docking.MemorySearch;
33     using libWin32.Win32.Threading;
34 william 230 using System.Threading;
35     using RomCheater.Logging;
36     using System.IO;
37 william 242 using Sojaner.MemoryScanner.MemoryProviers;
38 william 275 using RomCheater.PluginFramework.Events;
39 william 287 using System.Reflection;
40 william 292 using Sojaner.MemoryScanner;
41 william 399 using System.Collections;
42 william 401 using RomCheater.Serialization;
43 william 511 using RomCheater.Core;
44 william 227
45     namespace RomCheater.Docking
46     {
47 william 228 public partial class FloatingMemorySearcher : DockContent,
48 william 243 IAcceptsPlugin<IConfigPlugin>,
49 william 477 IAcceptsProcess<Process>,
50 william 243 IAcceptsProcessAndConfig,
51 william 275 ISearchInProgress,
52 william 287 IAcceptsBrowseMemoryRegion,
53     IAcceptsMemoryRange
54 william 227 {
55 william 280 #if INCREASE_NUMBER_OF_RESULTS_BEFORE_DISPLAY
56     const int MIN_NUMBER_OF_RESULTS_BEFORE_DISPLAY = 0x2701; // 10,000 results
57     #else
58     const int MIN_NUMBER_OF_RESULTS_BEFORE_DISPLAY = 0x03e8; // 1,000 results
59     #endif
60    
61 william 565 const uint MEM_1KB = 0x400;
62     const uint MEM_1MB = MEM_1KB * MEM_1KB; // 1024 * 1024 = 1MB
63     const uint MEM_CHUNK_SIZE_MB = MEM_1MB * 16; /* MEM_1MB * N = N in megabytes (in bytes) */
64     const uint MEM_CHUNK_SIZE_KB = MEM_1KB * 64; /* MEM_1KB * N = N in kilobytes (in bytes) */
65 william 546
66 william 565 const uint MEM_CHUNK_SIZE = MEM_CHUNK_SIZE_KB;
67    
68    
69 william 452 const bool USE_OLD_SEARCH_RESULTS_COMPRATOR_CODE = false;
70 william 457 const bool USE_NONRANGE_SEARCH_RESULT_READER = false;
71 william 229 private bool DefaultUnsignedState = true; // set unsigned to true
72 william 477 public FloatingMemorySearcher() { InitializeComponent(); this.AcceptedPlugin = null; OnBrowseMemoryRegion = null; this.AcceptedProcess = null; SearchInProgess = false; Reload(); }
73 william 227 public FloatingMemorySearcher(IConfigPlugin config) : this() { this.AcceptedPlugin = config; }
74 william 477 public FloatingMemorySearcher(IConfigPlugin config, Process process) : this() { this.AcceptedPlugin = config; this.AcceptedProcess = process; }
75 william 227
76 william 462 //new Action<int, string>(UpdateProgress) to use this as a delegate
77 william 511
78     private void thread_UpdateProgress(object o)
79 william 461 {
80 william 511 IProgressMessage pm = (o as IProgressMessage);
81     if (pm == null) { return; }
82     resultsprogress.Value = pm.Progress;
83 william 517 resultsprogress.Message = pm.Message;
84 william 534 //Application.DoEvents();
85 william 461 }
86    
87 william 532 private bool ShouldCancelAnySearchOperation() { return SearchWorkerThread.CancellationPending; }
88    
89 william 511 private void UpdateProgress(int progress, string message)
90 william 532 {
91 william 511 // detach the progress update from execution within the current thread (so it does not block a cpu-intensive or long running sequence)
92     Thread t = new Thread(new ParameterizedThreadStart(thread_UpdateProgress));
93 william 517 t.SetApartmentState(ApartmentState.STA);
94 william 511 t.Start(new ProgressMessage(progress, message));
95 william 517 //resultsprogress.Value = progress;
96     //resultsprogress.Message = message;
97 william 511 }
98    
99 william 237 #region IAcceptsProcess<Process> Members
100 william 477 private Process _AcceptedProcess;
101     public Process AcceptedProcess { get { return _AcceptedProcess; } set { _AcceptedProcess = value; UpdateAcceptedProcess(value); } }
102 william 227 #endregion
103     #region IAcceptsPlugin<IConfigPlugin> Members
104 william 243 private IConfigPlugin _AcceptedPlugin;
105 william 305 public IConfigPlugin AcceptedPlugin { get { return _AcceptedPlugin; } set { _AcceptedPlugin = value; UpdateAcceptedPlugin(value); } }
106 william 227 #endregion
107 william 275 #region IAcceptsBrowseMemoryRegion members
108 william 287 public event BaseEventHandler<BrowseMemoryRegionEvent> OnBrowseMemoryRegion;
109 william 275 #endregion
110    
111 william 305 private void UpdateAcceptedPlugin(IConfigPlugin config)
112 william 243 {
113     this.lstResults.AcceptedPlugin = config;
114     this.lstPatchList.AcceptedPlugin = config;
115 william 389 if (config != null)
116     {
117     MemoryRangeStart = AcceptedPlugin.MemoryRangeStart;
118     MemoryRangeSize = AcceptedPlugin.MemoryRangeStart + AcceptedPlugin.MemoryRangeSize;
119     }
120 william 305 }
121 william 477 private void UpdateAcceptedProcess(Process process)
122     {
123     this.lstResults.AcceptedProcess = process;
124     this.lstPatchList.AcceptedProcess = process;
125 william 287 #if USE_AUTOMATIC_MEMORY_SEARCH_RANGE && FORCE_USE_OF_MEMORYSIZECONSTANTS
126     logger.Warn.WriteLine("FloatingMemorySearcher.UpdateAcceptedProcessAndConfig(IConfigPlugin config, Process process):");
127     logger.Warn.WriteLine("Both USE_AUTOMATIC_MEMORY_SEARCH_RANGE and FORCE_USE_OF_MEMORYSIZECONSTANTS are defined");
128     logger.Warn.WriteLine("FORCE_USE_OF_MEMORYSIZECONSTANTS will take precedence and will ignore the values supplied in the memeory search range");
129 william 289 #endif
130     #if FORCE_USE_OF_MEMORYSIZECONSTANTS
131     // force use of MemorySizeConstants
132 william 349 txtMemoryRangeStart.Value = MemorySizeConstants.MinimumSearchAddress;
133 william 401 txtMemoryRangeSize.Value = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize;
134 william 287 #endif
135     #if USE_AUTOMATIC_MEMORY_SEARCH_RANGE && !FORCE_USE_OF_MEMORYSIZECONSTANTS
136 william 318 ////// code to automatically choose the best starting memory address and size
137     //if (process != null)
138     //{
139     // string filename = process.MainModule.FileName;
140     // //string filename = @"c:\Windows\notepad.exe";
141     // PEReader peReader = new PEReader(filename);
142     //}
143     //else
144     //{
145 william 389 //txtMemoryRangeStart.Value = MemorySizeConstants.MinimumSearchAddress;
146     //txtMemoryRangeSize.Value = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize;
147 william 318 //}
148 william 389 if (AcceptedPlugin != null)
149     {
150     MemoryRangeStart = AcceptedPlugin.MemoryRangeStart;
151     MemoryRangeSize = AcceptedPlugin.MemoryRangeStart + AcceptedPlugin.MemoryRangeSize;
152     }
153    
154 william 287 #endif
155    
156 william 243 }
157 william 228 #region ISearchInProgress members
158 william 399 private bool _SearchInProgess;
159     public bool SearchInProgess
160     {
161     get { return _SearchInProgess; }
162     private set
163     {
164     _SearchInProgess = value;
165     if (this.AcceptedPlugin != null)
166     this.AcceptedPlugin.SetMemorySearchReference(this);
167     }
168     }
169 william 444 private Guid _SearchGuid;
170     public Guid SearchGuid
171     {
172     get { return _SearchGuid; }
173     private set { _SearchGuid = value; }
174     }
175 william 228 #endregion
176 william 229
177 william 287 #region IAcceptsMemoryRange
178     #if !FORCE_USE_OF_MEMORYSIZECONSTANTS
179 william 389 private uint _MemoryRangeStart;
180 william 287 private uint _MemoryRangeSize;
181     #endif
182 william 378 public uint MemoryRangeStart
183 william 287 {
184     get
185     {
186     #if FORCE_USE_OF_MEMORYSIZECONSTANTS
187 william 349 return MemorySizeConstants.MinimumSearchAddress;
188 william 287 #else
189     return _MemoryRangeStart;
190     #endif
191     }
192     set
193     {
194     #if !FORCE_USE_OF_MEMORYSIZECONSTANTS
195     _MemoryRangeStart = value;
196 william 389 txtMemoryRangeStart.Value = value;
197 william 287 #endif
198     }
199     }
200     public uint MemoryRangeSize
201     {
202     get
203     {
204     #if FORCE_USE_OF_MEMORYSIZECONSTANTS
205 william 401 return MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize;
206 william 287 #else
207     return _MemoryRangeSize;
208     #endif
209     }
210     set
211     {
212     #if !FORCE_USE_OF_MEMORYSIZECONSTANTS
213     _MemoryRangeSize = value;
214 william 389 txtMemoryRangeSize.Value = value;
215 william 287 #endif
216     }
217     }
218     #endregion
219 william 229
220     public void Reload()
221     {
222     chkUnsigned.Checked = DefaultUnsignedState;
223     radio_8bits.Checked = true;
224     radiocompare_equal.Checked = true;
225     radio_oldvalue.Checked = true;
226 william 230 chkRefreshResults.Checked = true;
227 william 229 }
228 william 230 public enum eListViewResults
229     {
230     SEARCH_RESULTS_LIST = 0x3000,
231     PATCH_RESULTS_LIST = 0x3001,
232     UKNOWN_RESULTS_LIST = 0x3001
233     }
234 william 280 bool IsFirstSearch = true;
235 william 277 SearchType SearchArgs;
236 william 272 static int col_Found_Address = 1;
237     static int col_Found_Value = 2;
238 william 419 //static int col_Found_Frozen = 3; /* unused */
239 william 272 static int col_Added_Address = 1;
240     static int col_Added_Value = 2;
241 william 419 //static int col_Added_Frozen = 3; /* unused */
242 william 230 List<ListViewItem> ResultItems = new List<ListViewItem>();
243     List<ListViewItem> AddedItems = new List<ListViewItem>();
244     private bool _PatchedValue_NeedsUpdate;
245     bool PatchedValue_NeedsUpdate
246     {
247     get { if (_PatchedValue_NeedsUpdate) this.ThawResultsUpdate(); return _PatchedValue_NeedsUpdate; }
248     set { _PatchedValue_NeedsUpdate = value; if (value) this.ThawResultsUpdate(); }
249     }
250     private delegate ListViewItem ThreadSafe_GetResultItem(int index, int lv_type);
251     private ListViewItem GetResultItem(int index, int lv_type)
252     {
253     try
254     {
255     AddressValuePairList lv = null;
256     switch (lv_type)
257     {
258     case (int)eListViewResults.SEARCH_RESULTS_LIST: lv = lstResults; break;
259     case (int)eListViewResults.PATCH_RESULTS_LIST: lv = lstPatchList; break;
260     default: throw new IndexOutOfRangeException("Detected: " + Enum.GetName(typeof(eListViewResults), eListViewResults.UKNOWN_RESULTS_LIST) + " with value: " + lv_type.ToString("x4"));
261     }
262     ListViewItem item = new ListViewItem();
263     item = (ListViewItem)lv.Items[index].Clone();
264     return item;
265     }
266     catch (Exception)
267     {
268     return null;
269     }
270     }
271 william 229 private void radiocompare_equal_CheckedChanged(object sender, EventArgs e)
272     {
273     //if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
274     //{
275     if (radio_oldvalue.Checked)
276     {
277     txtStartAddr.ReadOnly = true;
278     txtEndAddr.ReadOnly = true;
279     }
280     if (radio_specificvalue.Checked)
281     {
282     txtStartAddr.ReadOnly = false;
283     txtEndAddr.ReadOnly = true;
284     }
285     //}
286     }
287    
288     private void radiocompare_between_CheckedChanged(object sender, EventArgs e)
289     {
290     if (!radiocompare_equal.Checked &&
291     !radiocompare_greaterthan.Checked &&
292     !radiocompare_greaterthan.Checked &&
293     !radiocompare_lessthan.Checked &&
294     !radiocompare_greaterthan_orequal.Checked &&
295     !radiocompare_lessthan_orequal.Checked &&
296     !radiocompare_notequal.Checked)
297     if (radiocompare_between.Checked)
298     {
299     txtStartAddr.ReadOnly = false;
300     txtEndAddr.ReadOnly = false;
301     return;
302     }
303     if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
304     {
305     if (radio_oldvalue.Checked)
306     {
307     txtStartAddr.ReadOnly = true;
308     txtEndAddr.ReadOnly = true;
309     }
310     if (radio_specificvalue.Checked)
311     {
312     txtStartAddr.ReadOnly = false;
313     txtEndAddr.ReadOnly = true;
314     }
315     }
316     }
317    
318     private void radiocompare_notbetween_CheckedChanged(object sender, EventArgs e)
319     {
320     if (!radiocompare_equal.Checked &&
321     !radiocompare_greaterthan.Checked &&
322     !radiocompare_greaterthan.Checked &&
323     !radiocompare_lessthan.Checked &&
324     !radiocompare_greaterthan_orequal.Checked &&
325     !radiocompare_lessthan_orequal.Checked &&
326     !radiocompare_notequal.Checked)
327     if (radiocompare_notbetween.Checked)
328     {
329     txtStartAddr.ReadOnly = false;
330     txtEndAddr.ReadOnly = false;
331     return;
332     }
333     if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
334     {
335     if (radio_oldvalue.Checked)
336     {
337     txtStartAddr.ReadOnly = true;
338     txtEndAddr.ReadOnly = true;
339     }
340     if (radio_specificvalue.Checked)
341     {
342     txtStartAddr.ReadOnly = false;
343     txtEndAddr.ReadOnly = true;
344     }
345     }
346     }
347    
348     private void radio_8bits_CheckedChanged(object sender, EventArgs e)
349     {
350     if (chkUnsigned.Checked)
351     {
352     txtStartAddr.CreateTypeSize<byte>();
353     txtEndAddr.CreateTypeSize<byte>();
354     }
355     else
356     {
357     txtStartAddr.CreateTypeSize<sbyte>();
358     txtEndAddr.CreateTypeSize<sbyte>();
359     }
360     }
361    
362     private void radio_16bits_CheckedChanged(object sender, EventArgs e)
363     {
364     if (chkUnsigned.Checked)
365     {
366     txtStartAddr.CreateTypeSize<ushort>();
367     txtEndAddr.CreateTypeSize<ushort>();
368     }
369     else
370     {
371     txtStartAddr.CreateTypeSize<short>();
372     txtEndAddr.CreateTypeSize<short>();
373     }
374     }
375    
376     private void radio_32bits_CheckedChanged(object sender, EventArgs e)
377     {
378    
379     if (chkUnsigned.Checked)
380     {
381     txtStartAddr.CreateTypeSize<uint>();
382     txtEndAddr.CreateTypeSize<uint>();
383     }
384     else
385     {
386     txtStartAddr.CreateTypeSize<int>();
387     txtEndAddr.CreateTypeSize<int>();
388     }
389     }
390    
391     private void radio_64bits_CheckedChanged(object sender, EventArgs e)
392     {
393    
394     if (chkUnsigned.Checked)
395     {
396     txtStartAddr.CreateTypeSize<ulong>();
397     txtEndAddr.CreateTypeSize<ulong>();
398     }
399     else
400     {
401     txtStartAddr.CreateTypeSize<long>();
402     txtEndAddr.CreateTypeSize<long>();
403     }
404     }
405    
406     private void radio_oldvalue_CheckedChanged(object sender, EventArgs e)
407     {
408     if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
409     {
410     txtStartAddr.ReadOnly = true;
411     txtEndAddr.ReadOnly = true;
412     }
413     }
414    
415     private void radio_specificvalue_CheckedChanged(object sender, EventArgs e)
416     {
417     if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
418     {
419     txtStartAddr.ReadOnly = false;
420     txtEndAddr.ReadOnly = true;
421     }
422     }
423    
424     private void chkRefreshResults_CheckedChanged(object sender, EventArgs e)
425     {
426     if (chkRefreshResults.Checked)
427     {
428     timer_update_results.Enabled = true;
429     }
430     else
431     {
432     timer_update_results.Enabled = false;
433     ResultsUpdateWorkerThread.CancelAsync();
434     }
435     }
436    
437     private void timer_update_results_Tick(object sender, EventArgs e)
438     {
439     if (chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
440     {
441     ResultsUpdateWorkerThread.RunWorkerAsync();
442     }
443     }
444 william 230 private bool ShouldUpdateResults()
445     {
446 william 477 if (this.AcceptedProcess == null) return false;
447 william 230 if (SearchWorkerThread.IsBusy) return false;
448     //if (JokerSearchWorker.IsBusy) return false;
449     if (this.IsResultsUpdateFrozen) return false;
450     if (mnuAddedResults.Visible) return false;
451     if (mnuResults.Visible) return false;
452 william 477 if (Process.GetProcessById(this.AcceptedProcess.Id) == null) return false;
453 william 230 if (lstResults.Items.Count > 0) return true;
454     if (lstPatchList.Items.Count > 0) return true;
455     return false;
456     }
457 william 229 private void ResultsUpdateWorkerThread_DoWork(object sender, DoWorkEventArgs e)
458     {
459 william 230 Thread.Sleep(250); // keep thread from blocking
460     if (!this.ShouldUpdateResults()) return;
461     ////if (SearchArgs == null) return;
462     ////if (this.IsResultsUpdateFrozen) return;
463     ////// put thread to sleep for 500ms
464     ////System.Threading.Thread.Sleep(500);
465     //PCSX2MemoryProvider provider = new PCSX2MemoryProvider(this.SearchPCSX2ProcessPID, resultslog);
466     //byte[] buffered_mem = provider.GetMemory();
467     //MemoryStream ms = new MemoryStream(buffered_mem);
468     //BinaryReader r_ms = new BinaryReader(ms);
469 william 229
470 william 230 #region Update Results List
471     ResultItems = new List<ListViewItem>();
472     //r_ms.BaseStream.Seek(0, SeekOrigin.Begin);
473     for (int i = 0; i < lstResults.Items.Count; i++)
474     {
475     if (this.lstResults.InvokeRequired)
476     {
477     ThreadSafe_GetResultItem _get_item = new ThreadSafe_GetResultItem(GetResultItem);
478     object item = this.lstResults.Invoke(_get_item, new object[] { i, (int)eListViewResults.SEARCH_RESULTS_LIST });
479     if (item != null)
480     ResultItems.Add((ListViewItem)item);
481     }
482     else
483     {
484     ResultItems.Add(lstResults.Items[i]);
485     }
486    
487     }
488     for (int i = 0; i < ResultItems.Count; i++)
489     {
490     if (ResultsUpdateWorkerThread.CancellationPending == true)
491     {
492     e.Cancel = true;
493     return;
494     }
495 william 249 int Address = 0;
496 william 230 ResultDataType _result = (ResultDataType)ResultItems[i].Tag;
497    
498 william 249 Address = Convert.ToInt32(ResultItems[i].SubItems[col_Found_Address].Text, 16);
499 william 242 //r_ms.BaseStream.Seek(Address, SeekOrigin.Begin);
500 william 398 using (GenericMemoryProvider provider = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
501 william 230 {
502 william 398 provider.OpenProvider();
503     int bytesReadSize;
504     byte[] data;
505     uint bytesToRead = 0;
506     switch (_result.ValueType)
507     {
508     case SearchDataTypes._8bits:
509     bytesToRead = 1;
510     break;
511     case SearchDataTypes._16bits:
512     bytesToRead = 2;
513     break;
514     case SearchDataTypes._32bits:
515     bytesToRead = 4;
516     break;
517     case SearchDataTypes._64bits:
518     bytesToRead = 8;
519     break;
520     }
521     provider.ReadProcessMemory(Address, bytesToRead, out bytesReadSize, out data);
522     using (MemoryStream ms = new MemoryStream(data))
523     {
524     using (BinaryReader r_ms = new BinaryReader(ms))
525     {
526     switch (_result.ValueType)
527     {
528     case SearchDataTypes._8bits:
529     if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x2}", r_ms.ReadByte()); }
530     else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x2}", r_ms.ReadSByte()); }
531     break;
532     case SearchDataTypes._16bits:
533     if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x4}", r_ms.ReadUInt16()); }
534     else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x4}", r_ms.ReadInt16()); }
535     break;
536     case SearchDataTypes._32bits:
537     if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x8}", r_ms.ReadUInt32()); }
538     else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x8}", r_ms.ReadInt32()); }
539     break;
540     case SearchDataTypes._64bits:
541     if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x16}", r_ms.ReadUInt64()); }
542     else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x16}", r_ms.ReadInt64()); }
543     break;
544     }
545     r_ms.Close();
546     }
547     }
548 william 424 provider.CloseProvider();
549 william 230 }
550 william 398 //Application.DoEvents();
551 william 230 }
552     #endregion
553    
554     #region Update Added Results List
555     AddedItems = new List<ListViewItem>();
556     //r_ms.BaseStream.Seek(0, SeekOrigin.Begin);
557     for (int i = 0; i < lstPatchList.Items.Count; i++)
558     {
559     if (this.lstResults.InvokeRequired)
560     {
561     ThreadSafe_GetResultItem _get_item = new ThreadSafe_GetResultItem(GetResultItem);
562     object item = this.lstResults.Invoke(_get_item, new object[] { i, (int)eListViewResults.PATCH_RESULTS_LIST });
563     if (item != null)
564     AddedItems.Add((ListViewItem)item);
565     }
566     else
567     {
568     AddedItems.Add(lstPatchList.Items[i]);
569     }
570    
571     }
572     for (int i = 0; i < AddedItems.Count; i++)
573     {
574     if (ResultsUpdateWorkerThread.CancellationPending == true)
575     {
576     e.Cancel = true;
577     return;
578     }
579 william 249 int Address = 0;
580 william 230 ResultDataType _result = (ResultDataType)AddedItems[i].Tag;
581 william 249 Address = Convert.ToInt32(AddedItems[i].SubItems[col_Added_Address].Text, 16);
582 william 398 using (GenericMemoryProvider provider = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
583 william 230 {
584 william 398 provider.OpenProvider();
585     int bytesReadSize;
586     byte[] data;
587     uint bytesToRead = 0;
588     switch (_result.ValueType)
589     {
590     case SearchDataTypes._8bits:
591     bytesToRead = 1;
592     break;
593     case SearchDataTypes._16bits:
594     bytesToRead = 2;
595     break;
596     case SearchDataTypes._32bits:
597     bytesToRead = 4;
598     break;
599     case SearchDataTypes._64bits:
600     bytesToRead = 8;
601     break;
602     }
603     provider.ReadProcessMemory(Address, bytesToRead, out bytesReadSize, out data);
604 william 424 provider.CloseProvider();
605 william 398 using (MemoryStream ms = new MemoryStream(data))
606     {
607     using (BinaryReader r_ms = new BinaryReader(ms))
608     {
609     switch (_result.ValueType)
610     {
611     case SearchDataTypes._8bits:
612     if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x2}", r_ms.ReadByte()); }
613     else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x2}", r_ms.ReadSByte()); }
614     break;
615     case SearchDataTypes._16bits:
616     if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x4}", r_ms.ReadUInt16()); }
617     else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x4}", r_ms.ReadInt16()); }
618     break;
619     case SearchDataTypes._32bits:
620     if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x8}", r_ms.ReadUInt32()); }
621     else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x8}", r_ms.ReadInt32()); }
622     break;
623     case SearchDataTypes._64bits:
624     if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x16}", r_ms.ReadUInt64()); }
625     else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x16}", r_ms.ReadInt64()); }
626     break;
627     }
628     r_ms.Close();
629     }
630     }
631 william 230 }
632 william 398 //Application.DoEvents();
633 william 230 }
634     #endregion
635    
636    
637 william 229 }
638    
639     private void ResultsUpdateWorkerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
640     {
641 william 230 try
642     {
643     //if ((lstResults.SelectedItems.Count > 0) && !PatchedValue_NeedsUpdate ) return;
644     //if ((lstPatchList.SelectedItems.Count > 0) && !PatchedValue_NeedsUpdate) return;
645     if (!this.ShouldUpdateResults()) return;
646     if (ResultItems.Count > 0)
647     {
648     //lstResults.Items.Clear();
649     //lstResults.Items.AddRange(ResultItems.ToArray());
650 william 229
651 william 230 for (int i = 0; i < ResultItems.Count; i++)
652     {
653     lstResults.Items[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text =
654     ResultItems[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text;
655     }
656    
657     }
658     if (AddedItems.Count > 0)
659     {
660     //lstPatchList.Items.Clear();
661     //lstPatchList.Items.AddRange(AddedItems.ToArray());
662    
663     for (int i = 0; i < AddedItems.Count; i++)
664     {
665     lstPatchList.Items[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text =
666     AddedItems[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text;
667     }
668    
669     }
670     PatchedValue_NeedsUpdate = false;
671     }
672     catch { }
673 william 229 }
674    
675     private void btnImportFile_Click(object sender, EventArgs e)
676     {
677     this.FreezeResultsUpdate();
678     if (!lstPatchList.ImportFromFile())
679     {
680     MessageBox.Show("Failed to Import Patch List from File.", "Import Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
681     this.ThawResultsUpdate();
682     return;
683     }
684     else
685     {
686     MessageBox.Show("Succesfully Imported Patch List from File.", "Import Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
687     this.ThawResultsUpdate();
688     return;
689     }
690     }
691     bool g_isFrozen = false;
692     private bool IsResultsUpdateFrozen
693     {
694     get { return g_isFrozen; }
695     set { g_isFrozen = value; }
696     }
697     private void ThawResultsUpdate()
698     {
699     this.IsResultsUpdateFrozen = false;
700 william 477 if (this.AcceptedProcess != null)
701 william 229 {
702     #if !DO_NOT_SUSPEND_RESUME_THREAD_ON_FREEZE
703 william 477 ThreadControl.ResumeProcess(this.AcceptedProcess.Id);
704 william 229 #endif
705     }
706     }
707    
708     private void FreezeResultsUpdate()
709     {
710     this.IsResultsUpdateFrozen = true;
711 william 285 //this.IsResultsUpdateFrozen = false;
712 william 477 if (this.AcceptedProcess != null)
713 william 229 {
714     #if !DO_NOT_SUSPEND_RESUME_THREAD_ON_FREEZE
715 william 477 ThreadControl.SuspendProcess(this.AcceptedProcess.Id);
716 william 229 #endif
717     }
718     }
719    
720     private void btnExportFile_Click(object sender, EventArgs e)
721     {
722     this.FreezeResultsUpdate();
723     if (!lstPatchList.ExportToFile())
724     {
725     MessageBox.Show("Failed to Export Patch List to File.", "Export Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
726     this.ThawResultsUpdate();
727     return;
728     }
729     else
730     {
731     MessageBox.Show("Succesfully Exported Patch List to File.", "Export Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
732     this.ThawResultsUpdate();
733     return;
734     }
735     }
736    
737     private void btnImportClipboard_Click(object sender, EventArgs e)
738     {
739     this.FreezeResultsUpdate();
740     if (!lstPatchList.ImportFromClipboard())
741     {
742     MessageBox.Show("Failed to Import Patch List from Clipboard.", "Import Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
743     this.ThawResultsUpdate();
744     return;
745     }
746     else
747     {
748     MessageBox.Show("Succesfully Import Patch List from Clipboard.", "Import Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
749     this.ThawResultsUpdate();
750     }
751     }
752    
753     private void btnExportClipboard_Click(object sender, EventArgs e)
754     {
755     this.FreezeResultsUpdate();
756     if (!lstPatchList.ExportToClipboard())
757     {
758     MessageBox.Show("Failed to Export Patch List to Clipboard.", "Export Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
759     this.ThawResultsUpdate();
760     return;
761     }
762     else
763     {
764     MessageBox.Show("Succesfully Exported Patch List to Clipboard.", "Export Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
765     this.ThawResultsUpdate();
766     return;
767     }
768     }
769    
770     private void btnAddPatchAddress_Click(object sender, EventArgs e)
771     {
772 william 245 PatchAdder adder = new PatchAdder((IAcceptsProcessAndConfig)this);
773 william 229 adder.ShowDialog();
774     if (adder.WasAPatchAdded) AddToPatchList(adder.AddedPatchValue);
775     }
776    
777     private void btnAddAddressRange_Click(object sender, EventArgs e)
778     {
779 william 245 PatchRangeAdder adder = new PatchRangeAdder((IAcceptsProcessAndConfig)this);
780 william 229 adder.ShowDialog();
781     if (adder.WasAPatchAdded) AddToPatchList(adder.AddedPatchValue);
782     }
783     private void AddToPatchList(List<ResultDataType> item) { foreach (ResultDataType data in item) { AddToPatchList(data); } }
784     private void AddToPatchList(ResultDataType item)
785     {
786     ResultItem item2 = null;
787     switch (item.ValueType)
788     {
789     case SearchDataTypes._8bits:
790     if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToByte(item.Value)); }
791     else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToSByte(item.Value)); }
792     break;
793     case SearchDataTypes._16bits:
794     if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToUInt16(item.Value)); }
795     else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToInt16(item.Value)); }
796     break;
797     case SearchDataTypes._32bits:
798     if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToUInt32(item.Value)); }
799     else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToInt32(item.Value)); }
800     break;
801     case SearchDataTypes._64bits:
802     if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToUInt64(item.Value)); }
803     else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToInt64(item.Value)); }
804     break;
805     }
806     this.AddToPatchList(item2);
807     }
808     private void AddToPatchList(ListViewItem item)
809     {
810     try
811     {
812     ResultDataType _result = (ResultDataType)item.Tag;
813     this.AddToPatchList(_result);
814     }
815     catch (InvalidCastException ex)
816     {
817     // unable to cast
818     MessageBox.Show(ex.Message, "Invalid Cast Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
819     }
820     catch (Exception ex)
821     {
822     // other exception
823     MessageBox.Show(ex.Message, "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
824     }
825     }
826     private void AddToPatchList(ResultItem item)
827     {
828     if (!lstPatchList.Items.Contains(item)) lstPatchList.Items.Add(item);
829     }
830     private void AddToPatchList(string address, SearchDataTypes bitsize, bool IsUnsigned)
831     {
832 william 245 ResultItemState state = new ResultItemState(address, bitsize, IsUnsigned, (IAcceptsProcessAndConfig)this);
833 william 229 ResultItem item = new ResultItem(state.Address, state.Value, state.Frozen, state.ValueType, state.IsUnsigned);
834     this.AddToPatchList(item);
835     }
836 william 230
837     private void mnuItemAddToPatchList_Click(object sender, EventArgs e)
838     {
839     if (!(lstResults.SelectedItems.Count > 0)) return;
840     //if (SearchArgs == null) return;
841    
842     try
843     {
844     for (int i = 0; i < lstResults.SelectedIndices.Count; i++)
845     {
846     //ResultDataType result = (ResultDataType)lstResults.Items[selected_index].Tag;
847     ListViewItem item = lstResults.Items[lstResults.SelectedIndices[i]];
848     this.AddToPatchList(item);
849     }
850     }
851     catch (Exception ex)
852     {
853     logger.Error.WriteLine(ex.ToString());
854     }
855     }
856    
857     private void mnuItemRemoveResult_Click(object sender, EventArgs e)
858     {
859     if (!(lstPatchList.SelectedItems.Count > 0)) return;
860     //if (SearchArgs == null) return;
861     try
862     {
863     this.FreezeResultsUpdate();
864     for (int i = 0; i < lstPatchList.SelectedIndices.Count; i++)
865     {
866     //lstPatchList.ThawItem(lstPatchList.SelectedIndices[i]);
867     lstPatchList.Items[lstPatchList.SelectedIndices[i]].Remove();
868     }
869     this.ThawResultsUpdate();
870     }
871     catch (Exception ex)
872     {
873     Debug.WriteLine(ex.ToString());
874     }
875     }
876     private void PatchRange(bool SingleEntry)
877     {
878     //if (SearchArgs == null) return;
879     #region Patch Selected Address
880     // stop ResultsUpdate Thread
881     ResultsUpdateWorkerThread.CancelAsync();
882    
883     List<ResultDataType> patch_list = new List<ResultDataType>();
884     List<int> SelectedIndexes = new List<int>();
885    
886     if (SingleEntry)
887     {
888     SelectedIndexes.Add(lstPatchList.SelectedIndices[0]);
889     }
890     else
891     {
892     foreach (int index in lstPatchList.SelectedIndices)
893     {
894     SelectedIndexes.Add(index);
895     }
896     }
897     //PCSX2MemoryProvider provider = new PCSX2MemoryProvider(this.SearchPCSX2ProcessPID, resultslog);
898     foreach (int index in SelectedIndexes)
899     {
900     if (SingleEntry)
901     {
902     SearchPatcher patcher = null;
903     uint Address = 0;
904     ListViewItem item = lstPatchList.Items[index];
905     ResultDataType _result = (ResultDataType)item.Tag;
906     Address = Convert.ToUInt32(item.SubItems[col_Found_Address].Text, 16);
907     switch (_result.ValueType)
908     {
909     case SearchDataTypes._8bits:
910     if (_result.IsUnsigned)
911     {
912     byte value = Convert.ToByte(item.SubItems[col_Found_Value].Text, 16);
913 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
914 william 230 timer_update_results.Enabled = false;
915     patcher.ShowDialog();
916     timer_update_results.Enabled = true;
917     PatchedValue_NeedsUpdate = true;
918     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
919     ResultsUpdateWorkerThread.RunWorkerAsync();
920     }
921     else
922     {
923     sbyte value = Convert.ToSByte(item.SubItems[col_Found_Value].Text, 16);
924 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
925 william 230 timer_update_results.Enabled = false;
926     patcher.ShowDialog();
927     timer_update_results.Enabled = true;
928     PatchedValue_NeedsUpdate = true;
929     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
930     ResultsUpdateWorkerThread.RunWorkerAsync();
931     }
932     break;
933     case SearchDataTypes._16bits:
934     if (_result.IsUnsigned)
935     {
936     ushort value = Convert.ToUInt16(item.SubItems[col_Found_Value].Text, 16);
937 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
938 william 230 timer_update_results.Enabled = false;
939     patcher.ShowDialog();
940     timer_update_results.Enabled = true;
941     PatchedValue_NeedsUpdate = true;
942     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
943     ResultsUpdateWorkerThread.RunWorkerAsync();
944     }
945     else
946     {
947     short value = Convert.ToInt16(item.SubItems[col_Found_Value].Text, 16);
948 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
949 william 230 timer_update_results.Enabled = false;
950     patcher.ShowDialog();
951     timer_update_results.Enabled = true;
952     PatchedValue_NeedsUpdate = true;
953     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
954     ResultsUpdateWorkerThread.RunWorkerAsync();
955     }
956     break;
957     case SearchDataTypes._32bits:
958     if (_result.IsUnsigned)
959     {
960     uint value = Convert.ToUInt32(item.SubItems[col_Found_Value].Text, 16);
961 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
962 william 230 timer_update_results.Enabled = false;
963     patcher.ShowDialog();
964     timer_update_results.Enabled = true;
965     PatchedValue_NeedsUpdate = true;
966     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
967     ResultsUpdateWorkerThread.RunWorkerAsync();
968     }
969     else
970     {
971     int value = Convert.ToInt32(item.SubItems[col_Found_Value].Text, 16);
972 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
973 william 230 timer_update_results.Enabled = false;
974     patcher.ShowDialog();
975     timer_update_results.Enabled = true;
976     PatchedValue_NeedsUpdate = true;
977     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
978     ResultsUpdateWorkerThread.RunWorkerAsync();
979     }
980     break;
981     case SearchDataTypes._64bits:
982     if (_result.IsUnsigned)
983     {
984     ulong value = Convert.ToUInt32(item.SubItems[col_Found_Value].Text, 16);
985 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
986 william 230 timer_update_results.Enabled = false;
987     patcher.ShowDialog();
988     timer_update_results.Enabled = true;
989     PatchedValue_NeedsUpdate = true;
990     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
991     ResultsUpdateWorkerThread.RunWorkerAsync();
992     }
993     else
994     {
995     long value = Convert.ToInt32(item.SubItems[col_Found_Value].Text, 16);
996 william 243 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
997 william 230 timer_update_results.Enabled = false;
998     patcher.ShowDialog();
999     timer_update_results.Enabled = true;
1000     PatchedValue_NeedsUpdate = true;
1001     if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1002     ResultsUpdateWorkerThread.RunWorkerAsync();
1003     }
1004     break;
1005     }
1006     }
1007     else
1008     {
1009    
1010     ListViewItem item = lstPatchList.Items[index];
1011     ResultDataType _result = (ResultDataType)item.Tag;
1012     patch_list.Add(_result);
1013     }
1014     }
1015    
1016     if (patch_list.Count > 0)
1017     {
1018 william 243 SearchRangePatcher rangePatcher = new SearchRangePatcher((IAcceptsProcessAndConfig)this, patch_list);
1019 william 230 rangePatcher.ShowDialog();
1020     }
1021    
1022     #endregion
1023     }
1024     private void mnuItemPatchSelectedEntry_Click(object sender, EventArgs e)
1025     {
1026     if (!(lstPatchList.SelectedItems.Count == 1)) return;
1027     PatchRange(true);
1028     }
1029    
1030     private void mnuItemPatchSelectedRange_Click(object sender, EventArgs e)
1031     {
1032     if (!(lstPatchList.SelectedItems.Count >= 1)) return;
1033     PatchRange(false);
1034     }
1035    
1036     private void mnuItemFreezeSelectedPatches_Click(object sender, EventArgs e)
1037     {
1038     if (!(lstPatchList.SelectedItems.Count > 0)) return;
1039     //if (SearchArgs == null) return;
1040     try
1041     {
1042 william 477 lstPatchList.ProcessID = this.AcceptedProcess.Id;
1043 william 230 this.FreezeResultsUpdate();
1044     for (int i = 0; i < lstPatchList.SelectedIndices.Count; i++)
1045     {
1046     lstPatchList.FreezeItem(lstPatchList.SelectedIndices[i]);
1047     }
1048     // force thaw and update
1049     this.ThawResultsUpdate();
1050     this.Update();
1051     }
1052     catch (Exception ex)
1053     {
1054     Debug.WriteLine(ex.ToString());
1055     }
1056     }
1057    
1058     private void mnuItemThawSelectedPatches_Click(object sender, EventArgs e)
1059     {
1060     if (!(lstPatchList.SelectedItems.Count > 0)) return;
1061     //if (SearchArgs == null) return;
1062     try
1063     {
1064 william 477 lstPatchList.ProcessID = this.AcceptedProcess.Id;
1065 william 230 this.FreezeResultsUpdate();
1066     for (int i = 0; i < lstPatchList.SelectedIndices.Count; i++)
1067     {
1068     lstPatchList.ThawItem(lstPatchList.SelectedIndices[i]);
1069     }
1070     // force thaw and update
1071     this.ThawResultsUpdate();
1072     this.Update();
1073     }
1074     catch (Exception ex)
1075     {
1076     Debug.WriteLine(ex.ToString());
1077     }
1078     }
1079 william 540
1080 william 230 private void SearchWorkerThread_DoWork(object sender, DoWorkEventArgs e)
1081     {
1082 william 410 try
1083 william 483 {
1084 william 410 Stopwatch st = new Stopwatch();
1085     st.Start();
1086 william 392
1087 william 410 Stopwatch st_first_search = new Stopwatch();
1088     Stopwatch st_nonrange_search = new Stopwatch();
1089     Stopwatch st_ranged_search = new Stopwatch();
1090 william 392
1091 william 410 e.Result = st;
1092     //List<ResultType<object>> tmp_Results = new List<ResultType<object>>();
1093 william 476 List<ResultType<ulong>> second_tmp_Results = new List<ResultType<ulong>>();
1094 william 410 //const int ElementsBeforeDisplay = 100;
1095     SearchArgs.LogSearchOptions();
1096     uint STEP_SIZE = (uint)SearchArgs.DataType / 8;
1097 william 399
1098 william 410 bool unsigned = SearchArgs.IsUnsignedDataType;
1099     SearchDataTypes sdt = SearchArgs.DataType;
1100     //byte[] buffered_mem = new byte[(MemoryRangeSize - MemoryRangeStart)]; // throws OutOfMemoryException if size is over 2G
1101     logger.Debug.WriteLine(string.Format("Buffered Memory Size -> 0x{0:x8}", MemoryRangeSize - MemoryRangeStart));
1102 william 517 UpdateProgress(0, string.Format("Search is Warming Up...Please Wait..."));
1103     //new Action<int, string>(UpdateProgress).Invoke(0, string.Format("Search is Warming Up...Please Wait..."));
1104 william 410 Stopwatch provider_st = new Stopwatch();
1105     provider_st.Start();
1106     using (GenericMemoryProvider provider = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1107     {
1108 william 483
1109 william 459 if (SearchArgs.IsFirstSearch)
1110     {
1111 william 560 #region FirstSearch
1112 william 460 provider.OpenProvider();
1113     int count = (int)((MemoryRangeSize - MemoryRangeStart) / STEP_SIZE);
1114 william 560 SearchResultWriter writer = new SearchResultWriter((int)(count), SearchGuid);
1115 william 525 int Last_Whole_Percent_Done = 0;
1116 william 547 uint size = 0;
1117     switch (sdt)
1118     {
1119 william 565 case SearchDataTypes._8bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1120     case SearchDataTypes._16bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1121     case SearchDataTypes._32bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1122     case SearchDataTypes._64bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1123 william 547 }
1124     //uint size = STEP_SIZE * 4096;
1125 william 560 for (uint i = MemoryRangeStart; i < MemoryRangeSize; i += size)
1126 william 521 {
1127 william 560
1128     int bytesRead = 0;
1129 william 521 byte[] data = new byte[size];
1130     provider.ReadProcessMemoryAtOnce(i, size, out bytesRead, out data);
1131     string message = string.Format(" -> Reading Address: 0x{0:x8}", (i + MemoryRangeStart));
1132     double double_percent_done = 100.0 * (double)((double)i / (double)MemoryRangeSize);
1133 william 525 int int_percent_done = (int)double_percent_done;
1134 william 560 if ((int_percent_done != Last_Whole_Percent_Done))// && (i % 10000) == 0)
1135 william 521 {
1136     UpdateProgress((int)double_percent_done, message);
1137 william 525 Last_Whole_Percent_Done = int_percent_done;
1138 william 521 }
1139    
1140 william 526 uint address_index = i;
1141 william 521 #region comparison and serialization
1142     switch (sdt)
1143     {
1144     case SearchDataTypes._8bits:
1145     if (unsigned)
1146     {
1147     #region 8bits - unsigned
1148 william 534 var t_data = data;
1149 william 521 foreach (var Value in t_data)
1150     {
1151     if (SearchWorkerThread.CancellationPending) { break; }
1152 william 526 using (_8bit_unsigned_comparer_ comparer = new _8bit_unsigned_comparer_(SearchArgs, address_index))
1153 william 521 {
1154     byte value = 0;
1155     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1156     {
1157     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1158     {
1159     try
1160     {
1161     gmp.OpenProvider();
1162 william 526 gmp.ReadMemory(address_index, out value);
1163 william 521 gmp.CloseProvider();
1164     }
1165     catch (Exception ex)
1166     {
1167     logger.VerboseError.WriteLine(ex.ToString());
1168     }
1169     }
1170     comparer.Value = value;
1171     }
1172     else
1173     {
1174     value = Convert.ToByte(SearchArgs.CompareStartValue);
1175     comparer.Value = value;
1176     }
1177     if (comparer.Compare(Convert.ToByte(Value), value))
1178     {
1179     writer.WriteResult<byte>(comparer.Address, comparer.Value);
1180     }
1181     }
1182 william 526 address_index += STEP_SIZE;
1183 william 521 }
1184     #endregion
1185     }
1186     else
1187     {
1188     #region 8bits - signed
1189 william 534 var t_data = data;
1190 william 521 foreach (var Value in t_data)
1191     {
1192     if (SearchWorkerThread.CancellationPending) { break; }
1193 william 526 using (_8bit_signed_comparer_ comparer = new _8bit_signed_comparer_(SearchArgs, address_index))
1194 william 521 {
1195     sbyte value = 0;
1196     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1197     {
1198     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1199     {
1200     try
1201     {
1202     gmp.OpenProvider();
1203 william 526 gmp.ReadMemory(address_index, out value);
1204 william 521 gmp.CloseProvider();
1205     }
1206     catch (Exception ex)
1207     {
1208     logger.VerboseError.WriteLine(ex.ToString());
1209     }
1210     }
1211     comparer.Value = value;
1212     }
1213     else
1214     {
1215     value = Convert.ToSByte(SearchArgs.CompareStartValue);
1216     comparer.Value = value;
1217     }
1218     if (comparer.Compare(Convert.ToSByte(Value), value))
1219     {
1220     writer.WriteResult<sbyte>(comparer.Address, comparer.Value);
1221     }
1222     }
1223 william 526 address_index += STEP_SIZE;
1224 william 521 }
1225     #endregion
1226     } break;
1227     case SearchDataTypes._16bits:
1228     if (unsigned)
1229     {
1230     #region 16bits - unsigned
1231 william 532 var t_data = BitTools.ConvertByteArray<ushort>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1232 william 560 foreach (var Value in t_data)
1233     {
1234     if (SearchWorkerThread.CancellationPending) { break; }
1235     using (_16bit_unsigned_comparer_ comparer = new _16bit_unsigned_comparer_(SearchArgs, address_index))
1236     {
1237     ushort value = 0;
1238     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1239     {
1240     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1241     {
1242     try
1243     {
1244     gmp.OpenProvider();
1245     gmp.ReadMemory(address_index, out value);
1246     gmp.CloseProvider();
1247     }
1248     catch (Exception ex)
1249     {
1250     logger.VerboseError.WriteLine(ex.ToString());
1251     }
1252     }
1253     comparer.Value = value;
1254     }
1255     else
1256     {
1257     value = Convert.ToUInt16(SearchArgs.CompareStartValue);
1258     comparer.Value = value;
1259     }
1260     if (comparer.Compare(Convert.ToUInt16(Value), value))
1261     {
1262     writer.WriteResult<ushort>(comparer.Address, comparer.Value);
1263     }
1264     }
1265     address_index += STEP_SIZE;
1266     }
1267 william 521 #endregion
1268     }
1269     else
1270     {
1271     #region 16bits - signed
1272 william 532 var t_data = BitTools.ConvertByteArray<short>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1273 william 560 foreach (var Value in t_data)
1274     {
1275     if (SearchWorkerThread.CancellationPending) { break; }
1276     using (_16bit_signed_comparer_ comparer = new _16bit_signed_comparer_(SearchArgs, address_index))
1277     {
1278     short value = 0;
1279     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1280     {
1281     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1282     {
1283     try
1284     {
1285     gmp.OpenProvider();
1286     gmp.ReadMemory(address_index, out value);
1287     gmp.CloseProvider();
1288     }
1289     catch (Exception ex)
1290     {
1291     logger.VerboseError.WriteLine(ex.ToString());
1292     }
1293     }
1294     comparer.Value = value;
1295     }
1296     else
1297     {
1298     value = Convert.ToInt16(SearchArgs.CompareStartValue);
1299     comparer.Value = value;
1300     }
1301     if (comparer.Compare(Convert.ToSByte(Value), value))
1302     {
1303     writer.WriteResult<short>(comparer.Address, comparer.Value);
1304     }
1305     }
1306     address_index += STEP_SIZE;
1307     }
1308 william 521 #endregion
1309     } break;
1310     case SearchDataTypes._32bits:
1311     if (unsigned)
1312     {
1313     #region 32bits - unsigned
1314 william 532 var t_data = BitTools.ConvertByteArray<uint>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1315 william 560 foreach (var Value in t_data)
1316     {
1317     if (SearchWorkerThread.CancellationPending) { break; }
1318     using (_32bit_unsigned_comparer_ comparer = new _32bit_unsigned_comparer_(SearchArgs, address_index))
1319     {
1320     uint value = 0;
1321     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1322     {
1323     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1324     {
1325     try
1326     {
1327     gmp.OpenProvider();
1328     gmp.ReadMemory(address_index, out value);
1329     gmp.CloseProvider();
1330     }
1331     catch (Exception ex)
1332     {
1333     logger.VerboseError.WriteLine(ex.ToString());
1334     }
1335     }
1336     comparer.Value = value;
1337     }
1338     else
1339     {
1340     value = Convert.ToUInt32(SearchArgs.CompareStartValue);
1341     comparer.Value = value;
1342     }
1343     if (comparer.Compare(Convert.ToUInt32(Value), value))
1344     {
1345     writer.WriteResult<uint>(comparer.Address, comparer.Value);
1346     }
1347     }
1348     address_index += STEP_SIZE;
1349     }
1350 william 521 #endregion
1351     }
1352     else
1353     {
1354     #region 32bits - signed
1355 william 532 var t_data = BitTools.ConvertByteArray<int>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1356 william 560 foreach (var Value in t_data)
1357     {
1358     if (SearchWorkerThread.CancellationPending) { break; }
1359     using (_32bit_signed_comparer_ comparer = new _32bit_signed_comparer_(SearchArgs, address_index))
1360     {
1361     int value = 0;
1362     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1363     {
1364     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1365     {
1366     try
1367     {
1368     gmp.OpenProvider();
1369     gmp.ReadMemory(address_index, out value);
1370     gmp.CloseProvider();
1371     }
1372     catch (Exception ex)
1373     {
1374     logger.VerboseError.WriteLine(ex.ToString());
1375     }
1376     }
1377     comparer.Value = value;
1378     }
1379     else
1380     {
1381     value = Convert.ToInt32(SearchArgs.CompareStartValue);
1382     comparer.Value = value;
1383     }
1384     if (comparer.Compare(Convert.ToInt32(Value), value))
1385     {
1386     writer.WriteResult<int>(comparer.Address, comparer.Value);
1387     }
1388     }
1389     address_index += STEP_SIZE;
1390     }
1391 william 521 #endregion
1392     } break;
1393     case SearchDataTypes._64bits:
1394     if (unsigned)
1395     {
1396     #region 64bits - unsigned
1397 william 532 var t_data = BitTools.ConvertByteArray<ulong>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1398 william 560 foreach (var Value in t_data)
1399     {
1400     if (SearchWorkerThread.CancellationPending) { break; }
1401     using (_64bit_unsigned_comparer_ comparer = new _64bit_unsigned_comparer_(SearchArgs, address_index))
1402     {
1403     ulong value = 0;
1404     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1405     {
1406     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1407     {
1408     try
1409     {
1410     gmp.OpenProvider();
1411     gmp.ReadMemory(address_index, out value);
1412     gmp.CloseProvider();
1413     }
1414     catch (Exception ex)
1415     {
1416     logger.VerboseError.WriteLine(ex.ToString());
1417     }
1418     }
1419     comparer.Value = value;
1420     }
1421     else
1422     {
1423     value = Convert.ToUInt64(SearchArgs.CompareStartValue);
1424     comparer.Value = value;
1425     }
1426     if (comparer.Compare(Convert.ToUInt64(Value), value))
1427     {
1428     writer.WriteResult<ulong>(comparer.Address, comparer.Value);
1429     }
1430     }
1431     address_index += STEP_SIZE;
1432     }
1433 william 521 #endregion
1434     }
1435     else
1436     {
1437     #region 64bits - signed
1438 william 532 var t_data = BitTools.ConvertByteArray<long>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1439 william 560 foreach (var Value in t_data)
1440     {
1441     if (SearchWorkerThread.CancellationPending) { break; }
1442     using (_64bit_signed_comparer_ comparer = new _64bit_signed_comparer_(SearchArgs, address_index))
1443     {
1444     long value = 0;
1445     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1446     {
1447     using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1448     {
1449     try
1450     {
1451     gmp.OpenProvider();
1452     gmp.ReadMemory(address_index, out value);
1453     gmp.CloseProvider();
1454     }
1455     catch (Exception ex)
1456     {
1457     logger.VerboseError.WriteLine(ex.ToString());
1458     }
1459     }
1460     comparer.Value = value;
1461     }
1462     else
1463     {
1464     value = Convert.ToInt64(SearchArgs.CompareStartValue);
1465     comparer.Value = value;
1466     }
1467     if (comparer.Compare(Convert.ToInt64(Value), value))
1468     {
1469     writer.WriteResult<long>(comparer.Address, comparer.Value);
1470     }
1471     }
1472     address_index += STEP_SIZE;
1473     }
1474 william 521 #endregion
1475     } break;
1476 william 560
1477 william 521 }
1478     #endregion
1479    
1480     if (SearchWorkerThread.CancellationPending)
1481     {
1482     provider_st.Stop();
1483     st.Stop();
1484     writer.CancelRequest();
1485     writer.Dispose();
1486     writer = null;
1487     e.Result = true;
1488     provider.CloseProvider();
1489     return;
1490     }
1491     }
1492    
1493 william 460 if (SearchWorkerThread.CancellationPending)
1494     {
1495     provider_st.Stop();
1496     st.Stop();
1497     writer.CancelRequest();
1498     writer.Dispose();
1499     writer = null;
1500     e.Result = true;
1501     provider.CloseProvider();
1502     return;
1503     }
1504     writer.Dispose();
1505     writer = null;
1506     provider.CloseProvider();
1507 william 560 #endregion
1508 william 561
1509     GC.Collect(); // force gc collection
1510 william 459 }
1511     else
1512     {
1513 william 560 #region SubsequentSearch
1514     Guid new_SearchGuid = GuidTools.IncrementGuid(SearchGuid);
1515 william 549 int Last_Whole_Percent_Done = 0;
1516 william 526 // need to get the address list
1517 william 560 uint[] reader_addresses = new uint[0];
1518     #region Address pre-population
1519     using (SearchResultReader reader = new SearchResultReader(SearchGuid, true, SearchArgs.IsUnsignedDataType, SearchArgs.DataType, new Action<int, string>(UpdateProgress), new Func<bool>(ShouldCancelAnySearchOperation))) // delete the file on dispose
1520 william 526 {
1521 william 560 reader_addresses = new uint[reader.ResultCount];
1522 william 549 // pre-populate the addresses array
1523     Stopwatch st_profiler_reader_addresses = new Stopwatch();
1524     st_profiler_reader_addresses.Start();
1525     int reader_address_index = 0;
1526 william 554 foreach (var k in reader)
1527 william 549 {
1528 william 560
1529 william 549 if (SearchWorkerThread.CancellationPending) { st_profiler_reader_addresses.Stop(); break; }
1530     reader_addresses[reader_address_index] = k.Address;
1531    
1532     string message = string.Format(" -> Creating Address Array (0x{0} of 0x{1})", reader_address_index.ToString("X"), reader_addresses.Length.ToString("X"));
1533     double double_percent_done = 100.0 * (double)((double)reader_address_index / (double)reader_addresses.Length);
1534     int int_percent_done = (int)double_percent_done;
1535     if ((int_percent_done != Last_Whole_Percent_Done))// && (reader_address_index % 10000) == 0)
1536     {
1537     UpdateProgress((int)double_percent_done, message);
1538     Last_Whole_Percent_Done = int_percent_done;
1539     logger.Profiler.WriteLine("It has taken {0} seconds to pre-populate the address array.", st_profiler_reader_addresses.Elapsed.TotalSeconds);
1540     }
1541    
1542     reader_address_index++;
1543     }
1544     st_profiler_reader_addresses.Stop();
1545     logger.Profiler.WriteLine("It took a total of {0} seconds to pre-populate the address array.", st_profiler_reader_addresses.Elapsed.TotalSeconds);
1546 william 560 }
1547     GC.Collect(); // force gc collection
1548     #endregion
1549    
1550     #region result writing
1551     using (SearchResultWriter writer = new SearchResultWriter(0, new_SearchGuid))
1552     {
1553     Last_Whole_Percent_Done = 0;
1554     //int index = 0;
1555    
1556     provider.OpenProvider();
1557     //int count = (int)((MemoryRangeSize - MemoryRangeStart) / STEP_SIZE);
1558     //SearchResultWriter writer = new SearchResultWriter((int)(count), SearchGuid);
1559 william 564 uint size = 0;
1560 william 560 switch (sdt)
1561 william 527 {
1562 william 565 case SearchDataTypes._8bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1563     case SearchDataTypes._16bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1564     case SearchDataTypes._32bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1565     case SearchDataTypes._64bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1566 william 560 }
1567     //size = STEP_SIZE * 4096;
1568     for (uint i = MemoryRangeStart; i < MemoryRangeSize; i += size)
1569     {
1570 william 542
1571 william 560 int bytesRead = 0;
1572     byte[] data = new byte[size];
1573     provider.ReadProcessMemoryAtOnce(i, size, out bytesRead, out data);
1574     string message = string.Format(" -> Reading Address: 0x{0:x8}", (i + MemoryRangeStart));
1575     double double_percent_done = 100.0 * (double)((double)i / (double)MemoryRangeSize);
1576     int int_percent_done = (int)double_percent_done;
1577     if ((int_percent_done != Last_Whole_Percent_Done))// && (i % 10000) == 0)
1578 william 546 {
1579 william 563 UpdateProgress(int_percent_done, message);
1580 william 560 Last_Whole_Percent_Done = int_percent_done;
1581 william 546 }
1582 william 560
1583     uint address_index = i;
1584 william 563 int inner_Last_Whole_Percent_Done = 0;
1585 william 560 #region comparison and serialization
1586     switch (sdt)
1587 william 527 {
1588 william 560 case SearchDataTypes._8bits:
1589     if (unsigned)
1590     {
1591     #region 8bits - unsigned
1592     var t_data = data;
1593     foreach (var Value in t_data)
1594 william 545 {
1595 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1596     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1597     int inner_int_percent_done = (int)inner_double_percent_done;
1598     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1599     {
1600     UpdateProgress(inner_int_percent_done, inner_message);
1601     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1602     }
1603 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1604     if (!reader_addresses.Contains(address_index))
1605 william 545 {
1606 william 562 address_index += STEP_SIZE;
1607 william 560 continue;
1608     }
1609     using (_8bit_unsigned_comparer_ comparer = new _8bit_unsigned_comparer_(SearchArgs, address_index))
1610     {
1611     byte value = 0;
1612     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1613 william 548 {
1614 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1615 william 545 {
1616 william 560 try
1617 william 545 {
1618 william 560 gmp.OpenProvider();
1619     gmp.ReadMemory(address_index, out value);
1620     gmp.CloseProvider();
1621 william 545 }
1622 william 560 catch (Exception ex)
1623     {
1624     logger.VerboseError.WriteLine(ex.ToString());
1625     }
1626 william 545 }
1627 william 560 comparer.Value = value;
1628 william 545 }
1629 william 560 else
1630     {
1631     value = Convert.ToByte(SearchArgs.CompareStartValue);
1632     comparer.Value = value;
1633     }
1634     if (comparer.Compare(Convert.ToByte(Value), value))
1635     {
1636     writer.WriteResult<byte>(comparer.Address, comparer.Value);
1637     }
1638 william 545 }
1639 william 560 address_index += STEP_SIZE;
1640 william 545 }
1641 william 560 #endregion
1642     }
1643     else
1644     {
1645     #region 8bits - signed
1646     var t_data = data;
1647     foreach (var Value in t_data)
1648 william 545 {
1649 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1650     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1651     int inner_int_percent_done = (int)inner_double_percent_done;
1652     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1653     {
1654     UpdateProgress(inner_int_percent_done, inner_message);
1655     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1656     }
1657 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1658     if (!reader_addresses.Contains(address_index))
1659 william 545 {
1660 william 562 address_index += STEP_SIZE;
1661 william 560 continue;
1662     }
1663     using (_8bit_signed_comparer_ comparer = new _8bit_signed_comparer_(SearchArgs, address_index))
1664     {
1665     sbyte value = 0;
1666     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1667 william 548 {
1668 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1669 william 545 {
1670 william 560 try
1671 william 545 {
1672 william 560 gmp.OpenProvider();
1673     gmp.ReadMemory(address_index, out value);
1674     gmp.CloseProvider();
1675 william 545 }
1676 william 560 catch (Exception ex)
1677     {
1678     logger.VerboseError.WriteLine(ex.ToString());
1679     }
1680 william 545 }
1681 william 560 comparer.Value = value;
1682 william 545 }
1683 william 560 else
1684     {
1685     value = Convert.ToSByte(SearchArgs.CompareStartValue);
1686     comparer.Value = value;
1687     }
1688     if (comparer.Compare(Convert.ToSByte(Value), value))
1689     {
1690     writer.WriteResult<sbyte>(comparer.Address, comparer.Value);
1691     }
1692 william 545 }
1693 william 560 address_index += STEP_SIZE;
1694     }
1695     #endregion
1696     } break;
1697     case SearchDataTypes._16bits:
1698     if (unsigned)
1699     {
1700     #region 16bits - unsigned
1701     var t_data = BitTools.ConvertByteArray<ushort>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1702     foreach (var Value in t_data)
1703 william 545 {
1704 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1705     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1706     int inner_int_percent_done = (int)inner_double_percent_done;
1707     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1708     {
1709     UpdateProgress(inner_int_percent_done, inner_message);
1710     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1711     }
1712 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1713     if (!reader_addresses.Contains(address_index))
1714 william 545 {
1715 william 562 address_index += STEP_SIZE;
1716 william 560 continue;
1717     }
1718     using (_16bit_unsigned_comparer_ comparer = new _16bit_unsigned_comparer_(SearchArgs, address_index))
1719     {
1720     ushort value = 0;
1721     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1722 william 548 {
1723 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1724 william 545 {
1725 william 560 try
1726 william 545 {
1727 william 560 gmp.OpenProvider();
1728     gmp.ReadMemory(address_index, out value);
1729     gmp.CloseProvider();
1730 william 545 }
1731 william 560 catch (Exception ex)
1732     {
1733     logger.VerboseError.WriteLine(ex.ToString());
1734     }
1735 william 545 }
1736 william 560 comparer.Value = value;
1737 william 545 }
1738 william 560 else
1739     {
1740     value = Convert.ToUInt16(SearchArgs.CompareStartValue);
1741     comparer.Value = value;
1742     }
1743     if (comparer.Compare(Convert.ToUInt16(Value), value))
1744     {
1745     writer.WriteResult<ushort>(comparer.Address, comparer.Value);
1746     }
1747 william 545 }
1748 william 560 address_index += STEP_SIZE;
1749 william 545 }
1750 william 560 #endregion
1751     }
1752     else
1753     {
1754     #region 16bits - signed
1755     var t_data = BitTools.ConvertByteArray<short>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1756     foreach (var Value in t_data)
1757 william 545 {
1758 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1759     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1760     int inner_int_percent_done = (int)inner_double_percent_done;
1761     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1762     {
1763     UpdateProgress(inner_int_percent_done, inner_message);
1764     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1765     }
1766 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1767     if (!reader_addresses.Contains(address_index))
1768 william 545 {
1769 william 562 address_index += STEP_SIZE;
1770 william 560 continue;
1771     }
1772     using (_16bit_signed_comparer_ comparer = new _16bit_signed_comparer_(SearchArgs, address_index))
1773     {
1774     short value = 0;
1775     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1776 william 548 {
1777 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1778 william 545 {
1779 william 560 try
1780 william 545 {
1781 william 560 gmp.OpenProvider();
1782     gmp.ReadMemory(address_index, out value);
1783     gmp.CloseProvider();
1784 william 545 }
1785 william 560 catch (Exception ex)
1786     {
1787     logger.VerboseError.WriteLine(ex.ToString());
1788     }
1789 william 545 }
1790 william 560 comparer.Value = value;
1791 william 545 }
1792 william 560 else
1793     {
1794     value = Convert.ToInt16(SearchArgs.CompareStartValue);
1795     comparer.Value = value;
1796     }
1797     if (comparer.Compare(Convert.ToSByte(Value), value))
1798     {
1799     writer.WriteResult<short>(comparer.Address, comparer.Value);
1800     }
1801 william 545 }
1802 william 560 address_index += STEP_SIZE;
1803     }
1804     #endregion
1805     } break;
1806     case SearchDataTypes._32bits:
1807     if (unsigned)
1808     {
1809     #region 32bits - unsigned
1810     var t_data = BitTools.ConvertByteArray<uint>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1811     foreach (var Value in t_data)
1812 william 545 {
1813 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1814     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1815     int inner_int_percent_done = (int)inner_double_percent_done;
1816     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1817     {
1818     UpdateProgress(inner_int_percent_done, inner_message);
1819     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1820     }
1821 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1822     if (!reader_addresses.Contains(address_index))
1823 william 545 {
1824 william 562 address_index += STEP_SIZE;
1825 william 560 continue;
1826     }
1827     using (_32bit_unsigned_comparer_ comparer = new _32bit_unsigned_comparer_(SearchArgs, address_index))
1828     {
1829     uint value = 0;
1830     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1831 william 548 {
1832 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1833 william 545 {
1834 william 560 try
1835 william 545 {
1836 william 560 gmp.OpenProvider();
1837     gmp.ReadMemory(address_index, out value);
1838     gmp.CloseProvider();
1839 william 545 }
1840 william 560 catch (Exception ex)
1841     {
1842     logger.VerboseError.WriteLine(ex.ToString());
1843     }
1844 william 545 }
1845 william 560 comparer.Value = value;
1846 william 545 }
1847 william 560 else
1848     {
1849     value = Convert.ToUInt32(SearchArgs.CompareStartValue);
1850     comparer.Value = value;
1851     }
1852     if (comparer.Compare(Convert.ToUInt32(Value), value))
1853     {
1854     writer.WriteResult<uint>(comparer.Address, comparer.Value);
1855     }
1856 william 545 }
1857 william 560 address_index += STEP_SIZE;
1858 william 545 }
1859 william 560 #endregion
1860     }
1861     else
1862     {
1863     #region 32bits - signed
1864     var t_data = BitTools.ConvertByteArray<int>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1865     foreach (var Value in t_data)
1866 william 545 {
1867 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1868     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1869     int inner_int_percent_done = (int)inner_double_percent_done;
1870     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1871     {
1872     UpdateProgress(inner_int_percent_done, inner_message);
1873     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1874     }
1875 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1876     if (!reader_addresses.Contains(address_index))
1877 william 545 {
1878 william 562 address_index += STEP_SIZE;
1879 william 560 continue;
1880     }
1881     using (_32bit_signed_comparer_ comparer = new _32bit_signed_comparer_(SearchArgs, address_index))
1882     {
1883     int value = 0;
1884     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1885 william 548 {
1886 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1887 william 545 {
1888 william 560 try
1889 william 545 {
1890 william 560 gmp.OpenProvider();
1891     gmp.ReadMemory(address_index, out value);
1892     gmp.CloseProvider();
1893 william 545 }
1894 william 560 catch (Exception ex)
1895     {
1896     logger.VerboseError.WriteLine(ex.ToString());
1897     }
1898 william 545 }
1899 william 560 comparer.Value = value;
1900 william 545 }
1901 william 560 else
1902     {
1903     value = Convert.ToInt32(SearchArgs.CompareStartValue);
1904     comparer.Value = value;
1905     }
1906     if (comparer.Compare(Convert.ToInt32(Value), value))
1907     {
1908     writer.WriteResult<int>(comparer.Address, comparer.Value);
1909     }
1910 william 545 }
1911 william 560 address_index += STEP_SIZE;
1912     }
1913     #endregion
1914     } break;
1915     case SearchDataTypes._64bits:
1916     if (unsigned)
1917     {
1918     #region 64bits - unsigned
1919     var t_data = BitTools.ConvertByteArray<ulong>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1920     foreach (var Value in t_data)
1921 william 545 {
1922 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1923     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1924     int inner_int_percent_done = (int)inner_double_percent_done;
1925     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1926     {
1927     UpdateProgress(inner_int_percent_done, inner_message);
1928     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1929     }
1930 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1931     if (!reader_addresses.Contains(address_index))
1932 william 545 {
1933 william 562 address_index += STEP_SIZE;
1934 william 560 continue;
1935     }
1936     using (_64bit_unsigned_comparer_ comparer = new _64bit_unsigned_comparer_(SearchArgs, address_index))
1937     {
1938     ulong value = 0;
1939     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1940 william 548 {
1941 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1942 william 545 {
1943 william 560 try
1944 william 545 {
1945 william 560 gmp.OpenProvider();
1946     gmp.ReadMemory(address_index, out value);
1947     gmp.CloseProvider();
1948 william 545 }
1949 william 560 catch (Exception ex)
1950     {
1951     logger.VerboseError.WriteLine(ex.ToString());
1952     }
1953 william 545 }
1954 william 560 comparer.Value = value;
1955 william 545 }
1956 william 560 else
1957     {
1958     value = Convert.ToUInt64(SearchArgs.CompareStartValue);
1959     comparer.Value = value;
1960     }
1961     if (comparer.Compare(Convert.ToUInt64(Value), value))
1962     {
1963     writer.WriteResult<ulong>(comparer.Address, comparer.Value);
1964     }
1965 william 545 }
1966 william 560 address_index += STEP_SIZE;
1967 william 545 }
1968 william 560 #endregion
1969     }
1970     else
1971     {
1972     #region 64bits - signed
1973     var t_data = BitTools.ConvertByteArray<long>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1974     foreach (var Value in t_data)
1975 william 545 {
1976 william 563 string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1977     double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)reader_addresses.Length);
1978     int inner_int_percent_done = (int)inner_double_percent_done;
1979     if ((inner_int_percent_done != inner_Last_Whole_Percent_Done))// && (address_index % 10000) == 0)
1980     {
1981     UpdateProgress(inner_int_percent_done, inner_message);
1982     inner_Last_Whole_Percent_Done = inner_int_percent_done;
1983     }
1984 william 560 if (SearchWorkerThread.CancellationPending) { break; }
1985     if (!reader_addresses.Contains(address_index))
1986 william 545 {
1987 william 562 address_index += STEP_SIZE;
1988 william 560 continue;
1989     }
1990     using (_64bit_signed_comparer_ comparer = new _64bit_signed_comparer_(SearchArgs, address_index))
1991     {
1992     long value = 0;
1993     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1994 william 548 {
1995 william 560 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1996 william 545 {
1997 william 560 try
1998 william 545 {
1999 william 560 gmp.OpenProvider();
2000     gmp.ReadMemory(address_index, out value);
2001     gmp.CloseProvider();
2002 william 545 }
2003 william 560 catch (Exception ex)
2004     {
2005     logger.VerboseError.WriteLine(ex.ToString());
2006     }
2007 william 545 }
2008 william 560 comparer.Value = value;
2009 william 545 }
2010 william 560 else
2011     {
2012     value = Convert.ToInt64(SearchArgs.CompareStartValue);
2013     comparer.Value = value;
2014     }
2015     if (comparer.Compare(Convert.ToInt64(Value), value))
2016     {
2017     writer.WriteResult<long>(comparer.Address, comparer.Value);
2018     }
2019 william 545 }
2020 william 560 address_index += STEP_SIZE;
2021     }
2022     #endregion
2023     } break;
2024 william 530
2025 william 460 }
2026 william 545 #endregion
2027 william 496
2028 william 560 if (SearchWorkerThread.CancellationPending)
2029     {
2030     provider_st.Stop();
2031     st.Stop();
2032     writer.CancelRequest();
2033     writer.Dispose();
2034     e.Result = true;
2035     provider.CloseProvider();
2036     return;
2037     }
2038 william 527 }
2039 william 560 }
2040     #endregion
2041 william 526
2042 william 527 SearchGuid = new_SearchGuid; // update with out new guid
2043 william 560 reader_addresses = null; // free memory used by address array
2044     GC.Collect(); // force gc collection
2045     #endregion
2046 william 459 }
2047 william 560
2048 william 410 }
2049     provider_st.Stop();
2050     logger.Profiler.WriteLine("It took a total of {0} seconds for the memory provider to complete it's operation(s).", provider_st.Elapsed.TotalSeconds);
2051     //if (buffered_mem.Length == 0) { logger.Warn.WriteLine("Buffered Memory is Zero Length."); return; }
2052 william 456 //int Last_Whole_Percent_Done = 0;
2053 william 408
2054    
2055 william 410 #region Subsequent Searches
2056     //r_ms.BaseStream.Seek(0, SeekOrigin.Begin);
2057 william 408
2058    
2059 william 410 // hack to help with OutOfMemory Exceptions (OldValue and Equal compare will always add all found search results)
2060     bool NeedToCompare = true;
2061     if (SearchArgs.CompareValueType == CompareValueTypes.OldValue &&
2062     SearchArgs.CompareType == SearchCompareTypes.Equal &&
2063     SearchArgs.IsFirstSearch)
2064     {
2065     NeedToCompare = false;
2066     //second_tmp_Results = null; // Free Memory
2067     }
2068 william 408
2069 william 410 if (NeedToCompare)
2070 william 535 {
2071 william 410 #region Ranged Searches
2072     #if !DONOT_HAVE_RANGED_SEARCH_SUPPORT
2073     if (SearchArgs.CompareType == SearchCompareTypes.Between || SearchArgs.CompareType == SearchCompareTypes.NotBetween)
2074 william 409 {
2075 william 410 st_ranged_search.Start();
2076     object start, end;
2077 william 408
2078 william 410 start = SearchArgs.CompareStartValue;
2079     end = SearchArgs.CompareEndValue;
2080 william 444 using (SearchResultReader reader = new SearchResultReader(SearchGuid))
2081 william 402 {
2082 william 410 for (int i = 0; i < reader.ResultCount; i += 1)
2083 william 409 {
2084 william 410 uint address = 0;
2085 william 483 #region switch (SearchArgs.DataType)
2086 william 410 switch (SearchArgs.DataType)
2087 william 402 {
2088 william 410 case SearchDataTypes._8bits: if (unsigned) { using (ResultType<byte> result = reader.GetNextResult<byte>()) { address = result.Address; } }
2089     else { using (ResultType<sbyte> result = reader.GetNextResult<sbyte>()) { address = result.Address; } } break;
2090     case SearchDataTypes._16bits: if (unsigned) { using (ResultType<ushort> result = reader.GetNextResult<ushort>()) { address = result.Address; } }
2091     else { using (ResultType<short> result = reader.GetNextResult<short>()) { address = result.Address; } } break;
2092     case SearchDataTypes._32bits: if (unsigned) { using (ResultType<uint> result = reader.GetNextResult<uint>()) { address = result.Address; } }
2093     else { using (ResultType<int> result = reader.GetNextResult<int>()) { address = result.Address; } } break;
2094     case SearchDataTypes._64bits: if (unsigned) { using (ResultType<ulong> result = reader.GetNextResult<ulong>()) { address = result.Address; } }
2095     else { using (ResultType<long> result = reader.GetNextResult<long>()) { address = result.Address; } } break;
2096     }
2097     #endregion
2098    
2099     if (MemoryRangeStart > 0 && !SearchArgs.IsFirstSearch) { address = address - MemoryRangeStart; }
2100     //r_ms.BaseStream.Seek(address, SeekOrigin.Begin);
2101     if (SearchArgs.CompareType == SearchCompareTypes.Between)
2102     {
2103     using (InRangeComparer comparer = new InRangeComparer(address, 0))
2104 william 409 {
2105 william 410 if (comparer.Compare(start, end, SearchArgs.DataType, SearchArgs.IsUnsignedDataType, (IAcceptsProcessAndConfig)this))
2106     {
2107     using (ResultType<object> _tmp_result = new ResultType<object>(comparer.Address, comparer.Value))
2108     {
2109     second_tmp_Results.Add(_tmp_result);
2110     }
2111     }
2112 william 409 }
2113 william 402 }
2114 william 410 else if (SearchArgs.CompareType == SearchCompareTypes.NotBetween)
2115 william 408 {
2116 william 410 using (NotInRangeComparer comparer = new NotInRangeComparer(address, 0))
2117 william 409 {
2118 william 410 if (comparer.Compare(start, end, SearchArgs.DataType, SearchArgs.IsUnsignedDataType, (IAcceptsProcessAndConfig)this))
2119     {
2120     using (ResultType<object> _tmp_result = new ResultType<object>(comparer.Address, comparer.Value))
2121     {
2122     second_tmp_Results.Add(_tmp_result);
2123     }
2124     }
2125 william 409 }
2126 william 408 }
2127 william 410 else
2128 william 408 {
2129 william 410 throw new InvalidOperationException("Encounted unkown range search type: " + SearchArgs.CompareType);
2130 william 408 }
2131 william 410 double double_percent_done = 100.0 * (double)((double)i / (double)reader.ResultCount);
2132     int int_percent_done = (int)double_percent_done;
2133     if (int_percent_done != Last_Whole_Percent_Done)
2134 william 409 {
2135 william 410 if (int_percent_done <= 100)
2136     {
2137     resultsprogress.Value = int_percent_done;
2138     resultsprogress.Message = string.Format(" -> Reading Address: 0x{0:x8}", i + MemoryRangeStart);
2139     Last_Whole_Percent_Done = int_percent_done;
2140     }
2141 william 409 }
2142 william 408 }
2143     }
2144 william 410 st_ranged_search.Stop();
2145     logger.Profiler.WriteLine("Ranged search took a total of {0} seconds to complete.", st_ranged_search.Elapsed.TotalSeconds);
2146 william 280 }
2147 william 410 #endif
2148     #endregion
2149 william 408 }
2150     #endregion
2151 william 457 //// leave SearchArgs.Results alone, if false
2152     //if (NeedToCompare)
2153     //{
2154     // // fix addresses when memory start is not zero
2155     // if (MemoryRangeStart > 0 && SearchArgs.IsFirstSearch) { for (int i = 0; i < second_tmp_Results.Count; i++) { second_tmp_Results[i].Address = second_tmp_Results[i].Address + MemoryRangeStart; } }
2156     // using (SearchResultWriter writer = new SearchResultWriter(second_tmp_Results.Count, SearchGuid))
2157     // {
2158     // for (int i = 0; i < second_tmp_Results.Count; i++)
2159     // {
2160     // switch (sdt)
2161     // {
2162     // case SearchDataTypes._8bits:
2163     // if (unsigned) { writer.WriteResult<Byte>(second_tmp_Results[i].Address, Convert.ToByte(second_tmp_Results[i].Value)); }
2164     // else { writer.WriteResult<SByte>(second_tmp_Results[i].Address, Convert.ToSByte(second_tmp_Results[i].Value)); } break;
2165     // case SearchDataTypes._16bits:
2166     // if (unsigned) { writer.WriteResult<UInt16>(second_tmp_Results[i].Address, Convert.ToUInt16(second_tmp_Results[i].Value)); }
2167     // else { writer.WriteResult<Int16>(second_tmp_Results[i].Address, Convert.ToInt16(second_tmp_Results[i].Value)); } break;
2168     // case SearchDataTypes._32bits:
2169     // if (unsigned) { writer.WriteResult<UInt32>(second_tmp_Results[i].Address, Convert.ToUInt32(second_tmp_Results[i].Value)); }
2170     // else { writer.WriteResult<Int32>(second_tmp_Results[i].Address, Convert.ToInt32(second_tmp_Results[i].Value)); } break;
2171     // case SearchDataTypes._64bits:
2172     // if (unsigned) { writer.WriteResult<UInt64>(second_tmp_Results[i].Address, Convert.ToUInt64(second_tmp_Results[i].Value)); }
2173     // else { writer.WriteResult<Int64>(second_tmp_Results[i].Address, Convert.ToInt64(second_tmp_Results[i].Value)); } break;
2174     // }
2175     // }
2176     // }
2177     // second_tmp_Results = null; // free memory
2178     //}
2179 william 280 }
2180 william 483 catch (OutOfMemoryException ex)
2181     {
2182     e.Result = true;
2183     logger.Error.WriteLine("Encounted {0} for search: {0}", ex.GetType().Name, SearchGuid.ToString());
2184     logger.VerboseError.WriteLine(ex.ToString());
2185     MessageBox.Show(string.Format("Encounted {0} for search: {0} ... Please try again.", ex.GetType().Name, SearchGuid.ToString()), string.Format("{0} was thrown", ex.GetType().Name), MessageBoxButtons.OK, MessageBoxIcon.Error);
2186     return;
2187     }
2188 william 410 catch (Exception ex)
2189     {
2190 william 419 throw ex;
2191 william 410 }
2192 william 230 }
2193    
2194 william 408
2195    
2196 william 230 private void SearchWorkerThread_ProgressChanged(object sender, ProgressChangedEventArgs e)
2197     {
2198 william 280 //if (SearchArgs.ProgressLogger != null)
2199     //{
2200     // resultsprogress.Value = e.ProgressPercentage;
2201     // //Application.DoEvents();
2202     //}
2203 william 230 }
2204    
2205     private void SearchWorkerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2206     {
2207 william 463 try { if ((bool