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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 812 - (show annotations) (download)
Tue Apr 15 14:52:10 2014 UTC (5 years, 9 months ago) by william
File size: 161041 byte(s)
+ update logging to use Enterpise.Logging -- more work is still needed

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

  ViewVC Help
Powered by ViewVC 1.1.22