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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 686 - (show annotations) (download)
Mon Jun 17 09:31:52 2013 UTC (8 years ago) by william
File size: 161041 byte(s)
+ massive move of source files

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

  ViewVC Help
Powered by ViewVC 1.1.22