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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 564 - (hide annotations) (download)
Thu Jun 6 04:33:03 2013 UTC (7 years, 4 months ago) by william
File size: 146732 byte(s)
MB_SIZE -> MEM_CHUNK_SIZE - declare const uint at top of file beloew MEM_1MB

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