-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathAD7DebugSession.cs
3867 lines (3362 loc) · 171 KB
/
AD7DebugSession.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DebugEngineHost;
using Microsoft.DebugEngineHost.VSCode;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Debugger.Interop.DAP;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol;
using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages;
using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenDebug;
using OpenDebug.CustomProtocolObjects;
using OpenDebugAD7.AD7Impl;
using ProtocolMessages = Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages;
namespace OpenDebugAD7
{
internal sealed class AD7DebugSession : DebugAdapterBase, IDebugPortNotify2, IDebugEventCallback2
{
// This is a general purpose lock. Don't hold it across long operations.
private readonly object m_lock = new object();
private IDebugProcess2 m_process;
private string m_processName;
private int m_processId = Constants.InvalidProcessId;
private IDebugEngineLaunch2 m_engineLaunch;
private IDebugEngine2 m_engine;
private EngineConfiguration m_engineConfiguration;
private AD7Port m_port;
private ClientId m_clientId;
private DebugSettingsCallback m_settingsCallback;
private readonly DebugEventLogger m_logger;
private readonly Dictionary<string, Dictionary<int, IDebugPendingBreakpoint2>> m_breakpoints;
private readonly ConcurrentDictionary<int, IDebugCodeContext2> m_gotoCodeContexts = new ConcurrentDictionary<int, IDebugCodeContext2>();
private int m_nextContextId = 1;
private Dictionary<string, IDebugPendingBreakpoint2> m_functionBreakpoints;
private Dictionary<ulong, IDebugPendingBreakpoint2> m_instructionBreakpoints;
private Dictionary<string, IDebugPendingBreakpoint2> m_dataBreakpoints;
private List<string> m_exceptionBreakpoints;
private readonly HandleCollection<IDebugStackFrame2> m_frameHandles;
private IDebugProgram2 m_program;
private readonly Dictionary<int, IDebugThread2> m_threads = new Dictionary<int, IDebugThread2>();
private ManualResetEvent m_disconnectedOrTerminated;
private int m_firstStoppingEvent;
private uint m_breakCounter = 0;
private bool m_isAttach;
private bool m_isStopped = false;
private bool m_isStepping = false;
private readonly TaskCompletionSource<object> m_configurationDoneTCS = new TaskCompletionSource<object>();
private readonly SessionConfiguration m_sessionConfig = new SessionConfiguration();
private PathConverter m_pathConverter = new PathConverter();
private VariableManager m_variableManager;
private static Guid s_guidFilterAllLocalsPlusArgs = new Guid("939729a8-4cb0-4647-9831-7ff465240d5f");
private static Guid s_guidFilterRegisters = new Guid("223ae797-bd09-4f28-8241-2763bdc5f713");
private int m_nextModuleHandle = 1;
private readonly Dictionary<IDebugModule2, int> m_moduleMap = new Dictionary<IDebugModule2, int>();
private object RegisterDebugModule(IDebugModule2 debugModule)
{
Debug.Assert(!m_moduleMap.ContainsKey(debugModule));
lock (m_moduleMap)
{
int moduleHandle = m_nextModuleHandle;
m_moduleMap[debugModule] = moduleHandle;
m_nextModuleHandle++;
return moduleHandle;
}
}
private int? ReleaseDebugModule(IDebugModule2 debugModule)
{
lock (m_moduleMap)
{
if (m_moduleMap.TryGetValue(debugModule, out int moduleId))
{
m_moduleMap.Remove(debugModule);
return moduleId;
} else {
Debug.Fail("Trying to unload a module that has not been registered.");
return null;
}
}
}
#region Constructor
public AD7DebugSession(Stream debugAdapterStdIn, Stream debugAdapterStdOut, List<LoggingCategory> loggingCategories)
{
// This initializes this.Protocol with the streams
base.InitializeProtocolClient(debugAdapterStdIn, debugAdapterStdOut);
Debug.Assert(Protocol != null, "InitializeProtocolClient should have initialized this.Protocol");
RegisterAD7EventCallbacks();
m_logger = new DebugEventLogger(Protocol.SendEvent, loggingCategories);
// Register message logger
Protocol.LogMessage += m_logger.TraceLogger_EventHandler;
m_frameHandles = new HandleCollection<IDebugStackFrame2>();
m_breakpoints = new Dictionary<string, Dictionary<int, IDebugPendingBreakpoint2>>();
m_functionBreakpoints = new Dictionary<string, IDebugPendingBreakpoint2>();
m_instructionBreakpoints = new Dictionary<ulong, IDebugPendingBreakpoint2>();
m_dataBreakpoints = new Dictionary<string, IDebugPendingBreakpoint2>();
m_exceptionBreakpoints = new List<string>();
m_variableManager = new VariableManager();
}
#endregion
#region Utility
private void SendTelemetryEvent(string eventName, KeyValuePair<string, object>[] eventProperties)
{
Dictionary<string, object> propertiesDictionary = null;
if (eventProperties != null)
{
propertiesDictionary = new Dictionary<string, object>();
foreach (var pair in eventProperties)
{
propertiesDictionary[pair.Key] = pair.Value;
}
}
m_logger.Write(LoggingCategory.Telemetry, eventName, propertiesDictionary);
}
private static string GetFrameworkVersionAttributeValue()
{
var attribute = typeof(object).Assembly.GetCustomAttribute(typeof(System.Reflection.AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute;
if (attribute == null)
return string.Empty;
return attribute.Version;
}
private ProtocolException CreateProtocolExceptionAndLogTelemetry(string telemetryEventName, int error, string message)
{
DebuggerTelemetry.ReportError(telemetryEventName, error);
return new ProtocolException(message, new Message(error, message));
}
private bool ValidateProgramPath(ref string program, string miMode)
{
// Make sure the slashes go in the correct direction
char directorySeparatorChar = Path.DirectorySeparatorChar;
char wrongSlashChar = directorySeparatorChar == '\\' ? '/' : '\\';
if (program.Contains(wrongSlashChar, StringComparison.Ordinal))
{
program = program.Replace(wrongSlashChar, directorySeparatorChar);
}
program = m_pathConverter.ConvertLaunchPathForVsCode(program);
if (!File.Exists(program))
{
// On macOS, check to see if we are trying to debug an app bundle (.app).
// 'app bundles' contain various resources and executables in a folder.
// LLDB understands how to target these bundles.
if (Utilities.IsOSX() && program.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && miMode?.Equals("lldb", StringComparison.OrdinalIgnoreCase) == true)
{
return Directory.Exists(program);
}
// On Windows, check if we are just missing a '.exe' from the file name. This way we can use the same
// launch.json on all platforms.
if (Utilities.IsWindows())
{
if (!program.EndsWith(".", StringComparison.OrdinalIgnoreCase) && !program.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
string programWithExe = program + ".exe";
if (File.Exists(programWithExe))
{
program = programWithExe;
return true;
}
}
}
return false;
}
return true;
}
private void SetCommonDebugSettings(Dictionary<string, JToken> args)
{
// Save the Just My Code setting. We will set it once the engine is created.
m_sessionConfig.JustMyCode = args.GetValueAsBool("justMyCode").GetValueOrDefault(m_sessionConfig.JustMyCode);
m_sessionConfig.RequireExactSource = args.GetValueAsBool("requireExactSource").GetValueOrDefault(m_sessionConfig.RequireExactSource);
m_sessionConfig.EnableStepFiltering = args.GetValueAsBool("enableStepFiltering").GetValueOrDefault(m_sessionConfig.EnableStepFiltering);
JObject logging = args.GetValueAsObject("logging");
if (logging != null)
{
HostLogger.Reset();
m_logger.SetLoggingConfiguration(LoggingCategory.Exception, logging.GetValueAsBool("exceptions").GetValueOrDefault(true));
m_logger.SetLoggingConfiguration(LoggingCategory.Module, logging.GetValueAsBool("moduleLoad").GetValueOrDefault(true));
m_logger.SetLoggingConfiguration(LoggingCategory.StdOut, logging.GetValueAsBool("programOutput").GetValueOrDefault(true));
m_logger.SetLoggingConfiguration(LoggingCategory.StdErr, logging.GetValueAsBool("programOutput").GetValueOrDefault(true));
JToken engineLogging = logging.GetValue("engineLogging", StringComparison.OrdinalIgnoreCase);
if (engineLogging != null)
{
if (engineLogging.Type == JTokenType.Boolean)
{
bool engineLoggingBool = engineLogging.Value<bool>();
if (engineLoggingBool)
{
m_logger.SetLoggingConfiguration(LoggingCategory.EngineLogging, true);
HostLogger.EnableHostLogging((message) => m_logger.WriteLine(LoggingCategory.EngineLogging, message), LogLevel.Verbose);
}
}
else if (engineLogging.Type == JTokenType.String)
{
string engineLoggingString = engineLogging.Value<string>();
if (Enum.TryParse(engineLoggingString, ignoreCase: true, out LogLevel level))
{
m_logger.SetLoggingConfiguration(LoggingCategory.EngineLogging, true);
HostLogger.EnableHostLogging((message) => m_logger.WriteLine(LoggingCategory.EngineLogging, message), level);
}
}
else
{
m_logger.WriteLine(LoggingCategory.EngineLogging, string.Format(CultureInfo.CurrentCulture, AD7Resources.Warning_EngineLoggingParse, engineLogging.ToString()));
}
}
bool? trace = logging.GetValueAsBool("trace");
bool? traceResponse = logging.GetValueAsBool("traceResponse");
if (trace.HasValue || traceResponse.HasValue)
{
m_logger.SetLoggingConfiguration(LoggingCategory.AdapterTrace, (trace.GetValueOrDefault(false)) || (traceResponse.GetValueOrDefault(false)));
}
if (traceResponse.HasValue)
{
m_logger.SetLoggingConfiguration(LoggingCategory.AdapterResponse, traceResponse.Value);
}
JToken natvisDiagnostics = logging.GetValue("natvisDiagnostics", StringComparison.OrdinalIgnoreCase);
if (natvisDiagnostics != null)
{
if (natvisDiagnostics.Type == JTokenType.Boolean)
{
bool natvisDiagnosticsBool = natvisDiagnostics.Value<bool>();
if (natvisDiagnosticsBool)
{
m_logger.SetLoggingConfiguration(LoggingCategory.NatvisDiagnostics, true);
HostLogger.EnableNatvisDiagnostics((message) => m_logger.WriteLine(LoggingCategory.NatvisDiagnostics, message), LogLevel.Verbose);
}
}
else if (natvisDiagnostics.Type == JTokenType.String)
{
string natvisDiagnosticsString = natvisDiagnostics.Value<string>();
if (Enum.TryParse(natvisDiagnosticsString, ignoreCase: true, out LogLevel level))
{
m_logger.SetLoggingConfiguration(LoggingCategory.NatvisDiagnostics, true);
HostLogger.EnableNatvisDiagnostics((message) => m_logger.WriteLine(LoggingCategory.NatvisDiagnostics, string.Concat("[Natvis] ", message)), level);
}
}
else
{
m_logger.WriteLine(LoggingCategory.EngineLogging, string.Format(CultureInfo.CurrentCulture, AD7Resources.Warning_NatvisLoggingParse, natvisDiagnostics.ToString()));
}
}
}
}
private void SetCommonMISettings(Dictionary<string, JToken> args)
{
string miMode = args.GetValueAsString("MIMode");
// If MIMode is not provided, set default to GDB.
if (string.IsNullOrEmpty(miMode))
{
args["MIMode"] = "gdb";
}
else
{
// If lldb and there is no miDebuggerPath, set it.
bool hasMiDebuggerPath = args.ContainsKey("miDebuggerPath") && !string.IsNullOrEmpty(args["miDebuggerPath"].ToString());
if (miMode == "lldb" && !hasMiDebuggerPath)
{
args["miDebuggerPath"] = MILaunchOptions.GetLLDBMIPath();
}
}
}
private ProtocolException VerifyLocalProcessId(string processId, string telemetryEventName, out int pid)
{
ProtocolException protocolException = VerifyProcessId(processId, telemetryEventName, out pid);
if (protocolException != null)
{
return protocolException;
}
try
{
Process.GetProcessById(pid);
}
catch (ArgumentException)
{
return CreateProtocolExceptionAndLogTelemetry(telemetryEventName, 1006, string.Format(CultureInfo.CurrentCulture, "attach: no process with the given id:{0} found", pid));
}
return null;
}
private ProtocolException VerifyProcessId(string processId, string telemetryEventName, out int pid)
{
if (!int.TryParse(processId, out pid))
{
return CreateProtocolExceptionAndLogTelemetry(telemetryEventName, 1005, "attach: unable to parse the process id");
}
if (pid == 0)
{
return CreateProtocolExceptionAndLogTelemetry(telemetryEventName, 1008, "attach: launch.json must be configured. Change 'processId' to the process you want to debug.");
}
return null;
}
private IList<Tracepoint> GetTracepoints(IDebugBreakpointEvent2 debugEvent)
{
IList<Tracepoint> tracepoints = new List<Tracepoint>();
if (debugEvent != null)
{
debugEvent.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 pBoundBreakpoints);
IDebugBoundBreakpoint2[] boundBp = new IDebugBoundBreakpoint2[1];
uint numReturned = 0;
while (pBoundBreakpoints.Next(1, boundBp, ref numReturned) == HRConstants.S_OK && numReturned == 1)
{
if (boundBp[0].GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBreakpoint) == HRConstants.S_OK &&
ppPendingBreakpoint.GetBreakpointRequest(out IDebugBreakpointRequest2 ppBPRequest) == HRConstants.S_OK &&
ppBPRequest is AD7BreakPointRequest ad7BreakpointRequest &&
ad7BreakpointRequest.HasTracepoint)
{
tracepoints.Add(ad7BreakpointRequest.Tracepoint);
}
}
}
return tracepoints;
}
public StoppedEvent.ReasonValue GetStoppedEventReason(IDebugBreakpointEvent2 breakpointEvent)
{
StoppedEvent.ReasonValue reason = StoppedEvent.ReasonValue.Breakpoint;
if (breakpointEvent != null)
{
if (breakpointEvent.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 enumBreakpoints) == HRConstants.S_OK &&
enumBreakpoints.GetCount(out uint bpCount) == HRConstants.S_OK &&
bpCount > 0)
{
bool allInstructionBreakpoints = true;
IDebugBoundBreakpoint2[] boundBp = new IDebugBoundBreakpoint2[1];
uint fetched = 0;
while (enumBreakpoints.Next(1, boundBp, ref fetched) == HRConstants.S_OK)
{
if (boundBp[0].GetPendingBreakpoint(out IDebugPendingBreakpoint2 pendingBreakpoint) == HRConstants.S_OK)
{
if (pendingBreakpoint.GetBreakpointRequest(out IDebugBreakpointRequest2 breakpointRequest) == HRConstants.S_OK)
{
AD7BreakPointRequest request = breakpointRequest as AD7BreakPointRequest;
if (breakpointRequest != null && request.MemoryContext == null)
{
allInstructionBreakpoints = false;
break;
}
}
}
}
if (allInstructionBreakpoints)
{
reason = StoppedEvent.ReasonValue.InstructionBreakpoint;
}
}
}
return reason;
}
private static long FileTimeToPosix(FILETIME ft)
{
long date = ((long)ft.dwHighDateTime << 32) + ft.dwLowDateTime;
// removes the diff between 1970 and 1601
// 100-nanoseconds = milliseconds * 10000
date -= 11644473600000L * 10000;
// converts back from 100-nanoseconds to seconds
return date / 10000000;
}
private ulong ResolveInstructionReference(string memoryReference, int? offset)
{
ulong address;
if (memoryReference.StartsWith("0x", StringComparison.Ordinal))
{
address = Convert.ToUInt64(memoryReference.Substring(2), 16);
}
else
{
address = Convert.ToUInt64(memoryReference, 10);
}
if (offset.HasValue && offset.Value != 0)
{
if (offset < 0)
{
address += (ulong)offset.Value;
}
else
{
address -= (ulong)-offset.Value;
}
}
return address;
}
private int GetMemoryContext(string memoryReference, int? offset, out IDebugMemoryContext2 memoryContext, out ulong address)
{
memoryContext = null;
address = ResolveInstructionReference(memoryReference, offset);
int hr = HRConstants.E_NOTIMPL; // Engine does not support IDebugMemoryBytesDAP
if (m_engine is IDebugMemoryBytesDAP debugMemoryBytesDAPEngine)
{
hr = debugMemoryBytesDAPEngine.CreateMemoryContext(address, out memoryContext);
}
return hr;
}
/// <summary>
/// Given 'expression', it will query the engine for an IDebugProperty2
/// </summary>
/// <param name="eb">Error handler to use in this method.</param>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="frameId">Which frame to use and evaluate the expression on.</param>
/// <param name="isExecInConsole">If the current expression is from a console exec.</param>
/// <param name="flags">Flags used for EvaluateSync</param>
/// <param name="dapEvalFlags">EvaluationFlags used for DAPEvaluateSync</param>
/// <param name="property">The IDebugProperty2 of the 'expression'</param>
/// <exception cref="ProtocolException">In any step of the method that fails, it will throw a protocol execption using the ErrorBuilder.</exception>
private void GetDebugPropertyFromExpression(ErrorBuilder eb, string expression, int frameId, bool isExecInConsole, enum_EVALFLAGS flags, DAPEvalFlags dapEvalFlags, out IDebugProperty2 property)
{
property = null;
IDebugStackFrame2 frame;
bool success;
if (frameId == -1 && isExecInConsole)
{
// If exec in console and no stack frame, evaluate off the top frame.
success = m_frameHandles.TryGetFirst(out frame);
}
else
{
success = m_frameHandles.TryGet(frameId, out frame);
}
if (!success)
{
throw new ProtocolException(AD7Resources.Error_InvalidStackFrameOnEvaluateExpression);
}
IDebugExpressionContext2 expressionContext;
int hr = frame.GetExpressionContext(out expressionContext);
eb.CheckHR(hr);
IDebugExpression2 expressionObject;
string error;
uint errorIndex;
hr = expressionContext.ParseText(expression, enum_PARSEFLAGS.PARSE_EXPRESSION, Constants.ParseRadix, out expressionObject, out error, out errorIndex);
if (!string.IsNullOrEmpty(error))
{
DebuggerTelemetry.ReportError(DebuggerTelemetry.TelemetryEvaluateEventName, 4001, "Error parsing expression");
throw new ProtocolException(error);
}
eb.CheckHR(hr);
eb.CheckOutput(expressionObject);
if (expressionObject is IDebugExpressionDAP expressionDapObject)
{
hr = expressionDapObject.EvaluateSync(flags, dapEvalFlags, Constants.EvaluationTimeout, null, out property);
}
else
{
hr = expressionObject.EvaluateSync(flags, Constants.EvaluationTimeout, null, out property);
}
eb.CheckHR(hr);
eb.CheckOutput(property);
}
private uint GetRadixFromValueForamt(ValueFormat format)
{
uint radix = Constants.EvaluationRadix;
if (format != null)
{
if (format.Hex == true)
{
radix = 16;
}
}
if (m_settingsCallback != null)
{
// MIEngine generally gets the radix from IDebugSettingsCallback110 rather than using the radix passed
m_settingsCallback.Radix = radix;
}
return radix;
}
#endregion
#region AD7EventHandlers helper methods
public void BeforeContinue()
{
m_isStepping = false;
m_isStopped = false;
m_variableManager.Reset();
m_frameHandles.Reset();
m_gotoCodeContexts.Clear();
}
public void Stopped(IDebugThread2 thread)
{
Debug.Assert(m_variableManager.IsEmpty(), "Why do we have variable handles?");
Debug.Assert(m_frameHandles.IsEmpty, "Why do we have frame handles?");
m_isStopped = true;
}
internal void FireStoppedEvent(IDebugThread2 thread, StoppedEvent.ReasonValue reason, string text = null)
{
Stopped(thread);
// Switch to another thread as engines may not expect to be called back on their event thread
ThreadPool.QueueUserWorkItem((o) =>
{
IEnumDebugFrameInfo2 frameInfoEnum;
thread.EnumFrameInfo(enum_FRAMEINFO_FLAGS.FIF_FRAME | enum_FRAMEINFO_FLAGS.FIF_FLAGS, Constants.EvaluationRadix, out frameInfoEnum);
TextPositionTuple textPosition = TextPositionTuple.Nil;
if (frameInfoEnum != null)
{
while (true)
{
FRAMEINFO[] frameInfoArray = new FRAMEINFO[1];
uint cFetched = 0;
frameInfoEnum.Next(1, frameInfoArray, ref cFetched);
if (cFetched != 1)
{
break;
}
if (AD7Utils.IsAnnotatedFrame(ref frameInfoArray[0]))
{
continue;
}
textPosition = TextPositionTuple.GetTextPositionOfFrame(m_pathConverter, frameInfoArray[0].m_pFrame) ?? TextPositionTuple.Nil;
break;
}
}
lock (m_lock)
{
m_breakCounter++;
}
Protocol.SendEvent(new OpenDebugStoppedEvent()
{
Reason = reason,
Text = text,
ThreadId = thread.Id(),
// Additional Breakpoint Information for Testing/Logging
Source = textPosition.Source,
Line = textPosition.Line,
Column = textPosition.Column,
});
});
if (Interlocked.Exchange(ref m_firstStoppingEvent, 1) == 0)
{
m_logger.WriteLine(LoggingCategory.DebuggerStatus, AD7Resources.DebugConsoleStartMessage);
}
}
private void SendDebugCompletedTelemetry()
{
Dictionary<string, object> properties = new Dictionary<string, object>();
lock (m_lock)
{
properties.Add(DebuggerTelemetry.TelemetryBreakCounter, m_breakCounter);
}
DebuggerTelemetry.ReportEvent(DebuggerTelemetry.TelemetryDebugCompletedEventName, properties);
}
private static IEnumerable<IDebugBoundBreakpoint2> GetBoundBreakpoints(IDebugBreakpointBoundEvent2 breakpointBoundEvent)
{
int hr;
IEnumDebugBoundBreakpoints2 boundBreakpointsEnum;
hr = breakpointBoundEvent.EnumBoundBreakpoints(out boundBreakpointsEnum);
if (hr != HRConstants.S_OK)
{
return Enumerable.Empty<IDebugBoundBreakpoint2>();
}
uint bufferSize;
hr = boundBreakpointsEnum.GetCount(out bufferSize);
if (hr != HRConstants.S_OK)
{
return Enumerable.Empty<IDebugBoundBreakpoint2>();
}
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[bufferSize];
uint fetched = 0;
hr = boundBreakpointsEnum.Next(bufferSize, boundBreakpoints, ref fetched);
if (hr != HRConstants.S_OK || fetched != bufferSize)
{
return Enumerable.Empty<IDebugBoundBreakpoint2>();
}
return boundBreakpoints;
}
private int? GetBoundBreakpointLineNumber(IDebugBoundBreakpoint2 boundBreakpoint)
{
int hr;
IDebugBreakpointResolution2 breakpointResolution;
hr = boundBreakpoint.GetBreakpointResolution(out breakpointResolution);
if (hr != HRConstants.S_OK)
{
return null;
}
BP_RESOLUTION_INFO[] resolutionInfo = new BP_RESOLUTION_INFO[1];
hr = breakpointResolution.GetResolutionInfo(enum_BPRESI_FIELDS.BPRESI_BPRESLOCATION, resolutionInfo);
if (hr != HRConstants.S_OK)
{
return null;
}
BP_RESOLUTION_LOCATION location = resolutionInfo[0].bpResLocation;
enum_BP_TYPE bpType = (enum_BP_TYPE)location.bpType;
if (bpType != enum_BP_TYPE.BPT_CODE || location.unionmember1 == IntPtr.Zero)
{
return null;
}
IDebugCodeContext2 codeContext;
try
{
codeContext = HostMarshal.GetDebugCodeContextForIntPtr(location.unionmember1);
HostMarshal.ReleaseCodeContextId(location.unionmember1);
location.unionmember1 = IntPtr.Zero;
}
catch (ArgumentException)
{
return null;
}
IDebugDocumentContext2 docContext;
hr = codeContext.GetDocumentContext(out docContext);
if (hr != HRConstants.S_OK)
{
return null;
}
// VSTS 237376: Shared library compiled without symbols will still bind a bp, but not have a docContext
if (null == docContext)
{
return null;
}
TEXT_POSITION[] begin = new TEXT_POSITION[1];
TEXT_POSITION[] end = new TEXT_POSITION[1];
hr = docContext.GetStatementRange(begin, end);
if (hr != HRConstants.S_OK)
{
return null;
}
return m_pathConverter.ConvertDebuggerLineToClient((int)begin[0].dwLine);
}
private enum MessagePrefix
{
None,
Warning,
Error
};
private class CurrentLaunchState
{
public Tuple<MessagePrefix, string> CurrentError { get; set; }
}
private CurrentLaunchState m_currentLaunchState;
private void SendMessageEvent(MessagePrefix prefix, string text)
{
string prefixString = string.Empty;
LoggingCategory category = LoggingCategory.DebuggerStatus;
switch (prefix)
{
case MessagePrefix.Warning:
prefixString = AD7Resources.Prefix_Warning;
category = LoggingCategory.DebuggerError;
break;
case MessagePrefix.Error:
prefixString = AD7Resources.Prefix_Error;
category = LoggingCategory.DebuggerError;
break;
}
m_logger.WriteLine(category, prefixString + text);
}
private VariablesResponse VariablesFromFrame(VariableScope vref, uint radix)
{
var frame = vref.StackFrame;
var category = vref.Category;
var response = new VariablesResponse();
Guid filter = Guid.Empty;
switch (category)
{
case VariableCategory.Locals:
filter = s_guidFilterAllLocalsPlusArgs;
break;
case VariableCategory.Registers:
filter = s_guidFilterRegisters;
break;
}
uint n;
IEnumDebugPropertyInfo2 varEnum;
if (frame.EnumProperties(GetDefaultPropertyInfoFlags(), radix, ref filter, 0, out n, out varEnum) == HRConstants.S_OK)
{
var props = new DEBUG_PROPERTY_INFO[1];
uint nProps;
var variablesDictionary = new Dictionary<string, Variable>();
while (varEnum.Next(1, props, out nProps) == HRConstants.S_OK)
{
Variable variable = m_variableManager.CreateVariable(props[0].pProperty, GetDefaultPropertyInfoFlags());
int uniqueCounter = 2;
string variableName = variable.Name;
while (variablesDictionary.ContainsKey(variableName))
{
variableName = String.Format(CultureInfo.InvariantCulture, VariableManager.VariableNameFormat, variable.Name, uniqueCounter++);
}
variable.Name = variableName;
variablesDictionary[variableName] = variable;
m_variableManager.AddVariableProperty((frame, variableName), props[0].pProperty);
}
response.Variables.AddRange(variablesDictionary.Values);
}
return response;
}
public enum_DEBUGPROP_INFO_FLAGS GetDefaultPropertyInfoFlags()
{
enum_DEBUGPROP_INFO_FLAGS flags =
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD |
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP |
enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME |
(enum_DEBUGPROP_INFO_FLAGS)enum_DEBUGPROP_INFO_FLAGS110.DEBUGPROP110_INFO_FORCE_REAL_FUNCEVAL;
if (m_sessionConfig.JustMyCode)
{
flags |= (enum_DEBUGPROP_INFO_FLAGS)enum_DEBUGPROP_INFO_FLAGS110.DEBUGPROP110_INFO_NO_NONPUBLIC_MEMBERS;
}
return flags;
}
private void SetExceptionCategory(ExceptionSettings.CategoryConfiguration category, enum_EXCEPTION_STATE state)
{
var exceptionInfo = new EXCEPTION_INFO[1];
exceptionInfo[0].dwState = state;
exceptionInfo[0].guidType = category.Id;
exceptionInfo[0].bstrExceptionName = category.Name;
m_engine.SetException(exceptionInfo);
}
private void SetCategoryGuidExceptions(Guid categoryId, enum_EXCEPTION_STATE state)
{
ExceptionSettings.CategoryConfiguration category = m_engineConfiguration.ExceptionSettings.Categories.FirstOrDefault(x => x.Id == categoryId);
if (category != null)
{
var exceptionInfo = new EXCEPTION_INFO[1];
exceptionInfo[0].dwState = state;
exceptionInfo[0].guidType = categoryId;
exceptionInfo[0].bstrExceptionName = category.Name;
m_engine.SetException(exceptionInfo);
}
else
{
Debug.Fail(categoryId + " is a referencing a non-existant category. This should have been caught in ExceptionSettings.ValidateExceptionFilters.");
}
}
private void StepInternal(int threadId, enum_STEPKIND stepKind, SteppingGranularity granularity, string errorMessage)
{
// If we are already running ignore additional step requests
if (!m_isStopped)
return;
IDebugThread2 thread = null;
lock (m_threads)
{
if (!m_threads.TryGetValue(threadId, out thread))
{
throw new AD7Exception(errorMessage);
}
}
ErrorBuilder builder = new ErrorBuilder(() => errorMessage);
m_isStepping = true;
enum_STEPUNIT stepUnit = enum_STEPUNIT.STEP_STATEMENT;
switch (granularity)
{
case SteppingGranularity.Statement:
default:
break;
case SteppingGranularity.Line:
stepUnit = enum_STEPUNIT.STEP_LINE;
break;
case SteppingGranularity.Instruction:
stepUnit = enum_STEPUNIT.STEP_INSTRUCTION;
break;
}
try
{
builder.CheckHR(m_program.Step(thread, stepKind, stepUnit));
}
catch (AD7Exception)
{
m_isStopped = true;
throw;
}
// The program should now be stepping, so it is safe to discard the
// cached program state.
BeforeContinue();
}
private enum ClientId
{
Unknown,
VisualStudio,
VsCode,
LiveshareServerHost
};
private bool IsClientVS
{
get
{
return m_clientId == ClientId.VisualStudio || m_clientId == ClientId.LiveshareServerHost;
}
}
#endregion
#region DebugAdapterBase
protected override void HandleInitializeRequestAsync(IRequestResponder<InitializeArguments, InitializeResponse> responder)
{
InitializeArguments arguments = responder.Arguments;
m_engineConfiguration = EngineConfiguration.TryGet(arguments.AdapterID);
m_engine = (IDebugEngine2)m_engineConfiguration.LoadEngine();
TypeInfo engineType = m_engine.GetType().GetTypeInfo();
HostTelemetry.InitializeTelemetry(SendTelemetryEvent, engineType, m_engineConfiguration.AdapterId);
DebuggerTelemetry.InitializeTelemetry(Protocol.SendEvent, engineType, typeof(Host).GetTypeInfo(), m_engineConfiguration.AdapterId);
HostOutputWindow.InitializeLaunchErrorCallback((error) => m_logger.WriteLine(LoggingCategory.DebuggerError, error));
m_engineLaunch = (IDebugEngineLaunch2)m_engine;
m_engine.SetRegistryRoot(m_engineConfiguration.AdapterId);
m_port = new AD7Port(this);
m_disconnectedOrTerminated = new ManualResetEvent(false);
m_firstStoppingEvent = 0;
if (m_engine is IDebugEngine110 engine110)
{
// MIEngine generally gets the radix from IDebugSettingsCallback110 rather than using the radix passed to individual
// APIs. To support this mechanism outside of VS, provide a fake settings callback here that we can use to control
// the radix.
m_settingsCallback = new DebugSettingsCallback();
engine110.SetMainThreadSettingsCallback110(m_settingsCallback);
}
m_pathConverter.ClientLinesStartAt1 = arguments.LinesStartAt1.GetValueOrDefault(true);
// Default is that they are URIs
m_pathConverter.ClientPathsAreURI = !(arguments.PathFormat.GetValueOrDefault(InitializeArguments.PathFormatValue.Unknown) == InitializeArguments.PathFormatValue.Path);
string clientId = responder.Arguments.ClientID;
if (clientId == "visualstudio")
{
m_clientId = ClientId.VisualStudio;
}
else if (clientId == "vscode")
{
m_clientId = ClientId.VsCode;
}
else if (clientId == "liveshare-server-host")
{
m_clientId = ClientId.LiveshareServerHost;
}
else
{
m_clientId = ClientId.Unknown;
}
// If the UI supports RunInTerminal, then register the callback.
// NOTE: Currently we don't support using the RunInTerminal request with VS or Windows Codespaces.
// This is because: (1) they don't support 'Integrated' terminal, and (2) for MIEngine, we don't ship WindowsDebugLauncher.exe.
if (!IsClientVS && arguments.SupportsRunInTerminalRequest.GetValueOrDefault(false))
{
HostRunInTerminal.RegisterRunInTerminalCallback((title, cwd, useExternalConsole, commandArgs, env, success, error) =>
{
RunInTerminalRequest request = new RunInTerminalRequest()
{
Arguments = commandArgs.ToList<string>(),
Kind = useExternalConsole ? RunInTerminalArguments.KindValue.External : RunInTerminalArguments.KindValue.Integrated,
Title = title,
Cwd = cwd,
Env = env
};
Protocol.SendClientRequest(
request,
(args, responseBody) =>
{
// responseBody can be null
success(responseBody?.ProcessId);
},
(args, exception) =>
{
new OutputEvent() { Category = OutputEvent.CategoryValue.Stderr, Output = exception.ToString() };
Protocol.SendEvent(new TerminatedEvent());
error(exception.ToString());
});
});
}
List<ColumnDescriptor> additionalModuleColumns = null;
if (IsClientVS)
{
additionalModuleColumns = new List<ColumnDescriptor>();