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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 838 - (show annotations) (download)
Tue Sep 16 00:57:18 2014 UTC (6 years ago) by william
File size: 161133 byte(s)
+ add an icon resource

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

  ViewVC Help
Powered by ViewVC 1.1.22