-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathMonoDebugSession.cs
1032 lines (866 loc) · 28.9 KB
/
MonoDebugSession.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 Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Linq;
using System.Net;
using Mono.Debugging.Client;
namespace VSCodeDebug
{
public class MonoDebugSession : DebugSession
{
private const string MONO = "mono";
private readonly string[] MONO_EXTENSIONS = new String[] {
".cs", ".csx",
".cake",
".fs", ".fsi", ".ml", ".mli", ".fsx", ".fsscript",
".hx",
".vb"
};
private const int MAX_CHILDREN = 100;
private const int MAX_CONNECTION_ATTEMPTS = 10;
private const int CONNECTION_ATTEMPT_INTERVAL = 500;
private AutoResetEvent _resumeEvent = new AutoResetEvent(false);
private bool _debuggeeExecuting = false;
private readonly object _lock = new object();
private Mono.Debugging.Soft.SoftDebuggerSession _session;
private volatile bool _debuggeeKilled = true;
private ProcessInfo _activeProcess;
private Mono.Debugging.Client.StackFrame _activeFrame;
private long _nextBreakpointId = 0;
private SortedDictionary<long, BreakEvent> _breakpoints;
private List<Catchpoint> _catchpoints;
private DebuggerSessionOptions _debuggerSessionOptions;
private System.Diagnostics.Process _process;
private Handles<ObjectValue[]> _variableHandles;
private Handles<Mono.Debugging.Client.StackFrame> _frameHandles;
private ObjectValue _exception;
private Dictionary<int, Thread> _seenThreads = new Dictionary<int, Thread>();
private bool _attachMode = false;
private bool _terminated = false;
private bool _stderrEOF = true;
private bool _stdoutEOF = true;
private dynamic exceptionOptionsFromDap;
public MonoDebugSession() : base()
{
_variableHandles = new Handles<ObjectValue[]>();
_frameHandles = new Handles<Mono.Debugging.Client.StackFrame>();
_seenThreads = new Dictionary<int, Thread>();
_debuggerSessionOptions = new DebuggerSessionOptions {
EvaluationOptions = EvaluationOptions.DefaultOptions
};
_session = new Mono.Debugging.Soft.SoftDebuggerSession();
_session.Breakpoints = new BreakpointStore();
_breakpoints = new SortedDictionary<long, BreakEvent>();
_catchpoints = new List<Catchpoint>();
DebuggerLoggingService.CustomLogger = new CustomLogger();
_session.ExceptionHandler = ex => {
return true;
};
_session.LogWriter = (isStdErr, text) => {
};
_session.TargetStopped += (sender, e) => {
Stopped();
SendEvent(CreateStoppedEvent("step", e.Thread));
_resumeEvent.Set();
};
_session.TargetHitBreakpoint += (sender, e) => {
Stopped();
SendEvent(CreateStoppedEvent("breakpoint", e.Thread));
_resumeEvent.Set();
};
_session.TargetExceptionThrown += (sender, e) => {
Stopped();
var ex = DebuggerActiveException();
if (ex != null) {
_exception = ex.Instance;
SendEvent(CreateStoppedEvent("exception", e.Thread, ex.Message));
}
_resumeEvent.Set();
};
_session.TargetUnhandledException += (sender, e) => {
Stopped ();
var ex = DebuggerActiveException();
if (ex != null) {
_exception = ex.Instance;
SendEvent(CreateStoppedEvent("exception", e.Thread, ex.Message));
}
_resumeEvent.Set();
};
_session.TargetStarted += (sender, e) => {
_activeFrame = null;
};
_session.TargetReady += (sender, e) => {
SetExceptionBreakpointsFromDap(exceptionOptionsFromDap);
_activeProcess = _session.GetProcesses().SingleOrDefault();
};
_session.TargetExited += (sender, e) => {
DebuggerKill();
_debuggeeKilled = true;
Terminate("target exited");
_resumeEvent.Set();
};
_session.TargetInterrupted += (sender, e) => {
_resumeEvent.Set();
};
_session.TargetEvent += (sender, e) => {
};
_session.TargetThreadStarted += (sender, e) => {
int tid = (int)e.Thread.Id;
lock (_seenThreads) {
_seenThreads[tid] = new Thread(tid, e.Thread.Name);
}
SendEvent(new ThreadEvent("started", tid));
};
_session.TargetThreadStopped += (sender, e) => {
int tid = (int)e.Thread.Id;
lock (_seenThreads) {
_seenThreads.Remove(tid);
}
SendEvent(new ThreadEvent("exited", tid));
};
_session.OutputWriter = (isStdErr, text) => {
SendOutput(isStdErr ? "stderr" : "stdout", text);
};
}
public override void Initialize(Response response, dynamic args)
{
OperatingSystem os = Environment.OSVersion;
if (os.Platform != PlatformID.MacOSX && os.Platform != PlatformID.Unix && os.Platform != PlatformID.Win32NT) {
SendErrorResponse(response, 3000, "Mono Debug is not supported on this platform ({_platform}).", new { _platform = os.Platform.ToString() }, true, true);
return;
}
SendResponse(response, new Capabilities() {
// This debug adapter does not need the configurationDoneRequest.
supportsConfigurationDoneRequest = false,
// This debug adapter does not support function breakpoints.
supportsFunctionBreakpoints = false,
// This debug adapter doesn't support conditional breakpoints.
supportsConditionalBreakpoints = false,
// This debug adapter does not support a side effect free evaluate request for data hovers.
supportsEvaluateForHovers = false,
supportsExceptionFilterOptions = true,
exceptionBreakpointFilters = new dynamic[] {
new { filter = "always", label = "All Exceptions", @default=false, supportsCondition=true, description="Break when an exception is thrown, even if it is caught later.",
conditionDescription = "Comma-separated list of exception types to break on"},
new { filter = "uncaught", label = "Uncaught Exceptions", @default=false, supportsCondition=false, description="Breaks only on exceptions that are not handled."}
}
});
// Mono Debug is ready to accept breakpoints immediately
SendEvent(new InitializedEvent());
}
public override async void Launch(Response response, dynamic args)
{
_attachMode = false;
SetExceptionBreakpoints(args.__exceptionOptions);
// validate argument 'program'
string programPath = getString(args, "program");
if (programPath == null) {
SendErrorResponse(response, 3001, "Property 'program' is missing or empty.", null);
return;
}
programPath = ConvertClientPathToDebugger(programPath);
if (!File.Exists(programPath) && !Directory.Exists(programPath)) {
SendErrorResponse(response, 3002, "Program '{path}' does not exist.", new { path = programPath });
return;
}
// validate argument 'cwd'
var workingDirectory = (string)args.cwd;
if (workingDirectory != null) {
workingDirectory = workingDirectory.Trim();
if (workingDirectory.Length == 0) {
SendErrorResponse(response, 3003, "Property 'cwd' is empty.");
return;
}
workingDirectory = ConvertClientPathToDebugger(workingDirectory);
if (!Directory.Exists(workingDirectory)) {
SendErrorResponse(response, 3004, "Working directory '{path}' does not exist.", new { path = workingDirectory });
return;
}
}
// validate argument 'runtimeExecutable'
var runtimeExecutable = (string)args.runtimeExecutable;
if (runtimeExecutable != null) {
runtimeExecutable = runtimeExecutable.Trim();
if (runtimeExecutable.Length == 0) {
SendErrorResponse(response, 3005, "Property 'runtimeExecutable' is empty.");
return;
}
runtimeExecutable = ConvertClientPathToDebugger(runtimeExecutable);
if (!File.Exists(runtimeExecutable)) {
SendErrorResponse(response, 3006, "Runtime executable '{path}' does not exist.", new { path = runtimeExecutable });
return;
}
}
// validate argument 'env'
Dictionary<string, string> env = new Dictionary<string, string>();
var environmentVariables = args.env;
if (environmentVariables != null) {
foreach (var entry in environmentVariables) {
env.Add((string)entry.Name, (string)entry.Value);
}
}
const string host = "127.0.0.1";
int port = Utilities.FindFreePort(55555);
string mono_path = runtimeExecutable;
if (mono_path == null) {
if (!Utilities.IsOnPath(MONO)) {
SendErrorResponse(response, 3011, "Can't find runtime '{_runtime}' on PATH.", new { _runtime = MONO });
return;
}
mono_path = MONO; // try to find mono through PATH
}
var cmdLine = new List<String>();
bool debug = !getBool(args, "noDebug", false);
if (debug) {
bool passDebugOptionsViaEnvironmentVariable = getBool(args, "passDebugOptionsViaEnvironmentVariable", false);
if (passDebugOptionsViaEnvironmentVariable) {
if (!env.ContainsKey("MONO_ENV_OPTIONS"))
env["MONO_ENV_OPTIONS"] = $" --debug --debugger-agent=transport=dt_socket,server=y,address={host}:{port}";
else
env["MONO_ENV_OPTIONS"] = $" --debug --debugger-agent=transport=dt_socket,server=y,address={host}:{port} " + env["MONO_ENV_OPTIONS"];
}
else {
cmdLine.Add("--debug");
cmdLine.Add($"--debugger-agent=transport=dt_socket,server=y,address={host}:{port}");
}
}
if (env.Count == 0) {
env = null;
}
// add 'runtimeArgs'
if (args.runtimeArgs != null) {
string[] runtimeArguments = args.runtimeArgs.ToObject<string[]>();
if (runtimeArguments != null && runtimeArguments.Length > 0) {
cmdLine.AddRange(runtimeArguments);
}
}
// add 'program'
if (workingDirectory == null) {
// if no working dir given, we use the direct folder of the executable
workingDirectory = Path.GetDirectoryName(programPath);
cmdLine.Add(Path.GetFileName(programPath));
}
else {
// if working dir is given and if the executable is within that folder, we make the program path relative to the working dir
cmdLine.Add(Utilities.MakeRelativePath(workingDirectory, programPath));
}
// add 'args'
if (args.args != null) {
string[] arguments = args.args.ToObject<string[]>();
if (arguments != null && arguments.Length > 0) {
cmdLine.AddRange(arguments);
}
}
// what console?
var console = getString(args, "console", null);
if (console == null) {
// continue to read the deprecated "externalConsole" attribute
bool externalConsole = getBool(args, "externalConsole", false);
if (externalConsole) {
console = "externalTerminal";
}
}
if (console == "externalTerminal" || console == "integratedTerminal") {
cmdLine.Insert(0, mono_path);
var termArgs = new {
kind = console == "integratedTerminal" ? "integrated" : "external",
title = "Node Debug Console",
cwd = workingDirectory,
args = cmdLine.ToArray(),
env
};
var resp = await SendRequest("runInTerminal", termArgs);
if (!resp.success) {
SendErrorResponse(response, 3011, "Cannot launch debug target in terminal ({_error}).", new { _error = resp.message });
return;
}
} else { // internalConsole
_process = new System.Diagnostics.Process();
_process.StartInfo.CreateNoWindow = true;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.WorkingDirectory = workingDirectory;
_process.StartInfo.FileName = mono_path;
_process.StartInfo.Arguments = Utilities.ConcatArgs(cmdLine.ToArray());
_stdoutEOF = false;
_process.StartInfo.RedirectStandardOutput = true;
_process.OutputDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => {
if (e.Data == null) {
_stdoutEOF = true;
}
SendOutput("stdout", e.Data);
};
_stderrEOF = false;
_process.StartInfo.RedirectStandardError = true;
_process.ErrorDataReceived += (object sender, System.Diagnostics.DataReceivedEventArgs e) => {
if (e.Data == null) {
_stderrEOF = true;
}
SendOutput("stderr", e.Data);
};
_process.EnableRaisingEvents = true;
_process.Exited += (object sender, EventArgs e) => {
Terminate("runtime process exited");
};
if (env != null) {
// we cannot set the env vars on the process StartInfo because we need to set StartInfo.UseShellExecute to true at the same time.
// instead we set the env vars on MonoDebug itself because we know that MonoDebug lives as long as a debug session.
foreach (var entry in env) {
System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
}
}
var cmd = string.Format("{0} {1}", mono_path, _process.StartInfo.Arguments);
SendOutput("console", cmd);
try {
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
}
catch (Exception e) {
SendErrorResponse(response, 3012, "Can't launch terminal ({reason}).", new { reason = e.Message });
return;
}
}
if (debug) {
Connect(IPAddress.Parse(host), port);
}
SendResponse(response);
if (_process == null && !debug) {
// we cannot track mono runtime process so terminate this session
Terminate("cannot track mono runtime");
}
}
public override void Attach(Response response, dynamic args)
{
_attachMode = true;
SetExceptionBreakpoints(args.__exceptionOptions);
// validate argument 'address'
var host = getString(args, "address");
if (host == null) {
SendErrorResponse(response, 3007, "Property 'address' is missing or empty.");
return;
}
// validate argument 'port'
var port = getInt(args, "port", -1);
if (port == -1) {
SendErrorResponse(response, 3008, "Property 'port' is missing.");
return;
}
IPAddress address = Utilities.ResolveIPAddress(host);
if (address == null) {
SendErrorResponse(response, 3013, "Invalid address '{address}'.", new { address = address });
return;
}
Connect(address, port);
SendResponse(response);
}
public override void Disconnect(Response response, dynamic args)
{
if (_attachMode) {
lock (_lock) {
if (_session != null) {
_debuggeeExecuting = true;
_breakpoints.Clear();
_session.Breakpoints.Clear();
_session.Continue();
_session = null;
}
}
} else {
// Let's not leave dead Mono processes behind...
if (_process != null) {
_process.Kill();
_process = null;
} else {
PauseDebugger();
DebuggerKill();
while (!_debuggeeKilled) {
System.Threading.Thread.Sleep(10);
}
}
}
SendResponse(response);
}
public override void Continue(Response response, dynamic args)
{
WaitForSuspend();
SendResponse(response);
lock (_lock) {
if (_session != null && !_session.IsRunning && !_session.HasExited) {
_session.Continue();
_debuggeeExecuting = true;
}
}
}
public override void Next(Response response, dynamic args)
{
WaitForSuspend();
SendResponse(response);
lock (_lock) {
if (_session != null && !_session.IsRunning && !_session.HasExited) {
_session.NextLine();
_debuggeeExecuting = true;
}
}
}
public override void StepIn(Response response, dynamic args)
{
WaitForSuspend();
SendResponse(response);
lock (_lock) {
if (_session != null && !_session.IsRunning && !_session.HasExited) {
_session.StepLine();
_debuggeeExecuting = true;
}
}
}
public override void StepOut(Response response, dynamic args)
{
WaitForSuspend();
SendResponse(response);
lock (_lock) {
if (_session != null && !_session.IsRunning && !_session.HasExited) {
_session.Finish();
_debuggeeExecuting = true;
}
}
}
public override void Pause(Response response, dynamic args)
{
SendResponse(response);
PauseDebugger();
}
public override void SetExceptionBreakpoints(Response response, dynamic args)
{
if (args.filterOptions != null)
{
if (_activeProcess != null)
SetExceptionBreakpointsFromDap(args.filterOptions);
else
exceptionOptionsFromDap = args.filterOptions;
}
else
SetExceptionBreakpoints(args.exceptionOptions);
SendResponse(response);
}
public override void SetBreakpoints(Response response, dynamic args)
{
string path = null;
if (args.source != null) {
string p = (string)args.source.path;
if (p != null && p.Trim().Length > 0) {
path = p;
}
}
if (path == null) {
SendErrorResponse(response, 3010, "setBreakpoints: property 'source' is empty or misformed", null, false, true);
return;
}
path = ConvertClientPathToDebugger(path);
if (!HasMonoExtension(path)) {
// we only support breakpoints in files mono can handle
SendResponse(response, new SetBreakpointsResponseBody());
return;
}
var clientLines = args.lines.ToObject<int[]>();
HashSet<int> lin = new HashSet<int>();
for (int i = 0; i < clientLines.Length; i++) {
lin.Add(ConvertClientLineToDebugger(clientLines[i]));
}
// find all breakpoints for the given path and remember their id and line number
var bpts = new List<Tuple<int, int>>();
foreach (var be in _breakpoints) {
var bp = be.Value as Mono.Debugging.Client.Breakpoint;
if (bp != null && bp.FileName == path) {
bpts.Add(new Tuple<int,int>((int)be.Key, (int)bp.Line));
}
}
HashSet<int> lin2 = new HashSet<int>();
foreach (var bpt in bpts) {
if (lin.Contains(bpt.Item2)) {
lin2.Add(bpt.Item2);
}
else {
// Program.Log("cleared bpt #{0} for line {1}", bpt.Item1, bpt.Item2);
BreakEvent b;
if (_breakpoints.TryGetValue(bpt.Item1, out b)) {
_breakpoints.Remove(bpt.Item1);
_session.Breakpoints.Remove(b);
}
}
}
for (int i = 0; i < clientLines.Length; i++) {
var l = ConvertClientLineToDebugger(clientLines[i]);
if (!lin2.Contains(l)) {
var id = _nextBreakpointId++;
_breakpoints.Add(id, _session.Breakpoints.Add(path, l));
// Program.Log("added bpt #{0} for line {1}", id, l);
}
}
var breakpoints = new List<Breakpoint>();
foreach (var l in clientLines) {
breakpoints.Add(new Breakpoint(true, l));
}
SendResponse(response, new SetBreakpointsResponseBody(breakpoints));
}
public override void StackTrace(Response response, dynamic args)
{
int maxLevels = getInt(args, "levels", 10);
int threadReference = getInt(args, "threadId", 0);
WaitForSuspend();
ThreadInfo thread = DebuggerActiveThread();
if (thread.Id != threadReference) {
// Program.Log("stackTrace: unexpected: active thread should be the one requested");
thread = FindThread(threadReference);
if (thread != null) {
thread.SetActive();
}
}
var stackFrames = new List<StackFrame>();
int totalFrames = 0;
var bt = thread.Backtrace;
if (bt != null && bt.FrameCount >= 0) {
totalFrames = bt.FrameCount;
for (var i = 0; i < Math.Min(totalFrames, maxLevels); i++) {
var frame = bt.GetFrame(i);
string path = frame.SourceLocation.FileName;
var hint = "subtle";
Source source = null;
if (!string.IsNullOrEmpty(path)) {
string sourceName = Path.GetFileName(path);
if (!string.IsNullOrEmpty(sourceName)) {
if (File.Exists(path)) {
source = new Source(sourceName, ConvertDebuggerPathToClient(path), 0, "normal");
hint = "normal";
} else {
source = new Source(sourceName, null, 1000, "deemphasize");
}
}
}
var frameHandle = _frameHandles.Create(frame);
string name = frame.SourceLocation.MethodName;
int line = frame.SourceLocation.Line;
stackFrames.Add(new StackFrame(frameHandle, name, source, ConvertDebuggerLineToClient(line), 0, hint));
}
}
SendResponse(response, new StackTraceResponseBody(stackFrames, totalFrames));
}
public override void Source(Response response, dynamic arguments) {
SendErrorResponse(response, 1020, "No source available");
}
public override void Scopes(Response response, dynamic args) {
int frameId = getInt(args, "frameId", 0);
var frame = _frameHandles.Get(frameId, null);
var scopes = new List<Scope>();
if (frame.Index == 0 && _exception != null) {
scopes.Add(new Scope("Exception", _variableHandles.Create(new ObjectValue[] { _exception })));
}
var locals = new[] { frame.GetThisReference() }.Concat(frame.GetParameters()).Concat(frame.GetLocalVariables()).Where(x => x != null).ToArray();
if (locals.Length > 0) {
scopes.Add(new Scope("Local", _variableHandles.Create(locals)));
}
SendResponse(response, new ScopesResponseBody(scopes));
}
public override void Variables(Response response, dynamic args)
{
int reference = getInt(args, "variablesReference", -1);
if (reference == -1) {
SendErrorResponse(response, 3009, "variables: property 'variablesReference' is missing", null, false, true);
return;
}
WaitForSuspend();
var variables = new List<Variable>();
ObjectValue[] children;
if (_variableHandles.TryGet(reference, out children)) {
if (children != null && children.Length > 0) {
bool more = false;
if (children.Length > MAX_CHILDREN) {
children = children.Take(MAX_CHILDREN).ToArray();
more = true;
}
if (children.Length < 20) {
// Wait for all values at once.
WaitHandle.WaitAll(children.Select(x => x.WaitHandle).ToArray());
foreach (var v in children) {
variables.Add(CreateVariable(v));
}
}
else {
foreach (var v in children) {
v.WaitHandle.WaitOne();
variables.Add(CreateVariable(v));
}
}
if (more) {
variables.Add(new Variable("...", null, null));
}
}
}
SendResponse(response, new VariablesResponseBody(variables));
}
public override void Threads(Response response, dynamic args)
{
var threads = new List<Thread>();
var process = _activeProcess;
if (process != null) {
Dictionary<int, Thread> d;
lock (_seenThreads) {
d = new Dictionary<int, Thread>(_seenThreads);
}
foreach (var t in process.GetThreads()) {
int tid = (int)t.Id;
d[tid] = new Thread(tid, t.Name);
}
threads = d.Values.ToList();
}
SendResponse(response, new ThreadsResponseBody(threads));
}
public override void Evaluate(Response response, dynamic args)
{
string error = null;
var expression = getString(args, "expression");
if (expression == null) {
error = "expression missing";
} else {
int frameId = getInt(args, "frameId", -1);
var frame = _frameHandles.Get(frameId, null);
if (frame != null) {
if (frame.ValidateExpression(expression)) {
var val = frame.GetExpressionValue(expression, _debuggerSessionOptions.EvaluationOptions);
val.WaitHandle.WaitOne();
var flags = val.Flags;
if (flags.HasFlag(ObjectValueFlags.Error) || flags.HasFlag(ObjectValueFlags.NotSupported)) {
error = val.DisplayValue;
if (error.IndexOf("reference not available in the current evaluation context") > 0) {
error = "not available";
}
}
else if (flags.HasFlag(ObjectValueFlags.Unknown)) {
error = "invalid expression";
}
else if (flags.HasFlag(ObjectValueFlags.Object) && flags.HasFlag(ObjectValueFlags.Namespace)) {
error = "not available";
}
else {
int handle = 0;
if (val.HasChildren) {
handle = _variableHandles.Create(val.GetAllChildren());
}
SendResponse(response, new EvaluateResponseBody(val.DisplayValue, handle));
return;
}
}
else {
error = "invalid expression";
}
}
else {
error = "no active stackframe";
}
}
SendErrorResponse(response, 3014, "Evaluate request failed ({_reason}).", new { _reason = error } );
}
//---- private ------------------------------------------
private void SetExceptionBreakpointsFromDap(dynamic exceptionOptions)
{
if (exceptionOptions != null) {
var exceptions = exceptionOptions.ToObject<dynamic[]>();
for (int i = 0; i < exceptions.Length; i++) {
var exception = exceptions[i];
bool caught = exception.filterId == "always" ? true : false;
if (exception.condition != null && exception.condition != "") {
string[] conditionNames = exception.condition.ToString().Split(',');
foreach (var conditionName in conditionNames)
_session.EnableException(conditionName, caught);
}
else {
_session.EnableException("System.Exception", caught);
}
}
}
}
private void SetExceptionBreakpoints(dynamic exceptionOptions)
{
if (exceptionOptions != null) {
// clear all existig catchpoints
foreach (var cp in _catchpoints) {
_session.Breakpoints.Remove(cp);
}
_catchpoints.Clear();
var exceptions = exceptionOptions.ToObject<dynamic[]>();
for (int i = 0; i < exceptions.Length; i++) {
var exception = exceptions[i];
string exName = null;
string exBreakMode = exception.breakMode;
if (exception.path != null) {
var paths = exception.path.ToObject<dynamic[]>();
var path = paths[0];
if (path.names != null) {
var names = path.names.ToObject<dynamic[]>();
if (names.Length > 0) {
exName = names[0];
}
}
}
if (exName != null && exBreakMode == "always") {
_catchpoints.Add(_session.Breakpoints.AddCatchpoint(exName));
}
}
}
}
private void SendOutput(string category, string data) {
if (!String.IsNullOrEmpty(data)) {
if (data[data.Length-1] != '\n') {
data += '\n';
}
SendEvent(new OutputEvent(category, data));
}
}
private void Terminate(string reason) {
if (!_terminated) {
// wait until we've seen the end of stdout and stderr
for (int i = 0; i < 100 && (_stdoutEOF == false || _stderrEOF == false); i++) {
System.Threading.Thread.Sleep(100);
}
SendEvent(new TerminatedEvent());
_terminated = true;
_process = null;
}
}
private StoppedEvent CreateStoppedEvent(string reason, ThreadInfo ti, string text = null)
{
return new StoppedEvent((int)ti.Id, reason, text);
}
private ThreadInfo FindThread(int threadReference)
{
if (_activeProcess != null) {
foreach (var t in _activeProcess.GetThreads()) {
if (t.Id == threadReference) {
return t;
}
}
}
return null;
}
private void Stopped()
{
_exception = null;
_variableHandles.Reset();
_frameHandles.Reset();
}
private Variable CreateVariable(ObjectValue v)
{
var dv = v.DisplayValue;
if (dv.Length > 1 && dv [0] == '{' && dv [dv.Length - 1] == '}') {
dv = dv.Substring (1, dv.Length - 2);
}
return new Variable(v.Name, dv, v.TypeName, v.HasChildren ? _variableHandles.Create(v.GetAllChildren()) : 0);
}
private bool HasMonoExtension(string path)
{
foreach (var e in MONO_EXTENSIONS) {
if (path.EndsWith(e)) {
return true;
}
}
return false;
}
private static bool getBool(dynamic container, string propertyName, bool dflt = false)
{
try {
return (bool)container[propertyName];
}
catch (Exception) {
// ignore and return default value
}
return dflt;
}
private static int getInt(dynamic container, string propertyName, int dflt = 0)
{
try {
return (int)container[propertyName];
}
catch (Exception) {
// ignore and return default value
}
return dflt;
}
private static string getString(dynamic args, string property, string dflt = null)
{
var s = (string)args[property];
if (s == null) {
return dflt;
}
s = s.Trim();
if (s.Length == 0) {
return dflt;
}
return s;
}
//-----------------------
private void WaitForSuspend()
{
if (_debuggeeExecuting) {
_resumeEvent.WaitOne();
_debuggeeExecuting = false;
}
}
private ThreadInfo DebuggerActiveThread()
{
lock (_lock) {
return _session == null ? null : _session.ActiveThread;
}
}
private Backtrace DebuggerActiveBacktrace() {
var thr = DebuggerActiveThread();
return thr == null ? null : thr.Backtrace;
}
private Mono.Debugging.Client.StackFrame DebuggerActiveFrame() {
if (_activeFrame != null)
return _activeFrame;
var bt = DebuggerActiveBacktrace();
if (bt != null)
return _activeFrame = bt.GetFrame(0);
return null;
}
private ExceptionInfo DebuggerActiveException() {
var bt = DebuggerActiveBacktrace();
return bt == null ? null : bt.GetFrame(0).GetException();
}
private void Connect(IPAddress address, int port)
{
lock (_lock) {
_debuggeeKilled = false;
var args0 = new Mono.Debugging.Soft.SoftDebuggerConnectArgs(string.Empty, address, port) {
MaxConnectionAttempts = MAX_CONNECTION_ATTEMPTS,
TimeBetweenConnectionAttempts = CONNECTION_ATTEMPT_INTERVAL
};