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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 593 - (show annotations) (download)
Thu Jun 6 10:39:39 2013 UTC (7 years, 3 months ago) by william
File size: 157712 byte(s)

1 #region Logging Defines
2 // include this any class or method that required logging, and comment-out what is not needed
3
4 #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 #if !USE_AUTOMATIC_MEMORY_SEARCH_RANGE
16 //#define FORCE_USE_OF_MEMORYSIZECONSTANTS // when defined wil force the use of the constants defined in MemorySizeConstants for memory search range
17 #endif
18 #define DONOT_HAVE_RANGED_SEARCH_SUPPORT // when defined, indicates that ranged searches have not been implemented
19 #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 using System;
22 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 using RomCheater.Docking.MemorySearch;
33 using libWin32.Win32.Threading;
34 using System.Threading;
35 using RomCheater.Logging;
36 using System.IO;
37 using Sojaner.MemoryScanner.MemoryProviers;
38 using RomCheater.PluginFramework.Events;
39 using System.Reflection;
40 using Sojaner.MemoryScanner;
41 using System.Collections;
42 using RomCheater.Serialization;
43 using RomCheater.Core;
44 using RomCheater.PluginFramework.Core;
45
46 namespace RomCheater.Docking
47 {
48 public partial class FloatingMemorySearcher : DockContent,
49 IAcceptsPlugin<IConfigPlugin>,
50 IAcceptsProcess<Process>,
51 IAcceptsProcessAndConfig,
52 ISearchInProgress,
53 IAcceptsBrowseMemoryRegion,
54 IAcceptsMemoryRange,
55 IAcceptPEData
56 {
57 #if INCREASE_NUMBER_OF_RESULTS_BEFORE_DISPLAY
58 const int MIN_NUMBER_OF_RESULTS_BEFORE_DISPLAY = 0x2701; // 10,000 results
59 #else
60 const int MIN_NUMBER_OF_RESULTS_BEFORE_DISPLAY = 0x03e8; // 1,000 results
61 #endif
62 private IPEDData _PEData;
63 private IPEDData PEData { get { return _PEData; } set { _PEData = value; } }
64 const uint MEM_1B = 0x1;
65 const uint MEM_1KB = 0x400;
66 const uint MEM_1MB = MEM_1KB * MEM_1KB; // 1024 * 1024 = 1MB
67 const uint MEM_CHUNK_SIZE_MB = MEM_1MB * 256; /* MEM_1MB * N = N in megabytes (in bytes) */
68 const uint MEM_CHUNK_SIZE_KB = MEM_1KB * 64; /* MEM_1KB * N = N in kilobytes (in bytes) */
69 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 */
70
71 const uint MEM_CHUNK_SIZE = MEM_CHUNK_SIZE_MB;
72
73
74 const bool USE_OLD_SEARCH_RESULTS_COMPRATOR_CODE = false;
75 const bool USE_NONRANGE_SEARCH_RESULT_READER = false;
76 private bool DefaultUnsignedState = true; // set unsigned to true
77 public FloatingMemorySearcher()
78 {
79 InitializeComponent();
80 this.AcceptedPlugin = null;
81 OnBrowseMemoryRegion = null;
82 this.AcceptedProcess = null;
83 SearchInProgess = false;
84 MemoryRangeStart = MemorySizeConstants.MinimumSearchAddress;
85 if (this.PEData != null)
86 {
87 if (this.PEData.Is32bitAssembly())
88 {
89 MemoryRangeSize = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x86;
90 }
91 else
92 {
93 MemoryRangeSize = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x64;
94 }
95 }
96 else
97 {
98 MemoryRangeSize = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x86;
99 }
100 Reload();
101 }
102 public FloatingMemorySearcher(IConfigPlugin config) : this() { this.AcceptedPlugin = config; }
103 public FloatingMemorySearcher(IConfigPlugin config, Process process) : this() { this.AcceptedPlugin = config; this.AcceptedProcess = process; }
104
105 //new Action<int, string>(UpdateProgress) to use this as a delegate
106
107 private void thread_UpdateProgress(object o)
108 {
109 IProgressMessage pm = (o as IProgressMessage);
110 if (pm == null) { return; }
111 resultsprogress.Value = pm.Progress;
112 resultsprogress.Message = pm.Message;
113 //Application.DoEvents();
114 }
115
116 private bool ShouldCancelAnySearchOperation() { return SearchWorkerThread.CancellationPending; }
117
118 private void UpdateProgress(int progress, string message)
119 {
120 // detach the progress update from execution within the current thread (so it does not block a cpu-intensive or long running sequence)
121 Thread t = new Thread(new ParameterizedThreadStart(thread_UpdateProgress));
122 t.SetApartmentState(ApartmentState.STA);
123 t.Start(new ProgressMessage(progress, message));
124 //resultsprogress.Value = progress;
125 //resultsprogress.Message = message;
126 }
127
128 #region IAcceptsProcess<Process> Members
129 private Process _AcceptedProcess;
130 public Process AcceptedProcess { get { return _AcceptedProcess; } set { _AcceptedProcess = value; UpdateAcceptedProcess(value); } }
131 #endregion
132 #region IAcceptsPlugin<IConfigPlugin> Members
133 private IConfigPlugin _AcceptedPlugin;
134 public IConfigPlugin AcceptedPlugin { get { return _AcceptedPlugin; } set { _AcceptedPlugin = value; UpdateAcceptedPlugin(value); } }
135 #endregion
136 #region IAcceptsBrowseMemoryRegion members
137 public event BaseEventHandler<BrowseMemoryRegionEvent> OnBrowseMemoryRegion;
138 #endregion
139
140 private void UpdateAcceptedPlugin(IConfigPlugin config)
141 {
142 this.lstResults.AcceptedPlugin = config;
143 this.lstPatchList.AcceptedPlugin = config;
144 if (config != null)
145 {
146 MemoryRangeStart = AcceptedPlugin.MemoryRangeStart;
147 MemoryRangeSize = AcceptedPlugin.MemoryRangeStart + AcceptedPlugin.MemoryRangeSize;
148
149 /* check for generic config and override the MemoryStart/Size parameters
150 the purpose of a config plugin supplying this data was incase a plugin was created and the memory start address and size were known ahead of time
151 however, for generic purposes use x86/x64 defaults...
152 */
153 if (config.IsGenericConfig)
154 {
155 if (this.PEData != null)
156 {
157 if (this.PEData.Is32bitAssembly())
158 {
159 this.MemoryRangeSize = MemorySizeConstants.MinimumAddress + MemorySizeConstants.MaximumAddressSize_x86;
160 }
161 else
162 {
163 this.MemoryRangeSize = MemorySizeConstants.MinimumAddress + MemorySizeConstants.MaximumAddressSize_x64;
164 }
165 }
166 else
167 {
168 this.MemoryRangeSize = MemorySizeConstants.MinimumAddress + MemorySizeConstants.MaximumAddressSize_x86;
169 }
170 }
171 }
172 }
173 private void UpdateAcceptedProcess(Process process)
174 {
175 this.lstResults.AcceptedProcess = process;
176 this.lstPatchList.AcceptedProcess = process;
177 #if USE_AUTOMATIC_MEMORY_SEARCH_RANGE && FORCE_USE_OF_MEMORYSIZECONSTANTS
178 logger.Warn.WriteLine("FloatingMemorySearcher.UpdateAcceptedProcessAndConfig(IConfigPlugin config, Process process):");
179 logger.Warn.WriteLine("Both USE_AUTOMATIC_MEMORY_SEARCH_RANGE and FORCE_USE_OF_MEMORYSIZECONSTANTS are defined");
180 logger.Warn.WriteLine("FORCE_USE_OF_MEMORYSIZECONSTANTS will take precedence and will ignore the values supplied in the memeory search range");
181 #endif
182 #if FORCE_USE_OF_MEMORYSIZECONSTANTS
183 // force use of MemorySizeConstants
184 txtMemoryRangeStart.Value = MemorySizeConstants.MinimumSearchAddress;
185 if (this.PEData != null)
186 {
187 if (this.PEData.Is32bitAssembly())
188 {
189 txtMemoryRangeSize.Value = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x86;
190 }
191 else
192 {
193 txtMemoryRangeSize.Value = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x64;
194 }
195 }
196 else
197 {
198 txtMemoryRangeSize.Value = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x86;
199 }
200
201 #endif
202 #if USE_AUTOMATIC_MEMORY_SEARCH_RANGE && !FORCE_USE_OF_MEMORYSIZECONSTANTS
203 ////// code to automatically choose the best starting memory address and size
204 //if (process != null)
205 //{
206 // string filename = process.MainModule.FileName;
207 // //string filename = @"c:\Windows\notepad.exe";
208 // PEReader peReader = new PEReader(filename);
209 //}
210 //else
211 //{
212 //txtMemoryRangeStart.Value = MemorySizeConstants.MinimumSearchAddress;
213 //txtMemoryRangeSize.Value = MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize;
214 //}
215 if (AcceptedPlugin != null)
216 {
217 MemoryRangeStart = AcceptedPlugin.MemoryRangeStart;
218 MemoryRangeSize = AcceptedPlugin.MemoryRangeStart + AcceptedPlugin.MemoryRangeSize;
219 }
220
221 #endif
222
223 }
224 #region ISearchInProgress members
225 private bool _SearchInProgess;
226 public bool SearchInProgess
227 {
228 get { return _SearchInProgess; }
229 private set
230 {
231 _SearchInProgess = value;
232 if (this.AcceptedPlugin != null)
233 this.AcceptedPlugin.SetMemorySearchReference(this);
234 }
235 }
236 private Guid _SearchGuid;
237 public Guid SearchGuid
238 {
239 get { return _SearchGuid; }
240 private set { _SearchGuid = value; }
241 }
242 #endregion
243
244 #region IAcceptsMemoryRange
245 #if !FORCE_USE_OF_MEMORYSIZECONSTANTS
246 private ulong _MemoryRangeStart;
247 private ulong _MemoryRangeSize;
248 #endif
249 public ulong MemoryRangeStart
250 {
251 get
252 {
253 #if FORCE_USE_OF_MEMORYSIZECONSTANTS
254 return MemorySizeConstants.MinimumSearchAddress;
255 #else
256 return _MemoryRangeStart;
257 #endif
258 }
259 set
260 {
261 #if !FORCE_USE_OF_MEMORYSIZECONSTANTS
262 _MemoryRangeStart = value;
263 txtMemoryRangeStart.Value = value;
264 #endif
265 }
266 }
267 public ulong MemoryRangeSize
268 {
269 get
270 {
271 #if FORCE_USE_OF_MEMORYSIZECONSTANTS
272 if (this.PEData != null)
273 {
274 if (this.PEData.Is32bitAssembly())
275 {
276 return MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x86;
277 }
278 else
279 {
280 return MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x64;
281 }
282 }
283 return MemorySizeConstants.MinimumSearchAddress + MemorySizeConstants.MaximumSearchSize_x86;
284 #else
285 return _MemoryRangeSize;
286 #endif
287 }
288 set
289 {
290 #if !FORCE_USE_OF_MEMORYSIZECONSTANTS
291 _MemoryRangeSize = value;
292 txtMemoryRangeSize.Value = value;
293 #endif
294 }
295 }
296 #endregion
297
298 public void Reload()
299 {
300 chkUnsigned.Checked = DefaultUnsignedState;
301 radio_8bits.Checked = true;
302 radiocompare_equal.Checked = true;
303 radio_oldvalue.Checked = true;
304 chkRefreshResults.Checked = true;
305 }
306 public enum eListViewResults
307 {
308 SEARCH_RESULTS_LIST = 0x3000,
309 PATCH_RESULTS_LIST = 0x3001,
310 UKNOWN_RESULTS_LIST = 0x3001
311 }
312 bool IsFirstSearch = true;
313 SearchType SearchArgs;
314 static int col_Found_Address = 1;
315 static int col_Found_Value = 2;
316 //static int col_Found_Frozen = 3; /* unused */
317 static int col_Added_Address = 1;
318 static int col_Added_Value = 2;
319 //static int col_Added_Frozen = 3; /* unused */
320 List<ListViewItem> ResultItems = new List<ListViewItem>();
321 List<ListViewItem> AddedItems = new List<ListViewItem>();
322 private bool _PatchedValue_NeedsUpdate;
323 bool PatchedValue_NeedsUpdate
324 {
325 get { if (_PatchedValue_NeedsUpdate) this.ThawResultsUpdate(); return _PatchedValue_NeedsUpdate; }
326 set { _PatchedValue_NeedsUpdate = value; if (value) this.ThawResultsUpdate(); }
327 }
328 private delegate ListViewItem ThreadSafe_GetResultItem(int index, int lv_type);
329 private ListViewItem GetResultItem(int index, int lv_type)
330 {
331 try
332 {
333 AddressValuePairList lv = null;
334 switch (lv_type)
335 {
336 case (int)eListViewResults.SEARCH_RESULTS_LIST: lv = lstResults; break;
337 case (int)eListViewResults.PATCH_RESULTS_LIST: lv = lstPatchList; break;
338 default: throw new IndexOutOfRangeException("Detected: " + Enum.GetName(typeof(eListViewResults), eListViewResults.UKNOWN_RESULTS_LIST) + " with value: " + lv_type.ToString("x4"));
339 }
340 ListViewItem item = new ListViewItem();
341 item = (ListViewItem)lv.Items[index].Clone();
342 return item;
343 }
344 catch (Exception)
345 {
346 return null;
347 }
348 }
349 private void radiocompare_equal_CheckedChanged(object sender, EventArgs e)
350 {
351 //if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
352 //{
353 if (radio_oldvalue.Checked)
354 {
355 txtStartAddr.ReadOnly = true;
356 txtEndAddr.ReadOnly = true;
357 }
358 if (radio_specificvalue.Checked)
359 {
360 txtStartAddr.ReadOnly = false;
361 txtEndAddr.ReadOnly = true;
362 }
363 //}
364 }
365
366 private void radiocompare_between_CheckedChanged(object sender, EventArgs e)
367 {
368 if (!radiocompare_equal.Checked &&
369 !radiocompare_greaterthan.Checked &&
370 !radiocompare_greaterthan.Checked &&
371 !radiocompare_lessthan.Checked &&
372 !radiocompare_greaterthan_orequal.Checked &&
373 !radiocompare_lessthan_orequal.Checked &&
374 !radiocompare_notequal.Checked)
375 if (radiocompare_between.Checked)
376 {
377 txtStartAddr.ReadOnly = false;
378 txtEndAddr.ReadOnly = false;
379 return;
380 }
381 if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
382 {
383 if (radio_oldvalue.Checked)
384 {
385 txtStartAddr.ReadOnly = true;
386 txtEndAddr.ReadOnly = true;
387 }
388 if (radio_specificvalue.Checked)
389 {
390 txtStartAddr.ReadOnly = false;
391 txtEndAddr.ReadOnly = true;
392 }
393 }
394 }
395
396 private void radiocompare_notbetween_CheckedChanged(object sender, EventArgs e)
397 {
398 if (!radiocompare_equal.Checked &&
399 !radiocompare_greaterthan.Checked &&
400 !radiocompare_greaterthan.Checked &&
401 !radiocompare_lessthan.Checked &&
402 !radiocompare_greaterthan_orequal.Checked &&
403 !radiocompare_lessthan_orequal.Checked &&
404 !radiocompare_notequal.Checked)
405 if (radiocompare_notbetween.Checked)
406 {
407 txtStartAddr.ReadOnly = false;
408 txtEndAddr.ReadOnly = false;
409 return;
410 }
411 if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
412 {
413 if (radio_oldvalue.Checked)
414 {
415 txtStartAddr.ReadOnly = true;
416 txtEndAddr.ReadOnly = true;
417 }
418 if (radio_specificvalue.Checked)
419 {
420 txtStartAddr.ReadOnly = false;
421 txtEndAddr.ReadOnly = true;
422 }
423 }
424 }
425
426 private void radio_8bits_CheckedChanged(object sender, EventArgs e)
427 {
428 if (chkUnsigned.Checked)
429 {
430 txtStartAddr.CreateTypeSize<byte>();
431 txtEndAddr.CreateTypeSize<byte>();
432 }
433 else
434 {
435 txtStartAddr.CreateTypeSize<sbyte>();
436 txtEndAddr.CreateTypeSize<sbyte>();
437 }
438 }
439
440 private void radio_16bits_CheckedChanged(object sender, EventArgs e)
441 {
442 if (chkUnsigned.Checked)
443 {
444 txtStartAddr.CreateTypeSize<ushort>();
445 txtEndAddr.CreateTypeSize<ushort>();
446 }
447 else
448 {
449 txtStartAddr.CreateTypeSize<short>();
450 txtEndAddr.CreateTypeSize<short>();
451 }
452 }
453
454 private void radio_32bits_CheckedChanged(object sender, EventArgs e)
455 {
456
457 if (chkUnsigned.Checked)
458 {
459 txtStartAddr.CreateTypeSize<uint>();
460 txtEndAddr.CreateTypeSize<uint>();
461 }
462 else
463 {
464 txtStartAddr.CreateTypeSize<int>();
465 txtEndAddr.CreateTypeSize<int>();
466 }
467 }
468
469 private void radio_64bits_CheckedChanged(object sender, EventArgs e)
470 {
471
472 if (chkUnsigned.Checked)
473 {
474 txtStartAddr.CreateTypeSize<ulong>();
475 txtEndAddr.CreateTypeSize<ulong>();
476 }
477 else
478 {
479 txtStartAddr.CreateTypeSize<long>();
480 txtEndAddr.CreateTypeSize<long>();
481 }
482 }
483
484 private void radio_oldvalue_CheckedChanged(object sender, EventArgs e)
485 {
486 if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
487 {
488 txtStartAddr.ReadOnly = true;
489 txtEndAddr.ReadOnly = true;
490 }
491 }
492
493 private void radio_specificvalue_CheckedChanged(object sender, EventArgs e)
494 {
495 if (!radiocompare_between.Checked && !radiocompare_notbetween.Checked)
496 {
497 txtStartAddr.ReadOnly = false;
498 txtEndAddr.ReadOnly = true;
499 }
500 }
501
502 private void chkRefreshResults_CheckedChanged(object sender, EventArgs e)
503 {
504 if (chkRefreshResults.Checked)
505 {
506 timer_update_results.Enabled = true;
507 }
508 else
509 {
510 timer_update_results.Enabled = false;
511 ResultsUpdateWorkerThread.CancelAsync();
512 }
513 }
514
515 private void timer_update_results_Tick(object sender, EventArgs e)
516 {
517 if (chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
518 {
519 ResultsUpdateWorkerThread.RunWorkerAsync();
520 }
521 }
522 private bool ShouldUpdateResults()
523 {
524 if (this.AcceptedProcess == null) return false;
525 if (SearchWorkerThread.IsBusy) return false;
526 //if (JokerSearchWorker.IsBusy) return false;
527 if (this.IsResultsUpdateFrozen) return false;
528 if (mnuAddedResults.Visible) return false;
529 if (mnuResults.Visible) return false;
530 if (Process.GetProcessById(this.AcceptedProcess.Id) == null) return false;
531 if (lstResults.Items.Count > 0) return true;
532 if (lstPatchList.Items.Count > 0) return true;
533 return false;
534 }
535 private void ResultsUpdateWorkerThread_DoWork(object sender, DoWorkEventArgs e)
536 {
537 Thread.Sleep(250); // keep thread from blocking
538 if (!this.ShouldUpdateResults()) return;
539 ////if (SearchArgs == null) return;
540 ////if (this.IsResultsUpdateFrozen) return;
541 ////// put thread to sleep for 500ms
542 ////System.Threading.Thread.Sleep(500);
543 //PCSX2MemoryProvider provider = new PCSX2MemoryProvider(this.SearchPCSX2ProcessPID, resultslog);
544 //byte[] buffered_mem = provider.GetMemory();
545 //MemoryStream ms = new MemoryStream(buffered_mem);
546 //BinaryReader r_ms = new BinaryReader(ms);
547
548 #region Update Results List
549 ResultItems = new List<ListViewItem>();
550 //r_ms.BaseStream.Seek(0, SeekOrigin.Begin);
551 for (int i = 0; i < lstResults.Items.Count; i++)
552 {
553 if (this.lstResults.InvokeRequired)
554 {
555 ThreadSafe_GetResultItem _get_item = new ThreadSafe_GetResultItem(GetResultItem);
556 object item = this.lstResults.Invoke(_get_item, new object[] { i, (int)eListViewResults.SEARCH_RESULTS_LIST });
557 if (item != null)
558 ResultItems.Add((ListViewItem)item);
559 }
560 else
561 {
562 ResultItems.Add(lstResults.Items[i]);
563 }
564
565 }
566 for (int i = 0; i < ResultItems.Count; i++)
567 {
568 if (ResultsUpdateWorkerThread.CancellationPending == true)
569 {
570 e.Cancel = true;
571 return;
572 }
573 int Address = 0;
574 ResultDataType _result = (ResultDataType)ResultItems[i].Tag;
575
576 Address = Convert.ToInt32(ResultItems[i].SubItems[col_Found_Address].Text, 16);
577 //r_ms.BaseStream.Seek(Address, SeekOrigin.Begin);
578 using (GenericMemoryProvider provider = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
579 {
580 provider.OpenProvider();
581 ulong bytesReadSize;
582 byte[] data;
583 uint bytesToRead = 0;
584 switch (_result.ValueType)
585 {
586 case SearchDataTypes._8bits:
587 bytesToRead = 1;
588 break;
589 case SearchDataTypes._16bits:
590 bytesToRead = 2;
591 break;
592 case SearchDataTypes._32bits:
593 bytesToRead = 4;
594 break;
595 case SearchDataTypes._64bits:
596 bytesToRead = 8;
597 break;
598 }
599 provider.ReadProcessMemory(Address, bytesToRead, out bytesReadSize, out data);
600 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) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x2}", r_ms.ReadByte()); }
608 else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x2}", r_ms.ReadSByte()); }
609 break;
610 case SearchDataTypes._16bits:
611 if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x4}", r_ms.ReadUInt16()); }
612 else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x4}", r_ms.ReadInt16()); }
613 break;
614 case SearchDataTypes._32bits:
615 if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x8}", r_ms.ReadUInt32()); }
616 else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x8}", r_ms.ReadInt32()); }
617 break;
618 case SearchDataTypes._64bits:
619 if (_result.IsUnsigned) { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x16}", r_ms.ReadUInt64()); }
620 else { ResultItems[i].SubItems[col_Found_Value].Text = string.Format("0x{0:x16}", r_ms.ReadInt64()); }
621 break;
622 }
623 r_ms.Close();
624 }
625 }
626 provider.CloseProvider();
627 }
628 //Application.DoEvents();
629 }
630 #endregion
631
632 #region Update Added Results List
633 AddedItems = new List<ListViewItem>();
634 //r_ms.BaseStream.Seek(0, SeekOrigin.Begin);
635 for (int i = 0; i < lstPatchList.Items.Count; i++)
636 {
637 if (this.lstResults.InvokeRequired)
638 {
639 ThreadSafe_GetResultItem _get_item = new ThreadSafe_GetResultItem(GetResultItem);
640 object item = this.lstResults.Invoke(_get_item, new object[] { i, (int)eListViewResults.PATCH_RESULTS_LIST });
641 if (item != null)
642 AddedItems.Add((ListViewItem)item);
643 }
644 else
645 {
646 AddedItems.Add(lstPatchList.Items[i]);
647 }
648
649 }
650 for (int i = 0; i < AddedItems.Count; i++)
651 {
652 if (ResultsUpdateWorkerThread.CancellationPending == true)
653 {
654 e.Cancel = true;
655 return;
656 }
657 ulong Address = 0;
658 ResultDataType _result = (ResultDataType)AddedItems[i].Tag;
659 Address = Convert.ToUInt64(AddedItems[i].SubItems[col_Added_Address].Text, 16);
660 using (GenericMemoryProvider provider = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
661 {
662 provider.OpenProvider();
663 ulong bytesReadSize;
664 byte[] data;
665 ulong bytesToRead = 0;
666 switch (_result.ValueType)
667 {
668 case SearchDataTypes._8bits:
669 bytesToRead = 1;
670 break;
671 case SearchDataTypes._16bits:
672 bytesToRead = 2;
673 break;
674 case SearchDataTypes._32bits:
675 bytesToRead = 4;
676 break;
677 case SearchDataTypes._64bits:
678 bytesToRead = 8;
679 break;
680 }
681 provider.ReadProcessMemory(Address, bytesToRead, out bytesReadSize, out data);
682 provider.CloseProvider();
683 using (MemoryStream ms = new MemoryStream(data))
684 {
685 using (BinaryReader r_ms = new BinaryReader(ms))
686 {
687 switch (_result.ValueType)
688 {
689 case SearchDataTypes._8bits:
690 if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x2}", r_ms.ReadByte()); }
691 else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x2}", r_ms.ReadSByte()); }
692 break;
693 case SearchDataTypes._16bits:
694 if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x4}", r_ms.ReadUInt16()); }
695 else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x4}", r_ms.ReadInt16()); }
696 break;
697 case SearchDataTypes._32bits:
698 if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x8}", r_ms.ReadUInt32()); }
699 else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x8}", r_ms.ReadInt32()); }
700 break;
701 case SearchDataTypes._64bits:
702 if (_result.IsUnsigned) { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x16}", r_ms.ReadUInt64()); }
703 else { AddedItems[i].SubItems[col_Added_Value].Text = string.Format("0x{0:x16}", r_ms.ReadInt64()); }
704 break;
705 }
706 r_ms.Close();
707 }
708 }
709 }
710 //Application.DoEvents();
711 }
712 #endregion
713
714
715 }
716
717 private void ResultsUpdateWorkerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
718 {
719 try
720 {
721 //if ((lstResults.SelectedItems.Count > 0) && !PatchedValue_NeedsUpdate ) return;
722 //if ((lstPatchList.SelectedItems.Count > 0) && !PatchedValue_NeedsUpdate) return;
723 if (!this.ShouldUpdateResults()) return;
724 if (ResultItems.Count > 0)
725 {
726 //lstResults.Items.Clear();
727 //lstResults.Items.AddRange(ResultItems.ToArray());
728
729 for (int i = 0; i < ResultItems.Count; i++)
730 {
731 lstResults.Items[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text =
732 ResultItems[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text;
733 }
734
735 }
736 if (AddedItems.Count > 0)
737 {
738 //lstPatchList.Items.Clear();
739 //lstPatchList.Items.AddRange(AddedItems.ToArray());
740
741 for (int i = 0; i < AddedItems.Count; i++)
742 {
743 lstPatchList.Items[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text =
744 AddedItems[i].SubItems[new AVPColumnText(AVPColumnType.VALUE).ColumnIndex].Text;
745 }
746
747 }
748 PatchedValue_NeedsUpdate = false;
749 }
750 catch { }
751 }
752
753 private void btnImportFile_Click(object sender, EventArgs e)
754 {
755 this.FreezeResultsUpdate();
756 if (!lstPatchList.ImportFromFile())
757 {
758 MessageBox.Show("Failed to Import Patch List from File.", "Import Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
759 this.ThawResultsUpdate();
760 return;
761 }
762 else
763 {
764 MessageBox.Show("Succesfully Imported Patch List from File.", "Import Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
765 this.ThawResultsUpdate();
766 return;
767 }
768 }
769 bool g_isFrozen = false;
770 private bool IsResultsUpdateFrozen
771 {
772 get { return g_isFrozen; }
773 set { g_isFrozen = value; }
774 }
775 private void ThawResultsUpdate()
776 {
777 this.IsResultsUpdateFrozen = false;
778 if (this.AcceptedProcess != null)
779 {
780 #if !DO_NOT_SUSPEND_RESUME_THREAD_ON_FREEZE
781 ThreadControl.ResumeProcess(this.AcceptedProcess.Id);
782 #endif
783 }
784 }
785
786 private void FreezeResultsUpdate()
787 {
788 this.IsResultsUpdateFrozen = true;
789 //this.IsResultsUpdateFrozen = false;
790 if (this.AcceptedProcess != null)
791 {
792 #if !DO_NOT_SUSPEND_RESUME_THREAD_ON_FREEZE
793 ThreadControl.SuspendProcess(this.AcceptedProcess.Id);
794 #endif
795 }
796 }
797
798 private void btnExportFile_Click(object sender, EventArgs e)
799 {
800 this.FreezeResultsUpdate();
801 if (!lstPatchList.ExportToFile())
802 {
803 MessageBox.Show("Failed to Export Patch List to File.", "Export Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
804 this.ThawResultsUpdate();
805 return;
806 }
807 else
808 {
809 MessageBox.Show("Succesfully Exported Patch List to File.", "Export Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
810 this.ThawResultsUpdate();
811 return;
812 }
813 }
814
815 private void btnImportClipboard_Click(object sender, EventArgs e)
816 {
817 this.FreezeResultsUpdate();
818 if (!lstPatchList.ImportFromClipboard())
819 {
820 MessageBox.Show("Failed to Import Patch List from Clipboard.", "Import Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
821 this.ThawResultsUpdate();
822 return;
823 }
824 else
825 {
826 MessageBox.Show("Succesfully Import Patch List from Clipboard.", "Import Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
827 this.ThawResultsUpdate();
828 }
829 }
830
831 private void btnExportClipboard_Click(object sender, EventArgs e)
832 {
833 this.FreezeResultsUpdate();
834 if (!lstPatchList.ExportToClipboard())
835 {
836 MessageBox.Show("Failed to Export Patch List to Clipboard.", "Export Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
837 this.ThawResultsUpdate();
838 return;
839 }
840 else
841 {
842 MessageBox.Show("Succesfully Exported Patch List to Clipboard.", "Export Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
843 this.ThawResultsUpdate();
844 return;
845 }
846 }
847
848 private void btnAddPatchAddress_Click(object sender, EventArgs e)
849 {
850 PatchAdder adder = new PatchAdder((IAcceptsProcessAndConfig)this);
851 adder.ShowDialog();
852 if (adder.WasAPatchAdded) AddToPatchList(adder.AddedPatchValue);
853 }
854
855 private void btnAddAddressRange_Click(object sender, EventArgs e)
856 {
857 PatchRangeAdder adder = new PatchRangeAdder((IAcceptsProcessAndConfig)this);
858 adder.ShowDialog();
859 if (adder.WasAPatchAdded) AddToPatchList(adder.AddedPatchValue);
860 }
861 private void AddToPatchList(List<ResultDataType> item) { foreach (ResultDataType data in item) { AddToPatchList(data); } }
862 private void AddToPatchList(ResultDataType item)
863 {
864 ResultItem item2 = null;
865 switch (item.ValueType)
866 {
867 case SearchDataTypes._8bits:
868 if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToByte(item.Value)); }
869 else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToSByte(item.Value)); }
870 break;
871 case SearchDataTypes._16bits:
872 if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToUInt16(item.Value)); }
873 else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToInt16(item.Value)); }
874 break;
875 case SearchDataTypes._32bits:
876 if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToUInt32(item.Value)); }
877 else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToInt32(item.Value)); }
878 break;
879 case SearchDataTypes._64bits:
880 if (item.IsUnsigned) { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToUInt64(item.Value)); }
881 else { item2 = new ResultItem(item.Address, item.IsFrozen, Convert.ToInt64(item.Value)); }
882 break;
883 }
884 this.AddToPatchList(item2);
885 }
886 private void AddToPatchList(ListViewItem item)
887 {
888 try
889 {
890 ResultDataType _result = (ResultDataType)item.Tag;
891 this.AddToPatchList(_result);
892 }
893 catch (InvalidCastException ex)
894 {
895 // unable to cast
896 MessageBox.Show(ex.Message, "Invalid Cast Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
897 }
898 catch (Exception ex)
899 {
900 // other exception
901 MessageBox.Show(ex.Message, "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
902 }
903 }
904 private void AddToPatchList(ResultItem item)
905 {
906 if (!lstPatchList.Items.Contains(item)) lstPatchList.Items.Add(item);
907 }
908 private void AddToPatchList(string address, SearchDataTypes bitsize, bool IsUnsigned)
909 {
910 ResultItemState state = new ResultItemState(address, bitsize, IsUnsigned, (IAcceptsProcessAndConfig)this);
911 ResultItem item = new ResultItem(state.Address, state.Value, state.Frozen, state.ValueType, state.IsUnsigned);
912 this.AddToPatchList(item);
913 }
914
915 private void mnuItemAddToPatchList_Click(object sender, EventArgs e)
916 {
917 if (!(lstResults.SelectedItems.Count > 0)) return;
918 //if (SearchArgs == null) return;
919
920 try
921 {
922 for (int i = 0; i < lstResults.SelectedIndices.Count; i++)
923 {
924 //ResultDataType result = (ResultDataType)lstResults.Items[selected_index].Tag;
925 ListViewItem item = lstResults.Items[lstResults.SelectedIndices[i]];
926 this.AddToPatchList(item);
927 }
928 }
929 catch (Exception ex)
930 {
931 logger.Error.WriteLine(ex.ToString());
932 }
933 }
934
935 private void mnuItemRemoveResult_Click(object sender, EventArgs e)
936 {
937 if (!(lstPatchList.SelectedItems.Count > 0)) return;
938 //if (SearchArgs == null) return;
939 try
940 {
941 this.FreezeResultsUpdate();
942 for (int i = 0; i < lstPatchList.SelectedIndices.Count; i++)
943 {
944 //lstPatchList.ThawItem(lstPatchList.SelectedIndices[i]);
945 lstPatchList.Items[lstPatchList.SelectedIndices[i]].Remove();
946 }
947 this.ThawResultsUpdate();
948 }
949 catch (Exception ex)
950 {
951 Debug.WriteLine(ex.ToString());
952 }
953 }
954 private void PatchRange(bool SingleEntry)
955 {
956 //if (SearchArgs == null) return;
957 #region Patch Selected Address
958 // stop ResultsUpdate Thread
959 ResultsUpdateWorkerThread.CancelAsync();
960
961 List<ResultDataType> patch_list = new List<ResultDataType>();
962 List<int> SelectedIndexes = new List<int>();
963
964 if (SingleEntry)
965 {
966 SelectedIndexes.Add(lstPatchList.SelectedIndices[0]);
967 }
968 else
969 {
970 foreach (int index in lstPatchList.SelectedIndices)
971 {
972 SelectedIndexes.Add(index);
973 }
974 }
975 //PCSX2MemoryProvider provider = new PCSX2MemoryProvider(this.SearchPCSX2ProcessPID, resultslog);
976 foreach (int index in SelectedIndexes)
977 {
978 if (SingleEntry)
979 {
980 SearchPatcher patcher = null;
981 uint Address = 0;
982 ListViewItem item = lstPatchList.Items[index];
983 ResultDataType _result = (ResultDataType)item.Tag;
984 Address = Convert.ToUInt32(item.SubItems[col_Found_Address].Text, 16);
985 switch (_result.ValueType)
986 {
987 case SearchDataTypes._8bits:
988 if (_result.IsUnsigned)
989 {
990 byte value = Convert.ToByte(item.SubItems[col_Found_Value].Text, 16);
991 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
992 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 else
1000 {
1001 sbyte value = Convert.ToSByte(item.SubItems[col_Found_Value].Text, 16);
1002 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1003 timer_update_results.Enabled = false;
1004 patcher.ShowDialog();
1005 timer_update_results.Enabled = true;
1006 PatchedValue_NeedsUpdate = true;
1007 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1008 ResultsUpdateWorkerThread.RunWorkerAsync();
1009 }
1010 break;
1011 case SearchDataTypes._16bits:
1012 if (_result.IsUnsigned)
1013 {
1014 ushort value = Convert.ToUInt16(item.SubItems[col_Found_Value].Text, 16);
1015 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1016 timer_update_results.Enabled = false;
1017 patcher.ShowDialog();
1018 timer_update_results.Enabled = true;
1019 PatchedValue_NeedsUpdate = true;
1020 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1021 ResultsUpdateWorkerThread.RunWorkerAsync();
1022 }
1023 else
1024 {
1025 short value = Convert.ToInt16(item.SubItems[col_Found_Value].Text, 16);
1026 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1027 timer_update_results.Enabled = false;
1028 patcher.ShowDialog();
1029 timer_update_results.Enabled = true;
1030 PatchedValue_NeedsUpdate = true;
1031 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1032 ResultsUpdateWorkerThread.RunWorkerAsync();
1033 }
1034 break;
1035 case SearchDataTypes._32bits:
1036 if (_result.IsUnsigned)
1037 {
1038 uint value = Convert.ToUInt32(item.SubItems[col_Found_Value].Text, 16);
1039 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1040 timer_update_results.Enabled = false;
1041 patcher.ShowDialog();
1042 timer_update_results.Enabled = true;
1043 PatchedValue_NeedsUpdate = true;
1044 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1045 ResultsUpdateWorkerThread.RunWorkerAsync();
1046 }
1047 else
1048 {
1049 int value = Convert.ToInt32(item.SubItems[col_Found_Value].Text, 16);
1050 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1051 timer_update_results.Enabled = false;
1052 patcher.ShowDialog();
1053 timer_update_results.Enabled = true;
1054 PatchedValue_NeedsUpdate = true;
1055 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1056 ResultsUpdateWorkerThread.RunWorkerAsync();
1057 }
1058 break;
1059 case SearchDataTypes._64bits:
1060 if (_result.IsUnsigned)
1061 {
1062 ulong value = Convert.ToUInt32(item.SubItems[col_Found_Value].Text, 16);
1063 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1064 timer_update_results.Enabled = false;
1065 patcher.ShowDialog();
1066 timer_update_results.Enabled = true;
1067 PatchedValue_NeedsUpdate = true;
1068 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1069 ResultsUpdateWorkerThread.RunWorkerAsync();
1070 }
1071 else
1072 {
1073 long value = Convert.ToInt32(item.SubItems[col_Found_Value].Text, 16);
1074 patcher = new SearchPatcher((IAcceptsProcessAndConfig)this, Address, value);
1075 timer_update_results.Enabled = false;
1076 patcher.ShowDialog();
1077 timer_update_results.Enabled = true;
1078 PatchedValue_NeedsUpdate = true;
1079 if (!chkRefreshResults.Checked && !ResultsUpdateWorkerThread.IsBusy)
1080 ResultsUpdateWorkerThread.RunWorkerAsync();
1081 }
1082 break;
1083 }
1084 }
1085 else
1086 {
1087
1088 ListViewItem item = lstPatchList.Items[index];
1089 ResultDataType _result = (ResultDataType)item.Tag;
1090 patch_list.Add(_result);
1091 }
1092 }
1093
1094 if (patch_list.Count > 0)
1095 {
1096 SearchRangePatcher rangePatcher = new SearchRangePatcher((IAcceptsProcessAndConfig)this, patch_list);
1097 rangePatcher.ShowDialog();
1098 }
1099
1100 #endregion
1101 }
1102 private void mnuItemPatchSelectedEntry_Click(object sender, EventArgs e)
1103 {
1104 if (!(lstPatchList.SelectedItems.Count == 1)) return;
1105 PatchRange(true);
1106 }
1107
1108 private void mnuItemPatchSelectedRange_Click(object sender, EventArgs e)
1109 {
1110 if (!(lstPatchList.SelectedItems.Count >= 1)) return;
1111 PatchRange(false);
1112 }
1113
1114 private void mnuItemFreezeSelectedPatches_Click(object sender, EventArgs e)
1115 {
1116 if (!(lstPatchList.SelectedItems.Count > 0)) return;
1117 //if (SearchArgs == null) return;
1118 try
1119 {
1120 lstPatchList.ProcessID = this.AcceptedProcess.Id;
1121 this.FreezeResultsUpdate();
1122 for (int i = 0; i < lstPatchList.SelectedIndices.Count; i++)
1123 {
1124 lstPatchList.FreezeItem(lstPatchList.SelectedIndices[i]);
1125 }
1126 // force thaw and update
1127 this.ThawResultsUpdate();
1128 this.Update();
1129 }
1130 catch (Exception ex)
1131 {
1132 Debug.WriteLine(ex.ToString());
1133 }
1134 }
1135
1136 private void mnuItemThawSelectedPatches_Click(object sender, EventArgs e)
1137 {
1138 if (!(lstPatchList.SelectedItems.Count > 0)) return;
1139 //if (SearchArgs == null) return;
1140 try
1141 {
1142 lstPatchList.ProcessID = this.AcceptedProcess.Id;
1143 this.FreezeResultsUpdate();
1144 for (int i = 0; i < lstPatchList.SelectedIndices.Count; i++)
1145 {
1146 lstPatchList.ThawItem(lstPatchList.SelectedIndices[i]);
1147 }
1148 // force thaw and update
1149 this.ThawResultsUpdate();
1150 this.Update();
1151 }
1152 catch (Exception ex)
1153 {
1154 Debug.WriteLine(ex.ToString());
1155 }
1156 }
1157
1158 private void SearchWorkerThread_DoWork(object sender, DoWorkEventArgs e)
1159 {
1160 try
1161 {
1162 Stopwatch st = new Stopwatch();
1163 st.Start();
1164
1165 Stopwatch st_first_search = new Stopwatch();
1166 Stopwatch st_nonrange_search = new Stopwatch();
1167 Stopwatch st_ranged_search = new Stopwatch();
1168
1169 e.Result = st;
1170 //List<ResultType<object>> tmp_Results = new List<ResultType<object>>();
1171 List<ResultType<ulong>> second_tmp_Results = new List<ResultType<ulong>>();
1172 //const int ElementsBeforeDisplay = 100;
1173 SearchArgs.LogSearchOptions();
1174 uint STEP_SIZE = (uint)SearchArgs.DataType / 8;
1175
1176 bool unsigned = SearchArgs.IsUnsignedDataType;
1177 SearchDataTypes sdt = SearchArgs.DataType;
1178 //byte[] buffered_mem = new byte[(MemoryRangeSize - MemoryRangeStart)]; // throws OutOfMemoryException if size is over 2G
1179 logger.Debug.WriteLine(string.Format("Buffered Memory Size -> 0x{0:x8}", MemoryRangeSize - MemoryRangeStart));
1180 UpdateProgress(0, string.Format("Search is Warming Up...Please Wait..."));
1181 //new Action<int, string>(UpdateProgress).Invoke(0, string.Format("Search is Warming Up...Please Wait..."));
1182 Stopwatch provider_st = new Stopwatch();
1183 provider_st.Start();
1184 using (GenericMemoryProvider provider = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1185 {
1186
1187 if (SearchArgs.IsFirstSearch)
1188 {
1189 #region FirstSearch
1190 provider.OpenProvider();
1191 ulong count = (ulong)((MemoryRangeSize - MemoryRangeStart) / STEP_SIZE);
1192 SearchResultWriter writer = new SearchResultWriter((ulong)(count), SearchGuid);
1193 int Last_Whole_Percent_Done = 0;
1194 ulong size = 0;
1195 switch (sdt)
1196 {
1197 case SearchDataTypes._8bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1198 case SearchDataTypes._16bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1199 case SearchDataTypes._32bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1200 case SearchDataTypes._64bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1201 }
1202 //uint size = STEP_SIZE * 4096;
1203 for (ulong i = MemoryRangeStart; i < MemoryRangeSize; i += size)
1204 {
1205
1206 ulong bytesRead = 0;
1207 byte[] data = new byte[size];
1208 provider.ReadProcessMemoryAtOnce(i, size, out bytesRead, out data);
1209 string message = string.Format(" -> Reading Address: 0x{0:x8}", (i + MemoryRangeStart));
1210 double double_percent_done = 100.0 * (double)((double)i / (double)MemoryRangeSize);
1211 int int_percent_done = (int)double_percent_done;
1212 if ((int_percent_done != Last_Whole_Percent_Done))// && (i % 10000) == 0)
1213 {
1214 UpdateProgress((int)double_percent_done, message);
1215 Last_Whole_Percent_Done = int_percent_done;
1216 }
1217
1218 ulong address_index = i;
1219 #region comparison and serialization
1220 switch (sdt)
1221 {
1222 case SearchDataTypes._8bits:
1223 if (unsigned)
1224 {
1225 #region 8bits - unsigned
1226 var t_data = data;
1227 foreach (var Value in t_data)
1228 {
1229 if (SearchWorkerThread.CancellationPending) { break; }
1230 using (_8bit_unsigned_comparer_ comparer = new _8bit_unsigned_comparer_(SearchArgs, address_index))
1231 {
1232 byte 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.ToByte(SearchArgs.CompareStartValue);
1253 comparer.Value = value;
1254 }
1255 if (comparer.Compare(Convert.ToByte(Value), value))
1256 {
1257 writer.WriteResult<byte>(comparer.Address, comparer.Value);
1258 }
1259 }
1260 address_index += STEP_SIZE;
1261 }
1262 #endregion
1263 }
1264 else
1265 {
1266 #region 8bits - signed
1267 var t_data = data;
1268 foreach (var Value in t_data)
1269 {
1270 if (SearchWorkerThread.CancellationPending) { break; }
1271 using (_8bit_signed_comparer_ comparer = new _8bit_signed_comparer_(SearchArgs, address_index))
1272 {
1273 sbyte 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.ToSByte(SearchArgs.CompareStartValue);
1294 comparer.Value = value;
1295 }
1296 if (comparer.Compare(Convert.ToSByte(Value), value))
1297 {
1298 writer.WriteResult<sbyte>(comparer.Address, comparer.Value);
1299 }
1300 }
1301 address_index += STEP_SIZE;
1302 }
1303 #endregion
1304 } break;
1305 case SearchDataTypes._16bits:
1306 if (unsigned)
1307 {
1308 #region 16bits - unsigned
1309 var t_data = BitTools.ConvertByteArray<ushort>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1310 foreach (var Value in t_data)
1311 {
1312 if (SearchWorkerThread.CancellationPending) { break; }
1313 using (_16bit_unsigned_comparer_ comparer = new _16bit_unsigned_comparer_(SearchArgs, address_index))
1314 {
1315 ushort 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.ToUInt16(SearchArgs.CompareStartValue);
1336 comparer.Value = value;
1337 }
1338 if (comparer.Compare(Convert.ToUInt16(Value), value))
1339 {
1340 writer.WriteResult<ushort>(comparer.Address, comparer.Value);
1341 }
1342 }
1343 address_index += STEP_SIZE;
1344 }
1345 #endregion
1346 }
1347 else
1348 {
1349 #region 16bits - signed
1350 var t_data = BitTools.ConvertByteArray<short>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1351 foreach (var Value in t_data)
1352 {
1353 if (SearchWorkerThread.CancellationPending) { break; }
1354 using (_16bit_signed_comparer_ comparer = new _16bit_signed_comparer_(SearchArgs, address_index))
1355 {
1356 short 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.ToInt16(SearchArgs.CompareStartValue);
1377 comparer.Value = value;
1378 }
1379 if (comparer.Compare(Convert.ToSByte(Value), value))
1380 {
1381 writer.WriteResult<short>(comparer.Address, comparer.Value);
1382 }
1383 }
1384 address_index += STEP_SIZE;
1385 }
1386 #endregion
1387 } break;
1388 case SearchDataTypes._32bits:
1389 if (unsigned)
1390 {
1391 #region 32bits - unsigned
1392 var t_data = BitTools.ConvertByteArray<uint>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1393 foreach (var Value in t_data)
1394 {
1395 if (SearchWorkerThread.CancellationPending) { break; }
1396 using (_32bit_unsigned_comparer_ comparer = new _32bit_unsigned_comparer_(SearchArgs, address_index))
1397 {
1398 uint 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.ToUInt32(SearchArgs.CompareStartValue);
1419 comparer.Value = value;
1420 }
1421 if (comparer.Compare(Convert.ToUInt32(Value), value))
1422 {
1423 writer.WriteResult<uint>(comparer.Address, comparer.Value);
1424 }
1425 }
1426 address_index += STEP_SIZE;
1427 }
1428 #endregion
1429 }
1430 else
1431 {
1432 #region 32bits - signed
1433 var t_data = BitTools.ConvertByteArray<int>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1434 foreach (var Value in t_data)
1435 {
1436 if (SearchWorkerThread.CancellationPending) { break; }
1437 using (_32bit_signed_comparer_ comparer = new _32bit_signed_comparer_(SearchArgs, address_index))
1438 {
1439 int 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.ToInt32(SearchArgs.CompareStartValue);
1460 comparer.Value = value;
1461 }
1462 if (comparer.Compare(Convert.ToInt32(Value), value))
1463 {
1464 writer.WriteResult<int>(comparer.Address, comparer.Value);
1465 }
1466 }
1467 address_index += STEP_SIZE;
1468 }
1469 #endregion
1470 } break;
1471 case SearchDataTypes._64bits:
1472 if (unsigned)
1473 {
1474 #region 64bits - unsigned
1475 var t_data = BitTools.ConvertByteArray<ulong>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1476 foreach (var Value in t_data)
1477 {
1478 if (SearchWorkerThread.CancellationPending) { break; }
1479 using (_64bit_unsigned_comparer_ comparer = new _64bit_unsigned_comparer_(SearchArgs, address_index))
1480 {
1481 ulong value = 0;
1482 if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1483 {
1484 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1485 {
1486 try
1487 {
1488 gmp.OpenProvider();
1489 gmp.ReadMemory(address_index, out value);
1490 gmp.CloseProvider();
1491 }
1492 catch (Exception ex)
1493 {
1494 logger.VerboseError.WriteLine(ex.ToString());
1495 }
1496 }
1497 comparer.Value = value;
1498 }
1499 else
1500 {
1501 value = Convert.ToUInt64(SearchArgs.CompareStartValue);
1502 comparer.Value = value;
1503 }
1504 if (comparer.Compare(Convert.ToUInt64(Value), value))
1505 {
1506 writer.WriteResult<ulong>(comparer.Address, comparer.Value);
1507 }
1508 }
1509 address_index += STEP_SIZE;
1510 }
1511 #endregion
1512 }
1513 else
1514 {
1515 #region 64bits - signed
1516 var t_data = BitTools.ConvertByteArray<long>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1517 foreach (var Value in t_data)
1518 {
1519 if (SearchWorkerThread.CancellationPending) { break; }
1520 using (_64bit_signed_comparer_ comparer = new _64bit_signed_comparer_(SearchArgs, address_index))
1521 {
1522 long value = 0;
1523 if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1524 {
1525 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1526 {
1527 try
1528 {
1529 gmp.OpenProvider();
1530 gmp.ReadMemory(address_index, out value);
1531 gmp.CloseProvider();
1532 }
1533 catch (Exception ex)
1534 {
1535 logger.VerboseError.WriteLine(ex.ToString());
1536 }
1537 }
1538 comparer.Value = value;
1539 }
1540 else
1541 {
1542 value = Convert.ToInt64(SearchArgs.CompareStartValue);
1543 comparer.Value = value;
1544 }
1545 if (comparer.Compare(Convert.ToInt64(Value), value))
1546 {
1547 writer.WriteResult<long>(comparer.Address, comparer.Value);
1548 }
1549 }
1550 address_index += STEP_SIZE;
1551 }
1552 #endregion
1553 } break;
1554
1555 }
1556 #endregion
1557
1558 if (SearchWorkerThread.CancellationPending)
1559 {
1560 provider_st.Stop();
1561 st.Stop();
1562 writer.CancelRequest();
1563 writer.Dispose();
1564 writer = null;
1565 e.Result = true;
1566 provider.CloseProvider();
1567 return;
1568 }
1569 }
1570
1571 if (SearchWorkerThread.CancellationPending)
1572 {
1573 provider_st.Stop();
1574 st.Stop();
1575 writer.CancelRequest();
1576 writer.Dispose();
1577 writer = null;
1578 e.Result = true;
1579 provider.CloseProvider();
1580 return;
1581 }
1582 writer.Dispose();
1583 writer = null;
1584 provider.CloseProvider();
1585 #endregion
1586
1587 GC.Collect(); // force gc collection
1588 }
1589 else
1590 {
1591 #region SubsequentSearch
1592 Guid new_SearchGuid = GuidTools.IncrementGuid(SearchGuid);
1593 int Last_Whole_Percent_Done = 0;
1594 // need to get the address list
1595 ulong[] reader_addresses = new ulong[0];
1596 #region Address pre-population
1597 using (SearchResultReader reader = new SearchResultReader(SearchGuid, SearchArgs.IsUnsignedDataType, SearchArgs.DataType, new Action<int, string>(UpdateProgress), new Func<bool>(ShouldCancelAnySearchOperation))) // delete the file on dispose
1598 {
1599 reader_addresses = new ulong[reader.ResultCount];
1600 // pre-populate the addresses array
1601 Stopwatch st_profiler_reader_addresses = new Stopwatch();
1602 st_profiler_reader_addresses.Start();
1603 int reader_address_index = 0;
1604 foreach (var k in reader)
1605 {
1606
1607 if (SearchWorkerThread.CancellationPending) { st_profiler_reader_addresses.Stop(); break; }
1608 reader_addresses[reader_address_index] = k.Address;
1609
1610 string message = string.Format(" -> Creating Address Array (0x{0} of 0x{1})", reader_address_index.ToString("X"), reader_addresses.Length.ToString("X"));
1611 double double_percent_done = 100.0 * (double)((double)reader_address_index / (double)reader_addresses.Length);
1612 int int_percent_done = (int)double_percent_done;
1613 if ((int_percent_done != Last_Whole_Percent_Done))// && (reader_address_index % 10000) == 0)
1614 {
1615 UpdateProgress((int)double_percent_done, message);
1616 Last_Whole_Percent_Done = int_percent_done;
1617 logger.Profiler.WriteLine("It has taken {0} seconds to pre-populate the address array.", st_profiler_reader_addresses.Elapsed.TotalSeconds);
1618 }
1619
1620 reader_address_index++;
1621 }
1622 st_profiler_reader_addresses.Stop();
1623 logger.Profiler.WriteLine("It took a total of {0} seconds to pre-populate the address array.", st_profiler_reader_addresses.Elapsed.TotalSeconds);
1624 }
1625 GC.Collect(); // force gc collection
1626 #endregion
1627
1628 #region result writing
1629 using (SearchResultWriter writer = new SearchResultWriter(0, new_SearchGuid))
1630 {
1631
1632 if (SearchWorkerThread.CancellationPending)
1633 {
1634 provider_st.Stop();
1635 st.Stop();
1636 writer.CancelRequest();
1637 writer.Dispose();
1638 e.Result = true;
1639 provider.CloseProvider();
1640 return;
1641 }
1642
1643 provider.OpenProvider();
1644 for (int i = 0; i < reader_addresses.Length; i++)
1645 {
1646 if (SearchWorkerThread.CancellationPending)
1647 {
1648 provider_st.Stop();
1649 st.Stop();
1650 writer.CancelRequest();
1651 writer.Dispose();
1652 e.Result = true;
1653 provider.CloseProvider();
1654 return;
1655 }
1656 var address = reader_addresses[i];
1657
1658 string message = string.Format(" -> Parsing Address 0x{0:x8} ({1} of {2})", address, i.ToString(), reader_addresses.Length.ToString());
1659 double double_percent_done = 100.0 * (double)((double)i / (double)reader_addresses.Length);
1660 int int_percent_done = (int)double_percent_done;
1661 if ((int_percent_done != Last_Whole_Percent_Done))// && (i % 10000) == 0)
1662 {
1663 UpdateProgress((int)double_percent_done, message);
1664 Last_Whole_Percent_Done = int_percent_done;
1665 }
1666
1667 ulong bytesRead = 0;
1668 byte[] data = new byte[STEP_SIZE];
1669 provider.ReadProcessMemory(address, STEP_SIZE, out bytesRead, out data);
1670 switch (sdt)
1671 {
1672 case SearchDataTypes._8bits:
1673 if (unsigned)
1674 {
1675 #region 8bits - unsigned
1676 byte Value = data[0];
1677 using (_8bit_unsigned_comparer_ comparer = new _8bit_unsigned_comparer_(SearchArgs, address))
1678 {
1679 byte value = 0;
1680 if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1681 {
1682 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1683 {
1684 try
1685 {
1686 gmp.OpenProvider();
1687 gmp.ReadMemory(address, out value);
1688 gmp.CloseProvider();
1689 }
1690 catch (Exception ex)
1691 {
1692 logger.VerboseError.WriteLine(ex.ToString());
1693 }
1694 }
1695 comparer.Value = value;
1696 }
1697 else
1698 {
1699 value = Convert.ToByte(SearchArgs.CompareStartValue);
1700 comparer.Value = value;
1701 }
1702 if (comparer.Compare(Convert.ToByte(Value), value))
1703 {
1704 writer.WriteResult<byte>(comparer.Address, comparer.Value);
1705 }
1706 }
1707 #endregion
1708 }
1709 else
1710 {
1711 #region 8bits - signed
1712 sbyte Value = Convert.ToSByte(data[0]);
1713 using (_8bit_signed_comparer_ comparer = new _8bit_signed_comparer_(SearchArgs, address))
1714 {
1715 sbyte value = 0;
1716 if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1717 {
1718 using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1719 {
1720 try
1721 {
1722 gmp.OpenProvider();
1723 gmp.ReadMemory(address, out value);
1724 gmp.CloseProvider();
1725 }
1726 catch (Exception ex)
1727 {
1728 logger.VerboseError.WriteLine(ex.ToString());
1729 }
1730 }
1731 comparer.Value = value;
1732 }
1733 else
1734 {
1735 value = Convert.ToSByte(SearchArgs.CompareStartValue);
1736 comparer.Value = value;
1737 }
1738 if (comparer.Compare(Convert.ToSByte(Value), value))
1739 {
1740 writer.WriteResult<sbyte>(comparer.Address, comparer.Value);
1741 }
1742 }
1743 #endregion
1744 }
1745 break;
1746 case SearchDataTypes._16bits:
1747 break;
1748 case SearchDataTypes._32bits:
1749 break;
1750 case SearchDataTypes._64bits:
1751 break;
1752 }
1753 }
1754 provider.CloseProvider();
1755
1756 #region old-code:
1757 //Last_Whole_Percent_Done = 0;
1758 ////int index = 0;
1759
1760 //provider.OpenProvider();
1761 ////int count = (int)((MemoryRangeSize - MemoryRangeStart) / STEP_SIZE);
1762 ////SearchResultWriter writer = new SearchResultWriter((int)(count), SearchGuid);
1763 //uint size = 0;
1764 //switch (sdt)
1765 //{
1766 // case SearchDataTypes._8bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1767 // case SearchDataTypes._16bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1768 // case SearchDataTypes._32bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1769 // case SearchDataTypes._64bits: size = (MEM_CHUNK_SIZE / BitTools.SizeOf<uint>(sdt)); break;
1770 //}
1771 ////size = STEP_SIZE * 4096;
1772 //for (uint i = MemoryRangeStart; i < MemoryRangeSize; i += size)
1773 //{
1774 // int bytesRead = 0;
1775 // byte[] data = new byte[size];
1776 // provider.ReadProcessMemoryAtOnce(i, size, out bytesRead, out data);
1777 // string message = string.Format(" -> Reading Address: 0x{0:x8}", (i + MemoryRangeStart));
1778 // double double_percent_done = 100.0 * (double)((double)i / (double)MemoryRangeSize);
1779 // int int_percent_done = (int)double_percent_done;
1780 // if ((int_percent_done != Last_Whole_Percent_Done))// && (i % 10000) == 0)
1781 // {
1782 // UpdateProgress(int_percent_done, message);
1783 // Last_Whole_Percent_Done = int_percent_done;
1784 // }
1785 // uint address_index = i;
1786 // int inner_Last_Whole_Percent_Done = 0;
1787 // #region comparison and serialization
1788 // switch (sdt)
1789 // {
1790 // case SearchDataTypes._8bits:
1791 // if (unsigned)
1792 // {
1793 // #region 8bits - unsigned
1794 // var t_data = data;
1795 // foreach (var Value in t_data)
1796 // {
1797 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1798 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
1799 // int inner_int_percent_done = (int)inner_double_percent_done;
1800 // if ((address_index % 10000) == 0)
1801 // {
1802 // UpdateProgress(inner_int_percent_done, inner_message);
1803 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
1804 // }
1805 // if (SearchWorkerThread.CancellationPending) { break; }
1806 // if (!reader_addresses.Contains(address_index))
1807 // {
1808 // address_index += STEP_SIZE;
1809 // continue;
1810 // }
1811 // else
1812 // {
1813 // writer.WriteResult<byte>(address_index, Value);
1814 // }
1815 // address_index += STEP_SIZE;
1816 // }
1817 // #endregion
1818 // }
1819 // else
1820 // {
1821 // #region 8bits - signed
1822 // var t_data = data;
1823 // foreach (var Value in t_data)
1824 // {
1825 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8} of 0x{1:x8}", address_index, MemoryRangeSize);
1826 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
1827 // int inner_int_percent_done = (int)inner_double_percent_done;
1828 // if ((address_index % 10000) == 0)
1829 // {
1830 // UpdateProgress(inner_int_percent_done, inner_message);
1831 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
1832 // }
1833 // if (SearchWorkerThread.CancellationPending) { break; }
1834 // if (!reader_addresses.Contains(address_index))
1835 // {
1836 // address_index += STEP_SIZE;
1837 // continue;
1838 // }
1839 // using (_8bit_signed_comparer_ comparer = new _8bit_signed_comparer_(SearchArgs, address_index))
1840 // {
1841 // sbyte value = 0;
1842 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1843 // {
1844 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1845 // {
1846 // try
1847 // {
1848 // gmp.OpenProvider();
1849 // gmp.ReadMemory(address_index, out value);
1850 // gmp.CloseProvider();
1851 // }
1852 // catch (Exception ex)
1853 // {
1854 // logger.VerboseError.WriteLine(ex.ToString());
1855 // }
1856 // }
1857 // comparer.Value = value;
1858 // }
1859 // else
1860 // {
1861 // value = Convert.ToSByte(SearchArgs.CompareStartValue);
1862 // comparer.Value = value;
1863 // }
1864 // if (comparer.Compare(Convert.ToSByte(Value), value))
1865 // {
1866 // writer.WriteResult<sbyte>(comparer.Address, comparer.Value);
1867 // }
1868 // }
1869 // address_index += STEP_SIZE;
1870 // }
1871 // #endregion
1872 // } break;
1873 // case SearchDataTypes._16bits:
1874 // if (unsigned)
1875 // {
1876 // #region 16bits - unsigned
1877 // var t_data = BitTools.ConvertByteArray<ushort>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1878 // foreach (var Value in t_data)
1879 // {
1880 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1881 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
1882 // int inner_int_percent_done = (int)inner_double_percent_done;
1883 // if ((address_index % 10000) == 0)
1884 // {
1885 // UpdateProgress(inner_int_percent_done, inner_message);
1886 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
1887 // }
1888 // if (SearchWorkerThread.CancellationPending) { break; }
1889 // if (!reader_addresses.Contains(address_index))
1890 // {
1891 // address_index += STEP_SIZE;
1892 // continue;
1893 // }
1894 // using (_16bit_unsigned_comparer_ comparer = new _16bit_unsigned_comparer_(SearchArgs, address_index))
1895 // {
1896 // ushort value = 0;
1897 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1898 // {
1899 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1900 // {
1901 // try
1902 // {
1903 // gmp.OpenProvider();
1904 // gmp.ReadMemory(address_index, out value);
1905 // gmp.CloseProvider();
1906 // }
1907 // catch (Exception ex)
1908 // {
1909 // logger.VerboseError.WriteLine(ex.ToString());
1910 // }
1911 // }
1912 // comparer.Value = value;
1913 // }
1914 // else
1915 // {
1916 // value = Convert.ToUInt16(SearchArgs.CompareStartValue);
1917 // comparer.Value = value;
1918 // }
1919 // if (comparer.Compare(Convert.ToUInt16(Value), value))
1920 // {
1921 // writer.WriteResult<ushort>(comparer.Address, comparer.Value);
1922 // }
1923 // }
1924 // address_index += STEP_SIZE;
1925 // }
1926 // #endregion
1927 // }
1928 // else
1929 // {
1930 // #region 16bits - signed
1931 // var t_data = BitTools.ConvertByteArray<short>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1932 // foreach (var Value in t_data)
1933 // {
1934 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1935 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
1936 // int inner_int_percent_done = (int)inner_double_percent_done;
1937 // if ((address_index % 10000) == 0)
1938 // {
1939 // UpdateProgress(inner_int_percent_done, inner_message);
1940 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
1941 // }
1942 // if (SearchWorkerThread.CancellationPending) { break; }
1943 // if (!reader_addresses.Contains(address_index))
1944 // {
1945 // address_index += STEP_SIZE;
1946 // continue;
1947 // }
1948 // using (_16bit_signed_comparer_ comparer = new _16bit_signed_comparer_(SearchArgs, address_index))
1949 // {
1950 // short value = 0;
1951 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
1952 // {
1953 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
1954 // {
1955 // try
1956 // {
1957 // gmp.OpenProvider();
1958 // gmp.ReadMemory(address_index, out value);
1959 // gmp.CloseProvider();
1960 // }
1961 // catch (Exception ex)
1962 // {
1963 // logger.VerboseError.WriteLine(ex.ToString());
1964 // }
1965 // }
1966 // comparer.Value = value;
1967 // }
1968 // else
1969 // {
1970 // value = Convert.ToInt16(SearchArgs.CompareStartValue);
1971 // comparer.Value = value;
1972 // }
1973 // if (comparer.Compare(Convert.ToSByte(Value), value))
1974 // {
1975 // writer.WriteResult<short>(comparer.Address, comparer.Value);
1976 // }
1977 // }
1978 // address_index += STEP_SIZE;
1979 // }
1980 // #endregion
1981 // } break;
1982 // case SearchDataTypes._32bits:
1983 // if (unsigned)
1984 // {
1985 // #region 32bits - unsigned
1986 // var t_data = BitTools.ConvertByteArray<uint>(data, new Func<bool>(ShouldCancelAnySearchOperation));
1987 // foreach (var Value in t_data)
1988 // {
1989 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
1990 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
1991 // int inner_int_percent_done = (int)inner_double_percent_done;
1992 // if ((address_index % 10000) == 0)
1993 // {
1994 // UpdateProgress(inner_int_percent_done, inner_message);
1995 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
1996 // }
1997 // if (SearchWorkerThread.CancellationPending) { break; }
1998 // if (!reader_addresses.Contains(address_index))
1999 // {
2000 // address_index += STEP_SIZE;
2001 // continue;
2002 // }
2003 // using (_32bit_unsigned_comparer_ comparer = new _32bit_unsigned_comparer_(SearchArgs, address_index))
2004 // {
2005 // uint value = 0;
2006 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
2007 // {
2008 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
2009 // {
2010 // try
2011 // {
2012 // gmp.OpenProvider();
2013 // gmp.ReadMemory(address_index, out value);
2014 // gmp.CloseProvider();
2015 // }
2016 // catch (Exception ex)
2017 // {
2018 // logger.VerboseError.WriteLine(ex.ToString());
2019 // }
2020 // }
2021 // comparer.Value = value;
2022 // }
2023 // else
2024 // {
2025 // value = Convert.ToUInt32(SearchArgs.CompareStartValue);
2026 // comparer.Value = value;
2027 // }
2028 // if (comparer.Compare(Convert.ToUInt32(Value), value))
2029 // {
2030 // writer.WriteResult<uint>(comparer.Address, comparer.Value);
2031 // }
2032 // }
2033 // address_index += STEP_SIZE;
2034 // }
2035 // #endregion
2036 // }
2037 // else
2038 // {
2039 // #region 32bits - signed
2040 // var t_data = BitTools.ConvertByteArray<int>(data, new Func<bool>(ShouldCancelAnySearchOperation));
2041 // foreach (var Value in t_data)
2042 // {
2043 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
2044 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
2045 // int inner_int_percent_done = (int)inner_double_percent_done;
2046 // if ((address_index % 10000) == 0)
2047 // {
2048 // UpdateProgress(inner_int_percent_done, inner_message);
2049 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
2050 // }
2051 // if (SearchWorkerThread.CancellationPending) { break; }
2052 // if (!reader_addresses.Contains(address_index))
2053 // {
2054 // address_index += STEP_SIZE;
2055 // continue;
2056 // }
2057 // using (_32bit_signed_comparer_ comparer = new _32bit_signed_comparer_(SearchArgs, address_index))
2058 // {
2059 // int value = 0;
2060 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
2061 // {
2062 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
2063 // {
2064 // try
2065 // {
2066 // gmp.OpenProvider();
2067 // gmp.ReadMemory(address_index, out value);
2068 // gmp.CloseProvider();
2069 // }
2070 // catch (Exception ex)
2071 // {
2072 // logger.VerboseError.WriteLine(ex.ToString());
2073 // }
2074 // }
2075 // comparer.Value = value;
2076 // }
2077 // else
2078 // {
2079 // value = Convert.ToInt32(SearchArgs.CompareStartValue);
2080 // comparer.Value = value;
2081 // }
2082 // if (comparer.Compare(Convert.ToInt32(Value), value))
2083 // {
2084 // writer.WriteResult<int>(comparer.Address, comparer.Value);
2085 // }
2086 // }
2087 // address_index += STEP_SIZE;
2088 // }
2089 // #endregion
2090 // } break;
2091 // case SearchDataTypes._64bits:
2092 // if (unsigned)
2093 // {
2094 // #region 64bits - unsigned
2095 // var t_data = BitTools.ConvertByteArray<ulong>(data, new Func<bool>(ShouldCancelAnySearchOperation));
2096 // foreach (var Value in t_data)
2097 // {
2098 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
2099 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
2100 // int inner_int_percent_done = (int)inner_double_percent_done;
2101 // if ((address_index % 10000) == 0)
2102 // {
2103 // UpdateProgress(inner_int_percent_done, inner_message);
2104 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
2105 // }
2106 // if (SearchWorkerThread.CancellationPending) { break; }
2107 // if (!reader_addresses.Contains(address_index))
2108 // {
2109 // address_index += STEP_SIZE;
2110 // continue;
2111 // }
2112 // using (_64bit_unsigned_comparer_ comparer = new _64bit_unsigned_comparer_(SearchArgs, address_index))
2113 // {
2114 // ulong value = 0;
2115 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
2116 // {
2117 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
2118 // {
2119 // try
2120 // {
2121 // gmp.OpenProvider();
2122 // gmp.ReadMemory(address_index, out value);
2123 // gmp.CloseProvider();
2124 // }
2125 // catch (Exception ex)
2126 // {
2127 // logger.VerboseError.WriteLine(ex.ToString());
2128 // }
2129 // }
2130 // comparer.Value = value;
2131 // }
2132 // else
2133 // {
2134 // value = Convert.ToUInt64(SearchArgs.CompareStartValue);
2135 // comparer.Value = value;
2136 // }
2137 // if (comparer.Compare(Convert.ToUInt64(Value), value))
2138 // {
2139 // writer.WriteResult<ulong>(comparer.Address, comparer.Value);
2140 // }
2141 // }
2142 // address_index += STEP_SIZE;
2143 // }
2144 // #endregion
2145 // }
2146 // else
2147 // {
2148 // #region 64bits - signed
2149 // var t_data = BitTools.ConvertByteArray<long>(data, new Func<bool>(ShouldCancelAnySearchOperation));
2150 // foreach (var Value in t_data)
2151 // {
2152 // string inner_message = string.Format(" -> Parsing value @ Address: 0x{0:x8}", address_index);
2153 // double inner_double_percent_done = 100.0 * (double)((double)address_index / (double)MemoryRangeSize);
2154 // int inner_int_percent_done = (int)inner_double_percent_done;
2155 // if ((address_index % 10000) == 0)
2156 // {
2157 // UpdateProgress(inner_int_percent_done, inner_message);
2158 // inner_Last_Whole_Percent_Done = inner_int_percent_done;
2159 // }
2160 // if (SearchWorkerThread.CancellationPending) { break; }
2161 // if (!reader_addresses.Contains(address_index))
2162 // {
2163 // address_index += STEP_SIZE;
2164 // continue;
2165 // }
2166 // using (_64bit_signed_comparer_ comparer = new _64bit_signed_comparer_(SearchArgs, address_index))
2167 // {
2168 // long value = 0;
2169 // if (SearchArgs.CompareValueType == CompareValueTypes.OldValue)
2170 // {
2171 // using (GenericMemoryProvider gmp = new GenericMemoryProvider((IAcceptsProcessAndConfig)this))
2172 // {
2173 // try
2174 // {
2175 // gmp.OpenProvider();
2176 // gmp.ReadMemory(address_index, out value);
2177 // gmp.CloseProvider();
2178 // }
2179 // catch (Exception ex)
2180 // {
2181 // logger.VerboseError.WriteLine(ex.ToString());
2182 // }
2183 // }
2184 // comparer.Value = value;
2185 // }
2186 // else
2187 // {
2188 // value = Convert.ToInt64(SearchArgs.CompareStartValue);
2189 // comparer.Value = value;
2190 // }
2191 // if (comparer.Compare(Convert.ToInt64(Value), value))
2192 // {
2193 // writer.WriteResult<long>(comparer.Address, comparer.Value);
2194 // }
2195 // }
2196 // address_index += STEP_SIZE;
2197 // }
2198 // #endregion
2199 // } break;
2200 // }
2201 // #endregion
2202 // if (SearchWorkerThread.CancellationPending)
2203 // {
2204 // provider_st.Stop();
2205 // st.Stop();
2206 // writer.CancelRequest();
2207 // writer.Dispose();
2208 // e.Result = true;
2209 // provider.CloseProvider();
2210 // return;
2211 // }
2212 //}
2213 #endregion
2214 }
2215 #endregion
2216
2217 SearchGuid = new_SearchGuid; // update with out new guid
2218 reader_addresses = null; // free memory used by address array
2219 GC.Collect(); // force gc collection
2220 #endregion
2221 }
2222
2223 }
2224 provider_st.Stop();
2225 logger.Profiler.WriteLine("It took a total of {0} seconds for the memory provider to complete it's operation(s).", provider_st.Elapsed.TotalSeconds);
2226 //if (buffered_mem.Length == 0) { logger.Warn.WriteLine("Buffered Memory is Zero Length."); return; }
2227 //int Last_Whole_Percent_Done = 0;
2228
2229
2230 #region Subsequent Searches
2231 //r_ms.BaseStream.Seek(0, SeekOrigin.Begin);
2232
2233
2234 // hack to help with OutOfMemory Exceptions (OldValue and Equal compare will always add all found search results)
2235 bool NeedToCompare = true;
2236 if (SearchArgs.CompareValueType == CompareValueTypes.OldValue &&
2237 SearchArgs.CompareType == SearchCompareTypes.Equal &&
2238 SearchArgs.IsFirstSearch)
2239 {
2240 NeedToCompare = false;
2241 //second_tmp_Results = null; // Free Memory
2242 }
2243
2244 if (NeedToCompare)
2245 {
2246 #region Ranged Searches
2247 #if !DONOT_HAVE_RANGED_SEARCH_SUPPORT
2248 if (SearchArgs.CompareType == SearchCompareTypes.Between || SearchArgs.CompareType == SearchCompareTypes.NotBetween)
2249 {
2250 st_ranged_search.Start();
2251 object start, end;
2252
2253 start = SearchArgs.CompareStartValue;
2254 end = SearchArgs.CompareEndValue;
2255 using (SearchResultReader reader = new SearchResultReader(SearchGuid))
2256 {
2257 for (int i = 0; i < reader.ResultCount; i += 1)
2258 {
2259 uint address = 0;
2260 #region switch (SearchArgs.DataType)
2261 switch (SearchArgs.DataType)
2262 {
2263 case SearchDataTypes._8bits: if (unsigned) { using (ResultType<byte> result = reader.GetNextResult<byte>()) { address = result.Address; } }
2264 else { using (ResultType<sbyte> result = reader.GetNextResult<sbyte>()) { address = result.Address; } } break;
2265 case SearchDataTypes._16bits: if (unsigned) { using (ResultType<ushort> result = reader.GetNextResult<ushort>()) { address = result.Address; } }
2266 else { using (ResultType<short> result = reader.GetNextResult<short>()) { address = result.Address; } } break;
2267 case SearchDataTypes._32bits: if (unsigned) { using (ResultType<uint> result = reader.GetNextResult<uint>()) { address = result.Address; } }
2268 else { using (ResultType<int> result = reader.GetNextResult<int>()) { address = result.Address; } } break;
2269 case SearchDataTypes._64bits: if (unsigned) { using (ResultType<ulong> result = reader.GetNextResult<ulong>()) { address = result.Address; } }
2270 else { using (ResultType<long> result = reader.GetNextResult<long>()) { address = result.Address; } } break;
2271 }
2272 #endregion
2273
2274 if (MemoryRangeStart > 0 && !SearchArgs.IsFirstSearch) { address = address - MemoryRangeStart; }
2275 //r_ms.BaseStream.Seek(address, SeekOrigin.Begin);
2276 if (SearchArgs.CompareType == SearchCompareTypes.Between)
2277 {
2278 using (InRangeComparer comparer = new InRangeComparer(address, 0))
2279 {
2280 if (comparer.Compare(start, end, SearchArgs.DataType, SearchArgs.IsUnsignedDataType, (IAcceptsProcessAndConfig)this))
2281 {
2282 using (ResultType<object> _tmp_result = new ResultType<object>(comparer.Address, comparer.Value))
2283 {
2284 second_tmp_Results.Add(_tmp_result);
2285 }
2286 }
2287 }
2288 }
2289 else if (SearchArgs.CompareType == SearchCompareTypes.NotBetween)
2290 {
2291 using (NotInRangeComparer comparer = new NotInRangeComparer(address, 0))
2292 {
2293 if (comparer.Compare(start, end, SearchArgs.DataType, SearchArgs.IsUnsignedDataType, (IAcceptsProcessAndConfig)this))
2294 {
2295 using (ResultType<object> _tmp_result = new ResultType<object>(comparer.Address, comparer.Value))
2296 {
2297 second_tmp_Results.Add(_tmp_result);
2298 }
2299 }
2300 }
2301 }
2302 else
2303 {
2304 throw new InvalidOperationException("Encounted unkown range search type: " + SearchArgs.CompareType);
2305 }
2306 double double_percent_done = 100.0 * (double)((double)i / (double)reader.ResultCount);
2307 int int_percent_done = (int)double_percent_done;
2308 if (int_percent_done != Last_Whole_Percent_Done)
2309 {
2310 if (int_percent_done <= 100)
2311 {
2312 resultsprogress.Value = int_percent_done;
2313 resultsprogress.Message = string.Format(" -> Reading Address: 0x{0:x8}", i + MemoryRangeStart);
2314 Last_Whole_Percent_Done = int_percent_done;
2315 }
2316 }
2317 }
2318 }
2319 st_ranged_search.Stop();
2320 logger.Profiler.WriteLine("Ranged search took a total of {0} seconds to complete.", st_ranged_search.Elapsed.TotalSeconds);
2321 }
2322 #endif
2323 #endregion
2324 }
2325 #endregion
2326 //// leave SearchArgs.Results alone, if false
2327 //if (NeedToCompare)
2328 //{
2329 // // fix addresses when memory start is not zero
2330 // 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; } }
2331 // using (SearchResultWriter writer = new SearchResultWriter(second_tmp_Results.Count, SearchGuid))
2332 // {
2333 // for (int i = 0; i < second_tmp_Results.Count; i++)
2334 // {
2335 // switch (sdt)
2336 // {
2337 // case SearchDataTypes._8bits:
2338 // if (unsigned) { writer.WriteResult<Byte>(second_tmp_Results[i].Address, Convert.ToByte(second_tmp_Results[i].Value)); }
2339 // else { writer.WriteResult<SByte>(second_tmp_Results[i].Address, Convert.ToSByte(second_tmp_Results[i].Value)); } break;
2340 // case SearchDataTypes._16bits:
2341 // if (unsigned) { writer.WriteResult<UInt16>(second_tmp_Results[i].Address, Convert.ToUInt16(second_tmp_Results[i].Value)); }
2342 // else { writer.WriteResult<Int16>(second_tmp_Results[i].Address, Convert.ToInt16(second_tmp_Results[i].Value)); } break;
2343 // case SearchDataTypes._32bits:
2344 // if (unsigned) { writer.WriteResult<UInt32>(second_tmp_Results[i].Address, Convert.ToUInt32(second_tmp_Results[i].Value)); }
2345 // else { writer.WriteResult<Int32>(second_tmp_Results[i].Address, Convert.ToInt32(second_tmp_Results[i].Value)); } break;
2346 // case SearchDataTypes._64bits:
2347 // if (unsigned) { writer.WriteResult<UInt64>(second_tmp_Results[i].Address, Convert.ToUInt64(second_tmp_Results[i].Value)); }
2348 // else { writer.WriteResult<Int64>(second_tmp_Results[i].Address, Convert.ToInt64(second_tmp_Results[i].Value)); } break;
2349 // }
2350 // }
2351 // }
2352 // second_tmp_Results = null; // free memory
2353 //}
2354 }
2355 catch (OutOfMemoryException ex)
2356 {
2357 e.Result = true;
2358 logger.Error.WriteLine("Encounted {0} for search: {0}", ex.GetType().Name, SearchGuid.ToString());
2359 logger.VerboseError.WriteLine(ex.ToString());
2360 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);
2361 return;
2362 }
2363 catch (Exception ex)
2364 {
2365 throw ex;
2366 }
2367 }
2368
2369
2370
2371 private void SearchWorkerThread_ProgressChanged(object sender, ProgressChangedEventArgs e)
2372 {
2373 //if (SearchArgs.ProgressLogger != null)
2374 //{
2375 // resultsprogress.Value = e.ProgressPercentage;
2376 // //Application.DoEvents();
2377 //}
2378 }
2379
2380 private void SearchWorkerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
2381 {
2382 try { if ((bool)e.Result) { logger.Warn.WriteLine("Search operation was cancelled.");
2383 //new Action<int, string>(UpdateProgress).Invoke(0, string.Empty);
2384 UpdateProgress(0, string.Empty);
2385 return; }
2386 }
2387 catch (InvalidCastException) { }
2388 try
2389 {
2390 Stopwatch st = (Stopwatch)e.Result;
2391 st.Stop();
2392 logger.Profiler.WriteLine("Search took {0} seconds, overall, to complete.", st.Elapsed.TotalSeconds);
2393 }
2394 catch (InvalidCastException) { }
2395 catch (Exception ex) { throw ex; }
2396
2397 UpdateProgress(100, String.Empty);
2398 //new Action<int, string>(UpdateProgress).Invoke(100, string.Empty);
2399 bool unsigned = SearchArgs.IsUnsignedDataType;
2400 using (SearchResultReader reader = new SearchResultReader(SearchGuid, SearchArgs.IsUnsignedDataType, SearchArgs.DataType, new Action<int, string>(UpdateProgress), new Func<bool>(ShouldCancelAnySearchOperation)))
2401 {
2402 logger.Info.WriteLine(string.Format("Found 0x{0:x8} results", reader.ResultCount));
2403
2404 if (reader.ResultCount <= MIN_NUMBER_OF_RESULTS_BEFORE_DISPLAY)
2405 {
2406 lstResults.Items.Clear();
2407 List<ResultItem> items = new List<ResultItem>();
2408 foreach (var k in reader)
2409 {
2410 switch (SearchArgs.DataType)
2411 {
2412 case SearchDataTypes._8bits:
2413 if (SearchArgs.IsUnsignedDataType) { items.Add(new ResultItem(k.Address, false, Convert.ToByte(k.Value))); }
2414 else { items.Add(new ResultItem(k.Address, false, Convert.ToSByte(k.Value))); }
2415 break;
2416 case SearchDataTypes._16bits:
2417 if (SearchArgs.IsUnsignedDataType) { items.Add(new ResultItem(k.Address, false, Convert.ToUInt16(k.Value))); }
2418 else { items.Add(new ResultItem(k.Address, false, Convert.ToInt16(k.Value))); }
2419 break;
2420 case SearchDataTypes._32bits:
2421 if (SearchArgs.IsUnsignedDataType) { items.Add(new ResultItem(k.Address, false, Convert.ToUInt32(k.Value))); }
2422 else { items.Add(new ResultItem(k.Address, false, Convert.ToInt32(k.Value))); }
2423 break;
2424 case SearchDataTypes._64bits:
2425 if (SearchArgs.IsUnsignedDataType) { items.Add(new ResultItem(k.Address, false, Convert.ToUInt64(k.Value))); }
2426 else { items.Add(new ResultItem(k.Address, false, Convert.ToInt64(k.Value))); }
2427 break;
2428 }
2429 }
2430 lstResults.Items.AddRange(items.ToArray());
2431 }
2432 }
2433 GC.Collect(); // force gc collection
2434 this.DoSearchDoneSpecific();
2435 //System.Threading.Thread.Sleep(100);
2436 //if (_SEARCH_MODE != SearchMode.SEARCH_MODE_NORMAL_WITH_JOKER)
2437 this.ThawResultsUpdate();
2438 Application.DoEvents();
2439 }
2440 private void DoSearchDoneSpecific()
2441 {
2442 SearchWorkerThread.CancelAsync();
2443 if (lstResults.Items.Count > 0) { timer_update_results.Enabled = true; }
2444 else { timer_update_results.Enabled = false; }
2445
2446 search_progress_updater.Enabled = false;
2447
2448 btnCancel.Enabled = false;
2449 btnReset.Enabled = true;
2450 btnSearch.Enabled = true;
2451 grpCompareType.Enabled = true;
2452 grpCompareValue.Enabled = true;
2453 UpdateProgress(0, string.Empty);
2454 //new Action<int, string>(UpdateProgress).Invoke(0, string.Empty);
2455 grpDataType.Enabled = false;
2456 // resume process on reset, incase it was suspended
2457 ThreadControl.ResumeProcess(this.AcceptedProcess.Id);
2458 //Application.DoEvents();
2459 this.Refresh();
2460 }
2461
2462 private void DoCancelSpecific()
2463 {
2464 this.DoSearchDoneSpecific();
2465 }
2466 private void DoResetSpecific()
2467 {
2468 this.DoCancelSpecific();
2469 IsFirstSearch = true;
2470 grpDataType.Enabled = true;
2471 btnReset.Enabled = false;
2472
2473 // delete any temporary search result files
2474 SearchResultWriter.CleanupTemporarySearchResultFiles();
2475
2476 }
2477 private void search_progress_updater_Tick(object sender, EventArgs e)
2478 {
2479 if ((this.AcceptedProcess ==null) || Process.GetProcessById(this.AcceptedProcess.Id) == null)
2480 {
2481 SearchWorkerThread.CancelAsync();
2482 //JokerSearchWorker.CancelAsync();
2483 ResultsUpdateWorkerThread.CancelAsync();
2484 }
2485 }
2486
2487 #region Search Button
2488 private void btnSearch_Click(object sender, EventArgs e)
2489 {
2490 if (this.SearchGuid == Guid.Empty)
2491 this.SearchGuid = Guid.NewGuid();
2492 chkMemoryRangeExpertMode.Enabled = false;
2493 this.SearchInProgess = true;
2494 btnCancel.Enabled = true;
2495 btnReset.Enabled = false; // disable during search
2496 btnSearch.Enabled = false;
2497 this.FreezeResultsUpdate();
2498 this.handle_btnSearch_Click();
2499 }
2500 private void handle_btnSearch_Click()
2501 {
2502 if (chkMemoryRangeExpertMode.Checked)
2503 {
2504 // update the settings
2505 this.MemoryRangeStart = txtMemoryRangeStart.Value;
2506 this.MemoryRangeSize = txtMemoryRangeSize.Value;
2507 }
2508
2509 //this.FreezeResultsUpdate();
2510 lstResults.Items.Clear();
2511
2512 if (lstResults.Items.Count > 0) { timer_update_results.Enabled = true; }
2513 else { timer_update_results.Enabled = false; }
2514 UpdateProgress(0, string.Empty);
2515 //new Action<int, string>(UpdateProgress).Invoke(0, string.Empty);
2516 bool _is_unsigned = chkUnsigned.Checked;
2517 SearchType search_type = new SearchType();
2518 SearchDataTypes _data_type = new SearchDataTypes();
2519 SearchCompareTypes _compare_type = new SearchCompareTypes();
2520 CompareValueTypes _compare_value_type = new CompareValueTypes();
2521 object start_value = 0;
2522 object end_value = 0;
2523 // get datatype
2524 if (radio_8bits.Checked) { _data_type = SearchDataTypes._8bits; }
2525 else if (radio_16bits.Checked) { _data_type = SearchDataTypes._16bits; }
2526 else if (radio_32bits.Checked) { _data_type = SearchDataTypes._32bits; }
2527 else if (radio_64bits.Checked) { _data_type = SearchDataTypes._64bits; }
2528 else { logger.Error.WriteLine("Could not determine search data type bit size. (was not 8/16/32/or 64bits)"); }
2529 // get compare type
2530 if (radiocompare_equal.Checked) { _compare_type = SearchCompareTypes.Equal; }
2531 else if (radiocompare_greaterthan.Checked) { _compare_type = SearchCompareTypes.GreaterThan; }
2532 else if (radiocompare_lessthan.Checked) { _compare_type = SearchCompareTypes.LessThan; }
2533 else if (radiocompare_greaterthan_orequal.Checked) { _compare_type = SearchCompareTypes.GreaterThanOrEqual; }
2534 else if (radiocompare_lessthan_orequal.Checked) { _compare_type = SearchCompareTypes.LessThanOrEqual; }
2535 else if (radiocompare_notequal.Checked) { _compare_type = SearchCompareTypes.NotEqual; }
2536 else if (radiocompare_between.Checked) { _compare_type = SearchCompareTypes.Between; }
2537 else if (radiocompare_notbetween.Checked) { _compare_type = SearchCompareTypes.NotBetween; }
2538 else { logger.Error.WriteLine("Could not determine search comparison type. (was not == > < >= <= != <> or !<>)"); }
2539 // get compare valure type
2540 if (radio_oldvalue.Checked) { _compare_value_type = CompareValueTypes.OldValue; }
2541 else if (radio_specificvalue.Checked) { _compare_value_type = CompareValueTypes.SpecificValue; }
2542 else { logger.Error.WriteLine("Could not determine search comparison type. (was not old or specific value"); }
2543
2544 if (_compare_value_type == CompareValueTypes.SpecificValue || (_compare_type == SearchCompareTypes.Between || _compare_type == SearchCompareTypes.NotBetween))
2545 {
2546
2547 switch (_data_type)
2548 {
2549 case SearchDataTypes._8bits:
2550 if (_is_unsigned) { start_value = txtStartAddr.ToByte(); }
2551 else { start_value = txtStartAddr.ToSByte(); }
2552 break;
2553 case SearchDataTypes._16bits:
2554 if (_is_unsigned) { start_value = txtStartAddr.ToUInt16(); }
2555 else { start_value = txtStartAddr.ToInt16(); }
2556 break;
2557 case SearchDataTypes._32bits:
2558 if (_is_unsigned) { start_value = txtStartAddr.ToUInt32(); }
2559 else { start_value = txtStartAddr.ToInt32(); }
2560 break;
2561 case SearchDataTypes._64bits:
2562 if (_is_unsigned) { start_value = txtStartAddr.ToUInt64(); }
2563 else { start_value = txtStartAddr.ToInt64(); }
2564 break;
2565 default: throw new InvalidOperationException("In SearchType(): Encounterd an Unkown Search Data Type.");
2566 }
2567 }
2568 if (_compare_type == SearchCompareTypes.Between || _compare_type == SearchCompareTypes.NotBetween)
2569 {
2570 switch (_data_type)
2571 {
2572 case SearchDataTypes._8bits:
2573 if (_is_unsigned) { end_value = txtEndAddr.ToByte(); }
2574 else { end_value = txtEndAddr.ToSByte(); }
2575 break;
2576 case SearchDataTypes._16bits:
2577 if (_is_unsigned) { end_value = txtEndAddr.ToUInt16(); }
2578 else { end_value = txtEndAddr.ToInt16(); }
2579 break;
2580 case SearchDataTypes._32bits:
2581 if (_is_unsigned) { end_value = txtEndAddr.ToUInt32(); }
2582 else { end_value = txtEndAddr.ToInt32(); }
2583 break;
2584 case SearchDataTypes._64bits:
2585 if (_is_unsigned) { end_value = txtEndAddr.ToUInt64(); }
2586 else { end_value = txtEndAddr.ToInt64(); }
2587 break;
2588 default: throw new InvalidOperationException("In SearchType(): Encounterd an Unkown Search Data Type.");
2589 }
2590 }
2591
2592 search_type = new SearchType(_data_type, _is_unsigned, _compare_type, _compare_value_type, start_value, end_value, resultsprogress);
2593
2594 //search_type.LogSearchOptions();
2595
2596 search_type.IsFirstSearch = IsFirstSearch;
2597
2598
2599
2600 DoSearch(search_type);
2601 IsFirstSearch = false;
2602 }
2603 private void DoSearch(SearchType args)
2604 {
2605 if (!args.IsFirstSearch && SearchArgs != null)
2606 {
2607 //args.Results.AddRange(SearchArgs.Results.ToArray());
2608 //args.Results = SearchArgs.Results;
2609 }
2610 SearchArgs = args;
2611 #if DONOT_HAVE_RANGED_SEARCH_SUPPORT
2612 if (SearchArgs.CompareType == SearchCompareTypes.Between || SearchArgs.CompareType == SearchCompareTypes.NotBetween)
2613 {
2614 throw new NotImplementedException("Between and Not Between Range searches have not been implemented.");
2615 }
2616 #endif
2617 search_progress_updater.Enabled = true;
2618 //padPluginSelector.Enabled = false;
2619 //gsPluginSelector.Enabled = false;
2620 btnReset.Enabled = false; // this will be disabled until the earch is finished
2621 btnSearch.Enabled = false;
2622 btnCancel.Enabled = true;
2623 grpDataType.Enabled = false;
2624 grpCompareType.Enabled = false;
2625 grpCompareValue.Enabled = false;
2626 this.Refresh();
2627 Application.DoEvents();
2628 SearchWorkerThread.RunWorkerAsync();
2629 }
2630 #endregion
2631 private void btnReset_Click(object sender, EventArgs e)
2632 {
2633 this.SearchGuid = Guid.Empty;
2634 this.SearchInProgess = false;
2635 chkMemoryRangeExpertMode.Enabled = true;
2636 btnSearch.Enabled = true;
2637 btnReset.Enabled = false;
2638 btnCancel.Enabled = false;
2639 this.DoResetSpecific();
2640 lstResults.Items.Clear();
2641 //try { SearchArgs.Results = new List<ResultType<object>>(); }
2642 //catch { }
2643 }
2644
2645 private void btnCancel_Click(object sender, EventArgs e)
2646 {
2647 this.SearchInProgess = false;
2648 btnCancel.Enabled = false;
2649 btnSearch.Enabled = true;
2650 btnReset.Enabled = true;
2651 this.DoCancelSpecific();
2652 }
2653
2654 private void mnuItemPatchListViewMemoryRegion_Click(object sender, EventArgs e)
2655 {
2656 List<ResultDataType> patch_list = new List<ResultDataType>();
2657 List<int> SelectedIndexes = new List<int>();
2658 foreach (int index in lstPatchList.SelectedIndices) { SelectedIndexes.Add(index); }
2659 foreach (int index in SelectedIndexes)
2660 {
2661 ListViewItem item = lstPatchList.Items[index];
2662 ResultDataType rdt = (ResultDataType)item.Tag;
2663 ViewMemoryRegion(rdt);
2664 break; // only get the fist item
2665 }
2666 }
2667
2668 private void mnuItemResultsListViewMemoryRegion_Click(object sender, EventArgs e)
2669 {
2670 List<ResultDataType> patch_list = new List<ResultDataType>();
2671 List<int> SelectedIndexes = new List<int>();
2672 foreach (int index in lstResults.SelectedIndices) { SelectedIndexes.Add(index); }
2673 foreach (int index in SelectedIndexes)
2674 {
2675 ListViewItem item = lstResults.Items[index];
2676 ResultDataType rdt = (ResultDataType)item.Tag;
2677 ViewMemoryRegion(rdt);
2678 break; // only get the fist item
2679 }
2680 }
2681 private void ViewMemoryRegion(ResultDataType rdt)
2682 {
2683 if (OnBrowseMemoryRegion != null)
2684 OnBrowseMemoryRegion(new BrowseMemoryRegionEvent(this, rdt.Address));
2685 }
2686
2687 private void mnuAddedResults_Opening(object sender, CancelEventArgs e)
2688 {
2689 if (!(lstPatchList.Items.Count > 0)) { mnuItemRemoveResult.Visible = false; e.Cancel = true; }
2690 if (!(lstPatchList.Items.Count > 0)) { mnuItemPatchSelectedEntry.Visible = false; e.Cancel = true; }
2691 if (e.Cancel) return;
2692 if (lstPatchList.Items.Count > 0) mnuItemRemoveResult.Visible = true;
2693 if (lstPatchList.Items.Count > 0) mnuItemPatchSelectedEntry.Visible = true;
2694
2695 if (!(lstPatchList.Items.Count > 0)) { mnuItemFreezeSelectedPatches.Visible = false; e.Cancel = true; }
2696 if (!(lstPatchList.Items.Count > 0)) { mnuItemThawSelectedPatches.Visible = false; e.Cancel = true; }
2697 if (e.Cancel) return;
2698
2699 if (lstPatchList.Items.Count > 0) mnuItemFreezeSelectedPatches.Visible = true;
2700 if (lstPatchList.Items.Count > 0) mnuItemThawSelectedPatches.Visible = true;
2701
2702 if (lstPatchList.SelectedItems.Count == 0) e.Cancel = true;
2703 if (e.Cancel) return;
2704
2705 }
2706
2707 private void mnuResults_Opening(object sender, CancelEventArgs e)
2708 {
2709 if (!(lstResults.Items.Count > 0)) e.Cancel = true;
2710 if (lstResults.SelectedItems.Count == 0) e.Cancel = true;
2711 if (SearchArgs == null) e.Cancel = true;
2712 if (e.Cancel) return;
2713 }
2714
2715 private void chkMemoryRangeExpertMode_CheckedChanged(object sender, EventArgs e)
2716 {
2717 txtMemoryRangeStart.ReadOnly = !chkMemoryRangeExpertMode.Checked;
2718 txtMemoryRangeSize.ReadOnly = !chkMemoryRangeExpertMode.Checked;
2719 }
2720
2721 private void txtMemoryRangeStart_ValueChanged(object sender, ValueChangedEventArgs e) { this.MemoryRangeStart = Convert.ToUInt64(e.NewValue); }
2722 private void txtMemoryRangeSize_ValueChanged(object sender, ValueChangedEventArgs e) { this.MemoryRangeSize = Convert.ToUInt64(e.NewValue); }
2723
2724 private void FloatingMemorySearcher_Load(object sender, EventArgs e)
2725 {
2726 #if DONOT_HAVE_RANGED_SEARCH_SUPPORT
2727 radiocompare_between.Enabled = false;
2728 radiocompare_notbetween.Enabled = false;
2729
2730 #endif
2731 }
2732
2733
2734 public void SetPEViewerData(IPEDData peData)
2735 {
2736 this.PEData = peData;
2737 this.MemoryRangeStart = MemorySizeConstants.MinimumAddress;
2738 if (this.PEData != null)
2739 {
2740 if (this.PEData.Is32bitAssembly())
2741 {
2742 this.MemoryRangeSize= MemorySizeConstants.MinimumAddress + MemorySizeConstants.MaximumAddressSize_x86;
2743 }
2744 else
2745 {
2746 this.MemoryRangeSize = MemorySizeConstants.MinimumAddress + MemorySizeConstants.MaximumAddressSize_x64;
2747 }
2748 }
2749 else
2750 {
2751 this.MemoryRangeSize = MemorySizeConstants.MinimumAddress + MemorySizeConstants.MaximumAddressSize_x86;
2752 }
2753 }
2754 }
2755 }

  ViewVC Help
Powered by ViewVC 1.1.22