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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.22