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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.22