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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 566 - (hide annotations) (download)
Thu Jun 6 05:52:19 2013 UTC (7 years, 4 months ago) by william
File size: 146963 byte(s)
+ optimize memory chunksize to 64MB

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