-
Notifications
You must be signed in to change notification settings - Fork 30
/
DbgEngDll.cs
1807 lines (1595 loc) · 72.2 KB
/
DbgEngDll.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using SharpDebug.Engine.Debuggers.DbgEngDllHelpers;
using SharpDebug.Engine.Marshaling;
using SharpDebug.Engine.Native;
using SharpDebug.Engine.SymbolProviders;
using SharpDebug.Engine.Utility;
using SharpDebug.Exceptions;
using DbgEng;
using DIA;
using SharpUtilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpDebug.Engine.Debuggers
{
/// <summary>
/// DbgEng.dll implementation of <see cref="IDebuggerEngine"/>.
/// </summary>
/// <seealso cref="SharpDebug.Engine.IDebuggerEngine" />
public class DbgEngDll : IDebuggerEngine
{
/// <summary>
/// The original debug client interface
/// </summary>
private IDebugClient originalClient;
/// <summary>
/// Default symbol provider cache.
/// </summary>
private SimpleCache<DbgEngSymbolProvider> dbgEngSymbolProvider;
/// <summary>
/// The thread debug client interface
/// </summary>
[ThreadStatic]
private static IDebugClient threadClient;
/// <summary>
/// The state cache
/// </summary>
private System.Threading.ThreadLocal<StateCache> stateCache;
/// <summary>
/// Dictionary of all debuggee flow controllers. Key is process id that is being debugged.
/// </summary>
private DebuggeeFlowController debuggeeFlowController;
/// <summary>
/// Mapping from DIA register index into DbgEng.dll register index.
/// </summary>
private DictionaryCache<CV_HREG_e, uint> registerIndexes;
/// <summary>
/// Initializes a new instance of the <see cref="DbgEngDll"/> class.
/// </summary>
/// <param name="debugClient">The debugger client interface.</param>
public DbgEngDll(IDebugClient debugClient)
{
originalClient = debugClient;
dbgEngSymbolProvider = SimpleCache.Create(() => new DbgEngSymbolProvider(this));
stateCache = new System.Threading.ThreadLocal<StateCache>(() => new StateCache(this));
registerIndexes = new DictionaryCache<CV_HREG_e, uint>(GetRegisterIndex);
if (IsLiveDebugging)
{
debuggeeFlowController = new DebuggeeFlowController(this);
}
}
/// <summary>
/// Gets a value indicating whether debugger is currently in live debugging.
/// </summary>
/// <value>
/// <c>true</c> if debugger is currently in live debugging; otherwise, <c>false</c>.
/// </value>
public bool IsLiveDebugging
{
get
{
try
{
return Client.GetNumberDumpFiles() == 0;
}
catch (Exception)
{
return false;
}
}
}
/// <summary>
/// Gets the state cache.
/// </summary>
internal StateCache StateCache
{
get
{
return stateCache.Value;
}
}
/// <summary>
/// Gets the thread debug client interface.
/// </summary>
internal IDebugClient ThreadClient
{
get
{
if (threadClient == null)
{
threadClient = originalClient.CreateClient();
}
return threadClient;
}
}
/// <summary>
/// Gets the DbgEng.dll Advanced interface
/// </summary>
public IDebugAdvanced4 Advanced
{
get
{
return ThreadClient as IDebugAdvanced4;
}
}
/// <summary>
/// The DbgEng.dll Client interface
/// </summary>
public IDebugClient7 Client
{
get
{
return ThreadClient as IDebugClient7;
}
}
/// <summary>
/// The DbgEng.dll Control interface
/// </summary>
public IDebugControl7 Control
{
get
{
return ThreadClient as IDebugControl7;
}
}
/// <summary>
/// The DbgEng.dll Data spaces interface
/// </summary>
public IDebugDataSpaces4 DataSpaces
{
get
{
return ThreadClient as IDebugDataSpaces4;
}
}
/// <summary>
/// The DbgEng.dll Registers interface
/// </summary>
public IDebugRegisters2 Registers
{
get
{
return ThreadClient as IDebugRegisters2;
}
}
/// <summary>
/// The DbgEng.dll Symbols interface
/// </summary>
public IDebugSymbols5 Symbols
{
get
{
return ThreadClient as IDebugSymbols5;
}
}
/// <summary>
/// The DbgEng.dll System objects interface
/// </summary>
public IDebugSystemObjects4 SystemObjects
{
get
{
return ThreadClient as IDebugSystemObjects4;
}
}
/// <summary>
/// Initializes the context with the specified <see cref="IDebugClient"/>.
/// </summary>
/// <param name="client">The client.</param>
public static void InitializeContext(IDebugClient client)
{
if (client != null)
{
IDebuggerEngine debugger = new DbgEngDll(client);
ISymbolProvider symbolProvider = new DiaSymbolProvider(debugger.GetDefaultSymbolProvider());
Context.InitializeDebugger(debugger, symbolProvider);
}
else
{
Context.InitializeDebugger(null, null);
}
}
/// <summary>
/// Ends current debugging session and disposes used memory.
/// This method is being called when new debugger engine is loaded with <see cref="Context.InitializeDebugger(IDebuggerEngine, ISymbolProvider)"/>.
/// </summary>
public void EndSession()
{
// Do nothing. Ending DbgEng.dll session closes all processes being debugger, even new one that is not being set.
}
#region Executing native commands
/// <summary>
/// Executes the specified command and captures its output.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Captured text</returns>
public static string ExecuteAndCapture(string command, params object[] parameters)
{
DebugOutput captureFlags = DebugOutput.Normal | DebugOutput.Error | DebugOutput.Warning | DebugOutput.Verbose
| DebugOutput.Prompt | DebugOutput.PromptRegisters | DebugOutput.ExtensionWarning | DebugOutput.Debuggee
| DebugOutput.DebuggeePrompt | DebugOutput.Symbols | DebugOutput.Status;
return ExecuteAndCapture(captureFlags, command, parameters);
}
/// <summary>
/// Executes the specified command and captures its output.
/// </summary>
/// <param name="captureFlags">The capture flags.</param>
/// <param name="command">The command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>Captured text</returns>
public static string ExecuteAndCapture(DebugOutput captureFlags, string command, params object[] parameters)
{
using (StringWriter writer = new StringWriter())
{
var callbacks = DebuggerOutputToTextWriter.Create(writer, captureFlags);
using (OutputCallbacksSwitcher switcher = OutputCallbacksSwitcher.Create(callbacks))
{
Execute(command, parameters);
writer.Flush();
return writer.GetStringBuilder().ToString();
}
}
}
/// <summary>
/// Executes the specified command, but leaves its output visible to the user.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="parameters">The parameters.</param>
public static void Execute(string command, params object[] parameters)
{
((DbgEngDll)Context.Debugger).ExecuteCommand(command, parameters);
}
#endregion
/// <summary>
/// Executes the specified command, but leaves its output visible to the user.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="parameters">The parameters.</param>
public void ExecuteCommand(string command, params object[] parameters)
{
command = string.Join(" ", command, string.Join(" ", parameters));
StateCache.SyncState();
Control.Execute((uint)DebugOutctl.ThisClient, command, (uint)(DebugExecute.NotLogged_ | DebugExecute.NoRepeat));
}
/// <summary>
/// Finds the pattern in memory of the specified process.
/// </summary>
/// <param name="process">The process.</param>
/// <param name="memoryStart">The memory start.</param>
/// <param name="memoryEnd">The memory end.</param>
/// <param name="pattern">The pattern.</param>
/// <param name="patternStart">The pattern start.</param>
/// <param name="patternEnd">The pattern end.</param>
/// <param name="searchAlignment">The search alignment in number of bytes. For a successful match, the difference between the location of the found pattern and memoryStart must be a multiple of searchAlignment.</param>
/// <param name="searchWritableMemoryOnly">if set to <c>true</c> search through writable memory only.</param>
/// <returns>Address of the successful match or 0 if patterns wasn't found.</returns>
public ulong FindPatternInMemory(Process process, ulong memoryStart, ulong memoryEnd, byte[] pattern, int patternStart, int patternEnd, uint searchAlignment = 1, bool searchWritableMemoryOnly = false)
{
if (memoryEnd <= memoryStart)
{
throw new ArgumentOutOfRangeException("memoryEnd", "less than memoryStart");
}
int patternSize = patternEnd - patternStart;
IntPtr pointer = Marshal.AllocHGlobal(patternSize);
try
{
Marshal.Copy(pattern, patternStart, pointer, patternSize);
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
return DataSpaces.SearchVirtual2(memoryStart, memoryEnd - memoryStart, searchWritableMemoryOnly ? 1U : 0U, pointer, (uint)patternSize, searchAlignment);
}
}
catch (COMException ex)
{
if ((uint)ex.HResult == 0x9000001A)
{
return 0;
}
throw;
}
finally
{
Marshal.FreeHGlobal(pointer);
}
}
/// <summary>
/// Gets the dump file memory reader of the specified process if it is debugged from a dump.
/// </summary>
/// <param name="process">The process.</param>
public DumpFileMemoryReader GetDumpFileMemoryReader(Process process)
{
string dumpFilename = process.DumpFileName;
if (File.Exists(dumpFilename))
{
return new WindowsDumpFileMemoryReader(dumpFilename);
}
return null;
}
/// <summary>
/// Reads the memory from the specified process.
/// </summary>
/// <param name="process">The process.</param>
/// <param name="address">The memory address.</param>
/// <param name="size">The buffer size.</param>
/// <returns>
/// Buffer containing read memory
/// </returns>
public MemoryBuffer ReadMemory(Process process, ulong address, uint size)
{
try
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
IntPtr buffer = Marshal.AllocHGlobal((int)size);
uint read;
try
{
DataSpaces.ReadVirtual(address, buffer, size, out read);
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, (int)size);
return new MemoryBuffer(bytes);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
}
catch (Exception)
{
throw new InvalidMemoryAddressException(address);
}
}
/// <summary>
/// Gets the module name. This is usually just the file name without the extension. In a few cases,
/// the module name differs significantly from the file name.
/// </summary>
/// <param name="module">The module.</param>
public string GetModuleName(Module module)
{
return GetModuleName(module, DebugModname.Module);
}
/// <summary>
/// Gets the name of the image. This is the name of the executable file, including the extension.
/// Typically, the full path is included in user mode but not in kernel mode.
/// </summary>
/// <param name="module">The module.</param>
public string GetModuleImageName(Module module)
{
return GetModuleName(module, DebugModname.Image);
}
/// <summary>
/// Gets the name of the loaded image. Unless Microsoft CodeView symbols are present, this is the same as the image name.
/// </summary>
/// <param name="module">The module.</param>
public string GetModuleLoadedImage(Module module)
{
return GetModuleName(module, DebugModname.LoadedImage);
}
/// <summary>
/// Gets the name of the symbol file. The path and name of the symbol file. If no symbols have been loaded,
/// this is the name of the executable file instead.
/// </summary>
/// <param name="module">The module.</param>
public string GetModuleSymbolFile(Module module)
{
return GetModuleName(module, DebugModname.SymbolFile);
}
/// <summary>
/// Gets the name of the mapped image. In most cases, this is null. If the debugger is mapping an image file
/// (for example, during minidump debugging), this is the name of the mapped image.
/// </summary>
/// <param name="module">The module.</param>
public string GetModuleMappedImage(Module module)
{
return GetModuleName(module, DebugModname.MappedImage);
}
/// <summary>
/// Gets the name of the module.
/// </summary>
/// <param name="module">The module.</param>
/// <param name="modname">The type of module name.</param>
/// <returns>Read name</returns>
private string GetModuleName(Module module, DebugModname modname)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, module.Process))
{
uint nameSize;
StringBuilder sb = new StringBuilder(Constants.MaxFileName);
Symbols.GetModuleNameStringWide((uint)modname, 0xffffffff, module.Address, sb, (uint)sb.Capacity, out nameSize);
if (modname == DebugModname.MappedImage && !File.Exists(sb.ToString()))
{
uint imagePathSize;
Symbols.GetImagePathWide(null, 0, out imagePathSize);
StringBuilder imagePath = new StringBuilder((int)imagePathSize + 1);
Symbols.GetImagePathWide(imagePath, (uint)imagePath.Capacity, out imagePathSize);
uint symbolPathSize;
Symbols.GetSymbolPathWide(null, 0, out symbolPathSize);
StringBuilder symbolPath = new StringBuilder((int)symbolPathSize + 1);
Symbols.GetSymbolPathWide(symbolPath, (uint)symbolPath.Capacity, out symbolPathSize);
List<string> folders = new List<string>();
folders.AddRange(imagePath.ToString().Split(";".ToCharArray()));
folders.AddRange(symbolPath.ToString().Split(";".ToCharArray()));
foreach (string folder in folders)
{
try
{
string path = Path.Combine(folder, module.LoadedImageName);
if (File.Exists(path))
{
return path;
}
}
catch
{
}
}
return null;
}
return sb.ToString();
}
}
/// <summary>
/// Add new breakpoint.
/// </summary>
/// <param name="process">Target process for breakpoint.</param>
/// <param name="breakpointSpec">Description of this breakpoint.</param>
/// <returns>Newly added breakpoint.</returns>
public IBreakpoint AddBreakpoint(Process process, BreakpointSpec breakpointSpec)
{
using (var processSwitcher = new ProcessSwitcher(StateCache, process))
{
DbgEngBreakpoint breakpoint = new DbgEngBreakpoint(breakpointSpec, () => process.InvalidateProcessCache(), this);
debuggeeFlowController.AddBreakpoint(breakpoint);
return breakpoint;
}
}
/// <summary>
/// Gets the current stack frame of the specified thread.
/// </summary>
/// <param name="thread">The thread.</param>
public StackFrame GetThreadCurrentStackFrame(Thread thread)
{
return StateCache.CurrentStackFrame[thread];
}
/// <summary>
/// Sets the current stack frame.
/// </summary>
/// <param name="stackFrame">The stack frame.</param>
public void SetCurrentStackFrame(StackFrame stackFrame)
{
StateCache.SetCurrentStackFrame(stackFrame);
}
/// <summary>
/// Reads the line from the debugger input.
/// </summary>
public string ReadInput()
{
uint inputSize;
StringBuilder sb = new StringBuilder(10240);
Control.InputWide(sb, (uint)sb.Capacity, out inputSize);
return sb.ToString();
}
/// <summary>
/// Sets the current thread.
/// </summary>
/// <param name="thread">The thread.</param>
public void SetCurrentThread(Thread thread)
{
StateCache.SetCurrentThread(thread);
}
/// <summary>
/// Gets the environment block address of the specified thread.
/// </summary>
/// <param name="thread">The thread.</param>
public ulong GetThreadEnvironmentBlockAddress(Thread thread)
{
using (ThreadSwitcher switcher = new ThreadSwitcher(StateCache, thread))
{
return SystemObjects.GetCurrentThreadTeb();
}
}
/// <summary>
/// Gets the thread context of the specified thread.
/// </summary>
/// <param name="thread">The thread.</param>
public ThreadContext GetThreadContext(Thread thread)
{
using (ThreadSwitcher switcher = new ThreadSwitcher(StateCache, thread))
using (MarshalArrayReader<ThreadContext> threadContextBuffer = WindowsThreadContext.CreateArrayMarshaler(thread.Process, 1))
{
Advanced.GetThreadContext(threadContextBuffer.Pointer, (uint)(threadContextBuffer.Count * threadContextBuffer.Size));
return threadContextBuffer.Elements.FirstOrDefault();
}
}
/// <summary>
/// Gets the stack trace of the specified thread.
/// </summary>
/// <param name="thread">The thread.</param>
public StackTrace GetThreadStackTrace(Thread thread)
{
return GetStackTraceFromContext(thread, IntPtr.Zero, 0);
}
/// <summary>
/// Gets the stack trace from the specified context.
/// </summary>
/// <param name="process">The process.</param>
/// <param name="contextAddress">The context address.</param>
/// <param name="contextSize">Size of the context. If 0 is specified, context size will be automatically calculated.</param>
public StackTrace GetStackTraceFromContext(Process process, ulong contextAddress, uint contextSize = 0)
{
if (contextSize == 0)
{
contextSize = (uint)WindowsThreadContext.GetContextSize(process);
}
Thread thread = new Thread(uint.MaxValue, 0, Process.Current);
IntPtr buffer = Marshal.AllocHGlobal((int)contextSize);
try
{
uint read;
DataSpaces.ReadVirtual(contextAddress, buffer, contextSize, out read);
return GetStackTraceFromContext(thread, buffer, contextSize);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
#if false
/// <summary>
/// An application-defined callback function used with the StackWalkEx function. It is called when StackWalk64 needs to read memory from the address space of the process.
/// </summary>
/// <param name="hProcess">A handle to the process for which the stack trace is generated.</param>
/// <param name="lpBaseAddress">The base address of the memory to be read.</param>
/// <param name="lpBuffer">A pointer to a buffer that receives the memory to be read.</param>
/// <param name="nSize">The size of the memory to be read, in bytes.</param>
/// <param name="lpNumberOfBytesRead">A pointer to a variable that receives the number of bytes actually read.</param>
private static unsafe bool ReadMemory(IntPtr hProcess, ulong lpBaseAddress, IntPtr lpBuffer, uint nSize, out uint lpNumberOfBytesRead)
{
try
{
Process process = Process.All.Where(p => (IntPtr)p.SystemId == hProcess).First();
MemoryBuffer memoryBuffer = Debugger.ReadMemory(process, lpBaseAddress, nSize);
if (memoryBuffer.BytePointer != null)
{
MemoryBuffer.MemCpy(lpBuffer.ToPointer(), memoryBuffer.BytePointer, Math.Min((uint)memoryBuffer.BytePointerLength, nSize));
lpNumberOfBytesRead = Math.Min((uint)memoryBuffer.BytePointerLength, nSize);
return true;
}
else
{
Marshal.Copy(memoryBuffer.Bytes, 0, lpBuffer, Math.Min(memoryBuffer.Bytes.Length, (int)nSize));
lpNumberOfBytesRead = Math.Min((uint)memoryBuffer.Bytes.Length, nSize);
return true;
}
}
catch (Exception)
{
lpNumberOfBytesRead = 0;
return false;
}
}
/// <summary>
/// An application-defined callback function used with the StackWalkEx function. It provides access to the run-time function table for the process.
/// </summary>
/// <param name="hProcess">A handle to the process for which the stack trace is generated.</param>
/// <param name="AddrBase">The address of the instruction to be located.</param>
/// <returns>The function returns a pointer to the run-time function table. On an x86 computer, this is a pointer to an FPO_DATA structure. On an Alpha computer, this is a pointer to an IMAGE_FUNCTION_ENTRY structure.</returns>
private static IntPtr GetFunctionTableAccess(IntPtr hProcess, ulong AddrBase)
{
return SymFunctionTableAccess64AccessRoutines(hProcess, AddrBase, ReadMemory, GetModuleBaseAddress);
}
/// <summary>
/// An application-defined callback function used with the StackWalkEx function. It is called when StackWalkEx needs a module base address for a given virtual address.
/// </summary>
/// <param name="hProcess">A handle to the process for which the stack trace is generated.</param>
/// <param name="Address">An address within the module image to be located.</param>
/// <returns>The function returns the base address of the module.</returns>
private static ulong GetModuleBaseAddress(IntPtr hProcess, ulong Address)
{
Process process = Process.All.Where(p => (IntPtr)p.SystemId == hProcess).First();
var modules = process.Modules;
ulong bestMatch = 0;
ulong bestDistance = ulong.MaxValue;
foreach (var module in modules)
{
if (module.Address < Address)
{
ulong distance = Address - module.Address;
if (distance < bestDistance)
{
bestDistance = distance;
bestMatch = module.Address;
}
}
}
return bestMatch;
}
/// <summary>
/// Reads the stack trace from context using StackWalkEx.
/// </summary>
/// <param name="thread">The thread.</param>
/// <param name="contextAddress">The context address.</param>
private StackTrace ReadStackTraceFromContext(Thread thread, IntPtr contextAddress)
{
List<_DEBUG_STACK_FRAME_EX> frames = new List<_DEBUG_STACK_FRAME_EX>();
List<ThreadContext> contexts = new List<ThreadContext>();
STACKFRAME_EX stackFrame = new STACKFRAME_EX();
while (true)
{
if (!StackWalkEx(thread.Process.ActualProcessorType, (IntPtr)thread.Process.SystemId, (IntPtr)thread.SystemId, ref stackFrame, contextAddress, ReadMemory, GetFunctionTableAccess, GetModuleBaseAddress, null, 0))
break;
frames.Add(new _DEBUG_STACK_FRAME_EX()
{
FrameNumber = (uint)frames.Count,
FrameOffset = stackFrame.AddrFrame.Offset,
FuncTableEntry = (ulong)stackFrame.FuncTableEntry.ToInt64(),
InlineFrameContext = stackFrame.InlineFrameContext,
InstructionOffset = stackFrame.AddrPC.Offset,
Params = null,
Reserved = null,
Reserved1 = 0,
ReturnOffset = stackFrame.AddrReturn.Offset,
StackOffset = stackFrame.AddrStack.Offset,
Virtual = stackFrame.Virtual,
});
contexts.Add(ThreadContext.PtrToStructure(thread.Process, contextAddress));
}
return new StackTrace(thread, frames.ToArray(), contexts.ToArray());
}
#endif
/// <summary>
/// Gets the stack trace from the specified context.
/// </summary>
/// <param name="thread">The thread.</param>
/// <param name="contextAddress">The context address.</param>
/// <param name="contextSize">Size of the context.</param>
/// <returns></returns>
private StackTrace GetStackTraceFromContext(Thread thread, IntPtr contextAddress, uint contextSize)
{
#if false
if (thread.Process.DumpFileMemoryReader != null)
{
if (contextAddress == IntPtr.Zero)
{
using (ThreadSwitcher switcher = new ThreadSwitcher(StateCache, thread))
using (MarshalArrayReader<ThreadContext> threadContextBuffer = ThreadContext.CreateArrayMarshaler(thread.Process, 1))
{
Advanced.GetThreadContext(threadContextBuffer.Pointer, (uint)(threadContextBuffer.Count * threadContextBuffer.Size));
return ReadStackTraceFromContext(thread, threadContextBuffer.Pointer);
}
}
else
{
return ReadStackTraceFromContext(thread, contextAddress);
}
}
#endif
const int MaxCallStack = 10240;
using (ThreadSwitcher switcher = new ThreadSwitcher(StateCache, thread))
using (MarshalArrayReader<_DEBUG_STACK_FRAME_EX> frameBuffer = new RegularMarshalArrayReader<_DEBUG_STACK_FRAME_EX>(MaxCallStack))
using (MarshalArrayReader<ThreadContext> threadContextBuffer = WindowsThreadContext.CreateArrayMarshaler(thread.Process, MaxCallStack))
{
uint framesCount;
Control.GetContextStackTraceEx(contextAddress, contextSize, frameBuffer.Pointer, (uint)frameBuffer.Count, threadContextBuffer.Pointer, (uint)(threadContextBuffer.Size * threadContextBuffer.Count), (uint)threadContextBuffer.Size, out framesCount);
_DEBUG_STACK_FRAME_EX[] frames = frameBuffer.Elements.Take((int)framesCount).ToArray();
ThreadContext[] frameContexts = threadContextBuffer.Elements.Take((int)framesCount).ToArray();
StackTrace stackTrace = new StackTrace(thread);
stackTrace.Frames = new StackFrame[frames.Length];
for (int i = 0; i < frames.Length; i++)
{
stackTrace.Frames[i] = new StackFrame(stackTrace, frameContexts[i])
{
Virtual = frames[i].Virtual != 0,
FrameNumber = frames[i].FrameNumber,
FrameOffset = frames[i].FrameOffset,
InstructionOffset = frames[i].InstructionOffset,
ReturnOffset = frames[i].ReturnOffset,
StackOffset = frames[i].StackOffset,
};
frameContexts[i].Registers = new RegisterAccess(stackTrace.Frames[i], this);
}
return stackTrace;
}
}
/// <summary>
/// Gets the system identifier of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public uint GetProcessSystemId(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
return SystemObjects.GetCurrentProcessSystemId();
}
}
/// <summary>
/// Gets the up time of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public uint GetProcessUpTime(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
return SystemObjects.GetCurrentProcessUpTime();
}
}
/// <summary>
/// Gets the process environment block address of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public ulong GetProcessEnvironmentBlockAddress(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
return SystemObjects.GetCurrentProcessPeb();
}
}
/// <summary>
/// Gets the executable name of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public string GetProcessExecutableName(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
return SystemObjects.GetCurrentProcessExecutableName();
}
}
/// <summary>
/// Gets the dump file name of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public string GetProcessDumpFileName(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
string[] dumps = Client.GetDumpFiles();
if (dumps.Length > 1)
{
throw new Exception("Unexpected number of dump files");
}
if (dumps.Length == 1)
{
return dumps[0];
}
return "";
}
}
/// <summary>
/// Gets the architecture type of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public ArchitectureType GetProcessArchitectureType(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
ImageFileMachine actual = (ImageFileMachine)Control.GetActualProcessorType();
ImageFileMachine effective = (ImageFileMachine)Control.GetEffectiveProcessorType();
switch (actual)
{
case ImageFileMachine.ARM:
return ArchitectureType.Arm;
case ImageFileMachine.I386:
return ArchitectureType.X86;
case ImageFileMachine.AMD64:
return effective == ImageFileMachine.I386 ? ArchitectureType.X86OverAmd64 : ArchitectureType.Amd64;
default:
return ArchitectureType.Unknown;
}
}
}
/// <summary>
/// Gets all threads of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public Thread[] GetProcessThreads(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
uint threadCount = SystemObjects.GetNumberThreads();
Thread[] threads = new Thread[threadCount];
uint[] threadIds = new uint[threadCount];
uint[] threadSytemIds = new uint[threadCount];
unsafe
{
fixed (uint* ids = &threadIds[0])
fixed (uint* systemIds = &threadSytemIds[0])
{
SystemObjects.GetThreadIdsByIndex(0, threadCount, out *ids, out *systemIds);
}
}
for (uint i = 0; i < threadCount; i++)
{
threads[i] = new Thread(threadIds[i], threadSytemIds[i], process);
}
return threads;
}
}
/// <summary>
/// Gets all modules of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public Module[] GetProcessModules(Process process)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
uint loaded, unloaded;
Symbols.GetNumberModules(out loaded, out unloaded);
Module[] modules = new Module[loaded + unloaded];
for (int i = 0; i < modules.Length; i++)
{
ulong moduleId = Symbols.GetModuleByIndex((uint)i);
modules[i] = process.ModulesById[moduleId];
}
return modules;
}
}
/// <summary>
/// Gets the current process.
/// </summary>
public Process GetCurrentProcess()
{
return StateCache.CurrentProcess;
}
/// <summary>
/// Sets the current process.
/// </summary>
/// <param name="process">The process.</param>
public void SetCurrentProcess(Process process)
{
StateCache.CurrentProcess = process;
}
/// <summary>
/// Gets all processes currently being debugged.
/// </summary>
public Process[] GetAllProcesses()
{
uint processCount = SystemObjects.GetNumberProcesses();
Process[] processes = new Process[processCount];
uint[] processIds = new uint[processCount];
uint[] processSytemIds = new uint[processCount];
unsafe
{
fixed (uint* ids = &processIds[0])
fixed (uint* systemIds = &processSytemIds[0])
{
SystemObjects.GetProcessIdsByIndex(0, processCount, out *ids, out *systemIds);
}
}
for (uint i = 0; i < processCount; i++)
{
processes[i] = GlobalCache.Processes[processIds[i]];
processes[i].systemId.Value = processSytemIds[i];
}
return processes;
}
/// <summary>
/// Gets the current thread of the specified process.
/// </summary>
/// <param name="process">The process.</param>
public Thread GetProcessCurrentThread(Process process)
{
return StateCache.CurrentThread[process];
}
/// <summary>
/// Gets the address of the module loaded into specified process.
/// </summary>
/// <param name="process">The process.</param>
/// <param name="moduleName">Name of the module.</param>
public ulong GetModuleAddress(Process process, string moduleName)
{
using (ProcessSwitcher switcher = new ProcessSwitcher(StateCache, process))
{
uint index;
ulong moduleAddress;
Symbols.GetModuleByModuleName2Wide(moduleName, 0, 0, out index, out moduleAddress);
return moduleAddress;
}
}