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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.22