Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DebuggingService.cs « MonoDevelop.Debugger « MonoDevelop.Debugger « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5ed2950d2ef4efed5ce39ceac8e7bc443f948035 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
// DebuggingService.cs
//
// Author:
//   Mike Kestner <mkesner@ximian.com>
//   Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2004-2008 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

using System;
using System.Collections.Generic;
using System.Xml;
using Mono.Addins;
using Mono.Debugging.Client;
using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide.Gui.Content;
using MonoDevelop.Projects;
using MonoDevelop.Debugger.Viewers;

/*
 * Some places we should be doing some error handling we used to toss
 * exceptions, now we error out silently, this needs a real solution.
 */
using MonoDevelop.Ide.TextEditing;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;
using MonoDevelop.Core.Instrumentation;
using MonoDevelop.Components;
using Microsoft.VisualStudio.Text;
using Microsoft.CodeAnalysis.Text;

namespace MonoDevelop.Debugger
{
	public static class DebuggingService
	{
		const string FactoriesPath = "/MonoDevelop/Debugging/DebuggerEngines";
		static DebuggerEngine [] engines;

		const string EvaluatorsPath = "/MonoDevelop/Debugging/Evaluators";
		static Dictionary<string, ExpressionEvaluatorExtensionNode> evaluators;

		static readonly PinnedWatchStore pinnedWatches = new PinnedWatchStore ();
		static readonly BreakpointStore breakpoints = new BreakpointStore ();
		static readonly DebugExecutionHandlerFactory executionHandlerFactory;

		static Dictionary<long, SourceLocation> nextStatementLocations = new Dictionary<long, SourceLocation> ();
		static Dictionary<DebuggerSession, SessionManager> sessions = new Dictionary<DebuggerSession, SessionManager> ();
		static Backtrace currentBacktrace;
		static SessionManager currentSession;
		static int currentFrame;

		static ExceptionCaughtMessage exceptionDialog;

		static BusyEvaluator busyEvaluator;
		static StatusBarIcon busyStatusIcon;
		static bool isBusy;

		static public event EventHandler DebugSessionStarted;
		static public event EventHandler PausedEvent;
		static public event EventHandler ResumedEvent;
		static public event EventHandler StoppedEvent;

		static public event EventHandler CallStackChanged;
		static public event EventHandler CurrentFrameChanged;
		static public event EventHandler ExecutionLocationChanged;
		static public event EventHandler VariableChanged;
		static public event EventHandler DisassemblyRequested;
		static public event EventHandler<DocumentEventArgs> DisableConditionalCompilation;

		static public event EventHandler EvaluationOptionsChanged;

		static DebuggingService ()
		{
			executionHandlerFactory = new DebugExecutionHandlerFactory ();
			IdeApp.Initialized += delegate {
				IdeServices.TextEditorService.LineCountChanged += OnLineCountChanged;
				IdeApp.Workspace.StoringUserPreferences += OnStoreUserPrefs;
				IdeApp.Workspace.LoadingUserPreferences += OnLoadUserPrefs;
				IdeApp.Workspace.LastWorkspaceItemClosed += OnSolutionClosed;
				busyEvaluator = new BusyEvaluator ();
			};
			AddinManager.AddExtensionNodeHandler (FactoriesPath, delegate {
				// Refresh the engines list
				engines = null;
			});
			AddinManager.AddExtensionNodeHandler (EvaluatorsPath, delegate {
				// Refresh the evaluators list
				evaluators = null;
			});
			IdeApp.Exiting += IdeApp_Exiting;
			FileService.FileRenamed += FileService_FileRenamed;
			FileService.FileMoved += FileService_FileRenamed;
		}

		private static void FileService_FileRenamed (object sender, FileCopyEventArgs e)
		{
			foreach (var file in e) {
				breakpoints.FileRenamed (file.SourceFile, file.TargetFile);
			}
		}

		static void IdeApp_Exiting (object sender, ExitEventArgs args)
		{
			if (!IsDebugging)
				return;
			if (MessageService.Confirm (GettextCatalog.GetString (
						"The debugger is currently running and will have to be stopped. Do you want to stop debugging?"),
						new AlertButton (GettextCatalog.GetString ("Stop Debugging")))) {
				Stop ();
			} else
				args.Cancel = true;
		}


		public static IExecutionHandler GetExecutionHandler ()
		{
			return executionHandlerFactory;
		}

		public static DebuggerSession DebuggerSession {
			get { return currentSession?.Session ?? sessions.Values.FirstOrDefault ()?.Session; }
		}


		public static DebuggerSession [] GetSessions ()
		{
			return sessions.Keys.ToArray ();
		}

		public static ProcessInfo [] GetProcesses ()
		{
			return sessions.Keys.Where (s => !s.IsRunning).SelectMany (s => s.GetProcesses ()).ToArray ();
		}

		public static BreakEventStatus GetBreakpointStatus (Breakpoint bp)
		{
			var result = BreakEventStatus.Disconnected;
			foreach (var sesion in sessions.Keys.ToArray ()) {
				var status = bp.GetStatus (sesion);
				if (status == BreakEventStatus.Bound)
					return BreakEventStatus.Bound;
				else
					result = status;
			}
			return result;
		}

		public static BreakpointStore Breakpoints {
			get { return breakpoints; }
		}

		public static PinnedWatchStore PinnedWatches {
			get { return pinnedWatches; }
		}

		public static void SetLiveUpdateMode (PinnedWatch watch, bool liveUpdate)
		{
			if (watch.LiveUpdate == liveUpdate)
				return;

			watch.LiveUpdate = liveUpdate;
			if (liveUpdate) {
				var bp = pinnedWatches.CreateLiveUpdateBreakpoint (watch);
				pinnedWatches.Bind (watch, bp);
				lock (breakpoints)
					breakpoints.Add(bp);
			} else {
				pinnedWatches.Bind (watch, null);
				lock (breakpoints)
					breakpoints.Remove (watch.BoundTracer);
			}
		}

		[Obsolete]
		public static string [] EnginePriority {
			get { return new string [0]; }
			set {
			}
		}

		internal static IEnumerable<ValueVisualizer> GetValueVisualizers (ObjectValue val)
		{
			foreach (object v in AddinManager.GetExtensionObjects ("/MonoDevelop/Debugging/ValueVisualizers", false)) {
				if (v is ValueVisualizer) {
					var vv = (ValueVisualizer)v;
					if (vv.CanVisualize (val))
						yield return vv;
				}
			}
		}

		internal static bool HasValueVisualizers (ObjectValue val)
		{
			return GetValueVisualizers (val).Any ();
		}

		internal static InlineVisualizer GetInlineVisualizer (ObjectValue val)
		{
			foreach (object v in AddinManager.GetExtensionObjects ("/MonoDevelop/Debugging/InlineVisualizers", true)) {
				var cv = v as InlineVisualizer;
				if (cv != null && cv.CanInlineVisualize (val)) {
					return cv;
				}
			}
			return null;
		}

		internal static bool HasInlineVisualizer (ObjectValue val)
		{
			return GetInlineVisualizer (val) != null;
		}

		internal static PreviewVisualizer GetPreviewVisualizer (ObjectValue val)
		{
			foreach (object v in AddinManager.GetExtensionObjects ("/MonoDevelop/Debugging/PreviewVisualizers", true)) {
				var cv = v as PreviewVisualizer;
				if (cv != null && cv.CanVisualize (val)) {
					return cv;
				}
			}
			return null;
		}

		internal static bool HasPreviewVisualizer (ObjectValue val)
		{
			return GetPreviewVisualizer (val) != null;
		}

		public static DebugValueConverter<T> GetGetConverter<T> (ObjectValue val)
		{
			foreach (object v in AddinManager.GetExtensionObjects ("/MonoDevelop/Debugging/DebugValueConverters", true)) {
				var cv = v as DebugValueConverter<T>;
				if (cv != null && cv.CanGetValue (val)) {
					return cv;
				}
			}
			return null;
		}

		public static bool HasGetConverter<T> (ObjectValue val)
		{
			return GetGetConverter<T> (val) != null;
		}

		public static DebugValueConverter<T> GetSetConverter<T> (ObjectValue val)
		{
			foreach (object v in AddinManager.GetExtensionObjects ("/MonoDevelop/Debugging/DebugValueConverters", true)) {
				var cv = v as DebugValueConverter<T>;
				if (cv != null && cv.CanSetValue (val)) {
					return cv;
				}
			}
			return null;
		}

		public static bool HasSetConverter<T> (ObjectValue val)
		{
			return GetSetConverter<T> (val) != null;
		}

		public static bool ShowValueVisualizer (ObjectValue val)
		{
			using (var dlg = new ValueVisualizerDialog ()) {
				dlg.Show (val);
				return MessageService.ShowCustomDialog (dlg) == (int)Gtk.ResponseType.Ok;
			}
		}

		public static void ShowPreviewVisualizer (ObjectValue val, MonoDevelop.Components.Control widget, Gdk.Rectangle previewButtonArea)
		{
			PreviewWindowManager.Show (val, widget, previewButtonArea);
		}

		public static bool ShowBreakpointProperties (ref BreakEvent bp, BreakpointType breakpointType = BreakpointType.Location)
		{
			using (var dlg = new BreakpointPropertiesDialog (bp, breakpointType)) {
				Xwt.WindowFrame parentWindow = Xwt.Toolkit.CurrentEngine.WrapWindow (IdeApp.Workbench.RootWindow);
				Xwt.Command response = dlg.Run (parentWindow);
				if (bp == null)
					bp = dlg.GetBreakEvent ();
				return response == Xwt.Command.Ok;
			}
		}

		public static void AddWatch (string expression)
		{
			var pad = IdeApp.Workbench.GetPad<WatchPad> ();
			var wp = (WatchPad)pad.Content;

			pad.BringToFront (false);
			wp.AddWatch (expression);
		}

		public static bool IsFeatureSupported (IBuildTarget target, DebuggerFeatures feature)
		{
			return (GetSupportedFeatures (target) & feature) == feature;
		}

		public static bool IsDebuggingSupported {
			get {
				return AddinManager.GetExtensionNodes (FactoriesPath).Count > 0;
			}
		}

		public static bool CurrentSessionSupportsFeature (DebuggerFeatures feature)
		{
			return (currentSession.Engine.SupportedFeatures & feature) == feature;
		}

		public static bool IsFeatureSupported (DebuggerFeatures feature)
		{
			foreach (var engine in GetDebuggerEngines ())
				if ((engine.SupportedFeatures & feature) == feature)
					return true;
			return false;
		}

		public static DebuggerFeatures GetSupportedFeatures (IBuildTarget target)
		{
			var fc = new FeatureCheckerHandlerFactory ();
			var ctx = new Projects.ExecutionContext (fc, null, IdeApp.Workspace.ActiveExecutionTarget);

			target.CanExecute (ctx, IdeApp.Workspace.ActiveConfiguration);

			return fc.SupportedFeatures;
		}

		public static DebuggerFeatures GetSupportedFeaturesForCommand (ExecutionCommand command)
		{
			var engine = GetFactoryForCommand (command);

			return engine != null ? engine.SupportedFeatures : DebuggerFeatures.None;
		}

		public static void ShowExpressionEvaluator (string expression)
		{
			var dlg = new ExpressionEvaluatorDialog ();
			if (expression != null)
				dlg.Expression = expression;
			dlg.TransientFor = MessageService.RootWindow;
			dlg.Show ();
			MessageService.PlaceDialog (dlg, MessageService.RootWindow);
		}

		public static void ShowExceptionCaughtDialog ()
		{
			var ops = GetUserOptions ().EvaluationOptions;
			ops.MemberEvaluationTimeout = 0;
			ops.EvaluationTimeout = 0;
			ops.EllipsizeStrings = false;

			var val = CurrentFrame.GetException (ops);
			if (val != null) {
				HideExceptionCaughtDialog ();
				exceptionDialog = new ExceptionCaughtMessage (val, CurrentFrame.SourceLocation.FileName, CurrentFrame.SourceLocation.Line, CurrentFrame.SourceLocation.Column);
				if (CurrentFrame.SourceLocation.FileName != null) {
					exceptionDialog.ShowButton ();
				} else {
					exceptionDialog.ShowDialog ();
				}
				exceptionDialog.Closed += (o, args) => exceptionDialog = null;
			}
		}

		static void HideExceptionCaughtDialog ()
		{
			if (exceptionDialog != null) {
				exceptionDialog.Dispose ();
				exceptionDialog = null;
			}
		}

		internal static ExceptionCaughtMessage ExceptionCaughtMessage {
			get {
				return exceptionDialog;
			}
		}

		static void SetupSession (SessionManager sessionManager)
		{
			sessions.Add (sessionManager.Session, sessionManager);
			isBusy = false;
			var session = sessionManager.Session;
			session.Breakpoints = breakpoints;
			session.TargetEvent += OnTargetEvent;
			session.TargetStarted += OnStarted;
			session.OutputWriter = sessionManager.OutputWriter;
			session.LogWriter = sessionManager.LogWriter;
			session.DebugWriter = sessionManager.DebugWriter;
			session.BusyStateChanged += OnBusyStateChanged;
			session.TypeResolverHandler = ResolveType;
			session.BreakpointTraceHandler = sessionManager.BreakpointTraceHandler;
			session.GetExpressionEvaluator = OnGetExpressionEvaluator;
			session.ConnectionDialogCreatorExtended = delegate (DebuggerStartInfo dsi) {
				if (dsi.RequiresManualStart)
					return new GtkConnectionDialog ();

				return new StatusBarConnectionDialog ();
			};

			Runtime.RunInMainThread (delegate {
				if (DebugSessionStarted != null)
					DebugSessionStarted (session, EventArgs.Empty);
				NotifyLocationChanged ();
			});
		}

		static readonly object cleanup_lock = new object ();
		static void Cleanup (SessionManager sessionManager)
		{
			StatusBarIcon currentIcon;

			var cleaningCurrentSession = sessionManager == currentSession;
			lock (cleanup_lock) {
				if (!IsDebugging)
					return;

				currentIcon = busyStatusIcon;

				nextStatementLocations.Clear ();
				if (cleaningCurrentSession) {
					currentSession = null;
					currentBacktrace = null;
				}
				busyStatusIcon = null;
				sessions.Remove (sessionManager.Session);
				pinnedWatches.InvalidateAll ();
			}

			if (sessions.Count == 0)
				UnsetDebugLayout ();
			var session = sessionManager.Session;
			session.BusyStateChanged -= OnBusyStateChanged;
			session.TargetEvent -= OnTargetEvent;
			session.TargetStarted -= OnStarted;

			session.BreakpointTraceHandler = null;
			session.GetExpressionEvaluator = null;
			session.TypeResolverHandler = null;
			session.OutputWriter = null;
			session.LogWriter = null;

			Runtime.RunInMainThread (delegate {
				if (cleaningCurrentSession)
					HideExceptionCaughtDialog ();

				if (currentIcon != null) {
					currentIcon.Dispose ();
					currentIcon = null;
				}

				if (StoppedEvent != null)
					StoppedEvent (session, new EventArgs ());

				NotifyCallStackChanged ();
				NotifyCurrentFrameChanged ();
				NotifyLocationChanged ();
			}).ContinueWith ((t) => {
				sessionManager.Dispose ();
			});
		}

		static string oldLayout;
		static void UnsetDebugLayout ()
		{
			// Dispatch synchronously to avoid start/stop races
			Runtime.RunInMainThread (delegate {
				IdeApp.Workbench.HideCommandBar ("Debug");
				if (IdeApp.Workbench.CurrentLayout == "Debug") {
					IdeApp.Workbench.CurrentLayout = oldLayout ?? "Solution";
				}
				oldLayout = null;
			}).Wait ();
		}

		static void SetDebugLayout ()
		{
			// Dispatch synchronously to avoid start/stop races
			Runtime.RunInMainThread (delegate {
				oldLayout = IdeApp.Workbench.CurrentLayout;
				IdeApp.Workbench.CurrentLayout = "Debug";
				IdeApp.Workbench.ShowCommandBar ("Debug");
			}).Wait ();
		}

		public static bool IsDebugging {
			get {
				return sessions.Count > 0;
			}
		}

		public static bool IsConnected {
			get {
				return IsDebugging && sessions.Keys.Any (s => s.IsConnected);
			}
		}

		public static bool IsRunning {
			get {
				return IsDebugging && sessions.Keys.Any (s => s.IsRunning);
			}
		}

		public static bool IsPaused {
			get {
				return IsDebugging && currentSession != null && currentBacktrace != null;
			}
		}

		public static void Pause ()
		{
			foreach (var session in sessions.Keys.ToArray ()) {
				if (session.IsRunning)
					session.Stop ();
			}
		}

		static ConcurrentQueue<Func<bool>> StopsQueue = new ConcurrentQueue<Func<bool>> ();

		static bool HandleStopQueue ()
		{
			Func<bool> delayedStop;
			while (StopsQueue.TryDequeue (out delayedStop)) {
				//Returns false if session which scheduled stop is terminated
				//So we just ignore it's stop entry and keep processing others or resume
				if (delayedStop ())
					return true;
			}
			return false;
		}

		public static void Resume ()
		{
			Runtime.AssertMainThread ();
			if (CheckIsBusy ())
				return;
			if (HandleStopQueue ())
				return;

			foreach (var session in sessions.Keys.ToArray ()) {
				if (!session.IsRunning)
					session.Continue ();
			}
			NotifyLocationChanged ();
		}

		public static void RunToCursor (string fileName, int line, int column)
		{
			Runtime.AssertMainThread ();
			if (CheckIsBusy ())
				return;

			var bp = new RunToCursorBreakpoint (fileName, line, column);
			Breakpoints.Add (bp);

			Resume ();
			NotifyLocationChanged ();
		}

		public static void SetNextStatement (string fileName, int line, int column)
		{
			Runtime.AssertMainThread ();
			if (!IsDebugging || !IsPaused || CheckIsBusy ())
				return;

			currentSession.Session.SetNextStatement (fileName, line, column);

			var location = new SourceLocation (CurrentFrame.SourceLocation.MethodName, fileName, line, column, -1, -1, null);
			nextStatementLocations [ActiveThread.Id] = location;
			NotifyLocationChanged ();
		}

		public static ProcessAsyncOperation Run (string file, OperationConsole console)
		{
			var cmd = Runtime.ProcessService.CreateCommand (file);
			return Run (cmd, console);
		}

		public static ProcessAsyncOperation Run (string file, string args, string workingDir, IDictionary<string, string> envVars, OperationConsole console)
		{
			var cmd = Runtime.ProcessService.CreateCommand (file);
			if (args != null)
				cmd.Arguments = args;
			if (workingDir != null)
				cmd.WorkingDirectory = workingDir;
			if (envVars != null)
				cmd.EnvironmentVariables = envVars;
			return Run (cmd, console);
		}

		public static ProcessAsyncOperation Run (ExecutionCommand cmd, OperationConsole console, DebuggerEngine engine = null)
		{
			return InternalRun (cmd, engine, console);
		}

		public static AsyncOperation AttachToProcess (DebuggerEngine debugger, ProcessInfo proc)
		{
			var session = debugger.CreateSession ();
			var monitor = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor (proc.Name);
			var sessionManager = new SessionManager (session, monitor.Console, debugger, null);
			SetupSession (sessionManager);
			session.TargetExited += delegate {
				monitor.Dispose ();
			};
			SetDebugLayout ();
			session.AttachToProcess (proc, GetUserOptions ());
			return sessionManager.debugOperation;
		}

		public static DebuggerSessionOptions GetUserOptions ()
		{
			EvaluationOptions eval = EvaluationOptions.DefaultOptions;
			eval.AllowTargetInvoke = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.AllowTargetInvoke", true);
			eval.AllowToStringCalls = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.AllowToStringCalls", true);
			eval.EvaluationTimeout = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.EvaluationTimeout", 2500);
			eval.FlattenHierarchy = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.FlattenHierarchy", false);
			eval.GroupPrivateMembers = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.GroupPrivateMembers", true);
			eval.EllipsizedLength = 260; // Instead of random default(100), lets use 260 which should cover 99.9% of file path cases
			eval.GroupStaticMembers = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.GroupStaticMembers", true);
			eval.MemberEvaluationTimeout = eval.EvaluationTimeout * 2;
			eval.StackFrameFormat = new StackFrameFormat () {
				Module = PropertyService.Get ("Monodevelop.StackTrace.ShowModuleName", eval.StackFrameFormat.Module),
				ParameterTypes = PropertyService.Get ("Monodevelop.StackTrace.ShowParameterType", eval.StackFrameFormat.ParameterTypes),
				ParameterNames = PropertyService.Get ("Monodevelop.StackTrace.ShowParameterName", eval.StackFrameFormat.ParameterNames),
				ParameterValues = PropertyService.Get ("Monodevelop.StackTrace.ShowParameterValue", eval.StackFrameFormat.ParameterValues),
				Line = PropertyService.Get ("Monodevelop.StackTrace.ShowLineNumber", eval.StackFrameFormat.Line),
				ExternalCode = PropertyService.Get ("Monodevelop.StackTrace.ShowExternalCode", eval.StackFrameFormat.ExternalCode)
			};
			return new DebuggerSessionOptions {
				StepOverPropertiesAndOperators = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.StepOverPropertiesAndOperators", true),
				ProjectAssembliesOnly = PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.ProjectAssembliesOnly", true),
				EvaluationOptions = eval,
			};
		}

		public static void SetUserOptions (DebuggerSessionOptions options)
		{
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.StepOverPropertiesAndOperators", options.StepOverPropertiesAndOperators);
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.ProjectAssembliesOnly", options.ProjectAssembliesOnly);

			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.AllowTargetInvoke", options.EvaluationOptions.AllowTargetInvoke);
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.AllowToStringCalls", options.EvaluationOptions.AllowToStringCalls);
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.EvaluationTimeout", options.EvaluationOptions.EvaluationTimeout);
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.FlattenHierarchy", options.EvaluationOptions.FlattenHierarchy);
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.GroupPrivateMembers", options.EvaluationOptions.GroupPrivateMembers);
			PropertyService.Set ("MonoDevelop.Debugger.DebuggingService.GroupStaticMembers", options.EvaluationOptions.GroupStaticMembers);


			PropertyService.Set ("Monodevelop.StackTrace.ShowModuleName", options.EvaluationOptions.StackFrameFormat.Module);
			PropertyService.Set ("Monodevelop.StackTrace.ShowParameterType", options.EvaluationOptions.StackFrameFormat.ParameterTypes);
			PropertyService.Set ("Monodevelop.StackTrace.ShowParameterName", options.EvaluationOptions.StackFrameFormat.ParameterNames);
			PropertyService.Set ("Monodevelop.StackTrace.ShowParameterValue", options.EvaluationOptions.StackFrameFormat.ParameterValues);
			PropertyService.Set ("Monodevelop.StackTrace.ShowLineNumber", options.EvaluationOptions.StackFrameFormat.Line);
			PropertyService.Set ("Monodevelop.StackTrace.ShowExternalCode", options.EvaluationOptions.StackFrameFormat.ExternalCode);

			foreach (var session in sessions.Keys.ToArray ()) {
				session.Options.EvaluationOptions = GetUserOptions ().EvaluationOptions;
			}
			if (EvaluationOptionsChanged != null)
				EvaluationOptionsChanged (null, EventArgs.Empty);
		}

		public static void ShowDisassembly ()
		{
			if (DisassemblyRequested != null)
				DisassemblyRequested (null, EventArgs.Empty);
		}

		internal static ProcessAsyncOperation InternalRun (ExecutionCommand cmd, DebuggerEngine factory, OperationConsole c)
		{
			// Start assuming success, update on failure
			var metadata = new DebuggerStartMetadata {
				Result = CounterResult.Success
			};
			var timer = Counters.DebuggerStart.BeginTiming (metadata);

			if (factory == null) {
				factory = GetFactoryForCommand (cmd);
				if (factory == null) {
					metadata.SetFailure ();
					timer.Dispose ();
					throw new InvalidOperationException ("Unsupported command: " + cmd);
				}
			}

			metadata.Name = factory.Name;

			DebuggerStartInfo startInfo = factory.CreateDebuggerStartInfo (cmd);
			startInfo.UseExternalConsole = c is ExternalConsole;
			if (startInfo.UseExternalConsole)
				startInfo.CloseExternalConsoleOnExit = ((ExternalConsole)c).CloseOnDispose;

			var session = factory.CreateSession ();

			SessionManager sessionManager;
			// When using an external console, create a new internal console which will be used
			// to show the debugger log
			if (startInfo.UseExternalConsole)
				sessionManager = new SessionManager (session, IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor (System.IO.Path.GetFileNameWithoutExtension (startInfo.Command)).Console, factory, timer);
			else
				sessionManager = new SessionManager (session, c, factory, timer);
			SetupSession (sessionManager);

			SetDebugLayout ();

			try {
				sessionManager.PrepareForRun ();
				session.Run (startInfo, GetUserOptions ());
			} catch {
				sessionManager.SessionError = true;
				Cleanup (sessionManager);
				metadata.SetFailure ();
				throw;
			}
			return sessionManager.debugOperation;
		}

		static bool ExceptionHandler (Exception ex)
		{
			Gtk.Application.Invoke ((o, args) => {
				if (ex is DebuggerException)
					MessageService.ShowError (ex.Message, ex);
				else
					MessageService.ShowError ("Debugger operation failed", ex);
			});
			return true;
		}

		class SessionManager : IDisposable
		{
			OperationConsole console;
			IDisposable cancelRegistration;
			System.Diagnostics.Stopwatch firstAssemblyLoadTimer;

			public readonly DebuggerSession Session;
			public readonly DebugAsyncOperation debugOperation;
			public readonly DebuggerEngine Engine;
			internal ITimeTracker<DebuggerStartMetadata> StartTimer { get; set; }

			internal bool TrackActionTelemetry { get; set; }
			internal DebuggerActionMetadata.ActionType CurrentAction { get; set; }
			internal ITimeTracker ActionTimeTracker { get; set; }

			public SessionManager (DebuggerSession session, OperationConsole console, DebuggerEngine engine, ITimeTracker<DebuggerStartMetadata> timeTracker)
			{
				Engine = engine;
				Session = session;
				session.ExceptionHandler = ExceptionHandler;
				session.AssemblyLoaded += OnAssemblyLoaded;
				this.console = console;
				StartTimer = timeTracker;

				cancelRegistration = console.CancellationToken.Register (Cancel);
				debugOperation = new DebugAsyncOperation (session);
			}

			void Cancel ()
			{
				Session.Exit ();
				StartTimer?.Metadata.SetUserCancel ();
				Cleanup (this);
			}

			public void LogWriter (bool iserr, string text)
			{
				console?.Log.Write (text);
			}

			public void DebugWriter (int level, string category, string message)
			{
				console?.Debug (level, category, message);
			}

			public void OutputWriter (bool iserr, string text)
			{
				if (iserr)
					console?.Error.Write (text);
				else
					console?.Out.Write (text);
			}

			public void BreakpointTraceHandler (BreakEvent be, string trace)
			{
				if (be is Breakpoint) {
					if (pinnedWatches.UpdateLiveWatch ((Breakpoint)be, trace))
						return; // No need to log the value. It is shown in the watch.
				}
				DebugWriter (0, "", trace + Environment.NewLine);
			}

			public void Dispose ()
			{
				UpdateDebugSessionCounter ();
				UpdateEvaluationStatsCounter ();

				console?.Dispose ();
				console = null;
				Session.AssemblyLoaded -= OnAssemblyLoaded;
				Session.Dispose ();
				debugOperation.Cleanup ();
				cancelRegistration?.Dispose ();
				cancelRegistration = null;

				StartTimer?.Dispose ();
			}

			bool sessionError;
			/// <summary>
			/// Indicates whether the debug session failed to an exception or any debugger
			/// operation failed and was reported to the user.
			/// </summary>
			public bool SessionError {
				get => sessionError;
				set {
					sessionError = value;
					StartTimer?.Metadata.SetFailure ();
				}
			}

			void UpdateDebugSessionCounter ()
			{
				var metadata = new Dictionary<string, object> ();
				metadata ["Success"] = (!SessionError).ToString ();
				metadata ["DebuggerType"] = Engine.Id;

				if (firstAssemblyLoadTimer != null) {
					if (firstAssemblyLoadTimer.IsRunning) {
						// No first assembly load event.
						firstAssemblyLoadTimer.Stop ();
					} else {
						metadata ["AssemblyFirstLoadDuration"] = firstAssemblyLoadTimer.ElapsedMilliseconds.ToString ();
					}
				}

				Counters.DebugSession.Inc (1, null, metadata);
			}

			void UpdateEvaluationStatsCounter ()
			{
				if (Session.EvaluationStats.TimingsCount == 0 && Session.EvaluationStats.FailureCount == 0) {
					// No timings or failures recorded.
					return;
				}

				var metadata = new Dictionary<string, object> ();
				metadata ["DebuggerType"] = Engine.Id;
				metadata ["AverageDuration"] = Session.EvaluationStats.AverageTime.ToString ();
				metadata ["MaximumDuration"] = Session.EvaluationStats.MaxTime.ToString ();
				metadata ["MinimumDuration"] = Session.EvaluationStats.MinTime.ToString ();
				metadata ["FailureCount"] = Session.EvaluationStats.FailureCount.ToString ();
				metadata ["SuccessCount"] = Session.EvaluationStats.TimingsCount.ToString ();

				Counters.EvaluationStats.Inc (1, null, metadata);
			}

			bool ExceptionHandler (Exception ex)
			{
				SessionError = true;
				return DebuggingService.ExceptionHandler (ex);
			}

			/// <summary>
			/// Called just before DebugSession.Run is called.
			/// </summary>
			public void PrepareForRun ()
			{
				firstAssemblyLoadTimer = new System.Diagnostics.Stopwatch ();
				firstAssemblyLoadTimer.Start ();
			}

			void OnAssemblyLoaded (object sender, AssemblyEventArgs e)
			{
				DebuggerSession.AssemblyLoaded -= OnAssemblyLoaded;
				firstAssemblyLoadTimer?.Stop ();
			}
		}

		static async void OnBusyStateChanged (object s, BusyStateEventArgs args)
		{
			isBusy = args.IsBusy;
			await Runtime.RunInMainThread (delegate {
				busyEvaluator.UpdateBusyState (args);
				if (args.IsBusy) {
					var session = (DebuggerSession) s;

					if (sessions.TryGetValue (session, out var manager)) {
						var metadata = new Dictionary<string, object> {
							["DebuggerType"] = manager.Engine.Id,
							["Debugger.AsyncOperation.Description"] = args.Description,
							["Debugger.EvaluationOptions.AllowDisplayStringEvaluation"] = args.EvaluationContext.Options.AllowDisplayStringEvaluation,
							["Debugger.EvaluationOptions.AllowMethodEvaluation"] = args.EvaluationContext.Options.AllowMethodEvaluation,
							["Debugger.EvaluationOptions.AllowTargetInvoke"] = args.EvaluationContext.Options.AllowTargetInvoke,
							["Debugger.EvaluationOptions.AllowToStringCalls"] = args.EvaluationContext.Options.AllowToStringCalls,
							["Debugger.EvaluationOptions.ChunkRawStrings"] = args.EvaluationContext.Options.ChunkRawStrings,
							["Debugger.EvaluationOptions.EvaluationTimeout"] = args.EvaluationContext.Options.EvaluationTimeout,
						};

						Counters.DebuggerBusy.Inc (1, null, metadata);
					}

					if (busyStatusIcon == null) {
						busyStatusIcon = IdeApp.Workbench.StatusBar.ShowStatusIcon (ImageService.GetIcon ("md-bug", Gtk.IconSize.Menu));
						busyStatusIcon.SetAlertMode (100);
						busyStatusIcon.Title = GettextCatalog.GetString ("Debugger");
						busyStatusIcon.ToolTip = GettextCatalog.GetString ("The debugger runtime is not responding. You can wait for it to recover, or stop debugging.");
						busyStatusIcon.Help = GettextCatalog.GetString ("Debugger information");
						busyStatusIcon.Clicked += OnBusyStatusIconClicked;
					}
				} else {
					if (busyStatusIcon != null) {
						busyStatusIcon.Clicked -= OnBusyStatusIconClicked;
						busyStatusIcon.Dispose ();
						busyStatusIcon = null;
					}
				}
			});
		}

		static void OnBusyStatusIconClicked (object sender, StatusBarIconClickedEventArgs args)
		{
			MessageService.PlaceDialog (busyEvaluator.Dialog, MessageService.RootWindow);
		}

		static bool CheckIsBusy ()
		{
			if (isBusy && !busyEvaluator.Dialog.Visible)
				MessageService.PlaceDialog (busyEvaluator.Dialog, MessageService.RootWindow);
			return isBusy;
		}

		static void OnStarted (object s, EventArgs a)
		{
			nextStatementLocations.Clear ();

			if (currentSession?.Session == s) {
				currentBacktrace = null;
				currentSession = null;
			}

			Runtime.RunInMainThread (delegate {
				HideExceptionCaughtDialog ();
				if (ResumedEvent != null)
					ResumedEvent (null, a);
				NotifyCallStackChanged ();
				NotifyCurrentFrameChanged ();
				NotifyLocationChanged ();
			});
		}

		static void OnTargetEvent (object sender, TargetEventArgs args)
		{
			var session = (DebuggerSession)sender;
			if (args.BreakEvent != null && args.BreakEvent.NonUserBreakpoint)
				return;
			nextStatementLocations.Clear ();

			SessionManager sessionManager = null;
			try {
				switch (args.Type) {
				case TargetEventType.TargetExited:
					Breakpoints.RemoveRunToCursorBreakpoints ();
					SessionManager sessionToCleanup;
					if (sessions.TryGetValue (session, out sessionToCleanup))//It was already cleanedUp by Stop command
						Cleanup (sessionToCleanup);
					break;
				case TargetEventType.TargetSignaled:
				case TargetEventType.TargetStopped:
				case TargetEventType.TargetHitBreakpoint:
				case TargetEventType.TargetInterrupted:
				case TargetEventType.UnhandledException:
				case TargetEventType.ExceptionThrown:
					var action = new Func<bool> (delegate {
						if (!sessions.TryGetValue (session, out sessionManager))
							return false;

						if (sessionManager.TrackActionTelemetry) {
							var metadata = new DebuggerActionMetadata () {
								Type = sessionManager.CurrentAction
							};
							sessionManager.ActionTimeTracker = Counters.DebuggerAction.BeginTiming ("Debugger action", metadata);
						}
						Breakpoints.RemoveRunToCursorBreakpoints ();
						currentSession = sessionManager;
						ActiveThread = args.Thread;
						NotifyPaused (currentSession);
						NotifyException (args);
						return true;
					});
					if (currentSession != null && currentSession != sessions [session]) {
						StopsQueue.Enqueue (action);
						NotifyPaused (null);//Notify about pause again, so ThreadsPad can update, to show all processes
					} else {
						action ();
					}
					break;
				case TargetEventType.TargetReady:
					if (!sessions.TryGetValue (session, out sessionManager)) {
						return;
					}

					sessionManager.StartTimer?.Metadata.SetSuccess ();

					sessionManager.StartTimer?.Dispose ();
					sessionManager.StartTimer = null;

					if (Ide.Counters.TrackingBuildAndDeploy) {
						Ide.Counters.BuildAndDeploy.EndTiming ();
						Ide.Counters.TrackingBuildAndDeploy = false;
					}
					break;
				}
			} catch (Exception ex) {
				LoggingService.LogError ("Error handling debugger target event", ex);
			}
		}

		static void OnDisableConditionalCompilation (DocumentEventArgs e)
		{
			EventHandler<DocumentEventArgs> handler = DisableConditionalCompilation;
			if (handler != null)
				handler (null, e);
		}

		static void NotifyPaused (SessionManager sessionManager)
		{
			Runtime.RunInMainThread (delegate {
				stepSwitchCts?.Cancel ();
				if (PausedEvent != null)
					PausedEvent (null, EventArgs.Empty);
				NotifyLocationChanged ();
				IdeApp.Workbench.GrabDesktopFocus ();

			}).ContinueWith ((arg) => {
				// PausedEventHandlers may queue additional UI events that can cause a freeze.
				// Ensure those UI events have completed before we stop tracking the time.
				Runtime.RunInMainThread (() => {
					if (sessionManager.TrackActionTelemetry) {
						sessionManager.ActionTimeTracker.Dispose ();
						sessionManager.TrackActionTelemetry = false;
					}
				});
			});
		}

		static void NotifyException (TargetEventArgs args)
		{
			if (args.Type == TargetEventType.UnhandledException || args.Type == TargetEventType.ExceptionThrown) {
				Runtime.RunInMainThread (delegate {
					if (CurrentFrame != null) {
						ShowExceptionCaughtDialog ();
					}
				});
			}
		}

		static void NotifyLocationChanged ()
		{
			Runtime.AssertMainThread ();

			ExecutionLocationChanged?.Invoke (null, EventArgs.Empty);
		}

		static void NotifyCurrentFrameChanged ()
		{
			if (currentBacktrace != null)
				pinnedWatches.InvalidateAll ();

			CurrentFrameChanged?.Invoke (null, EventArgs.Empty);
		}

		static void NotifyCallStackChanged ()
		{
			CallStackChanged?.Invoke (null, EventArgs.Empty);
		}

		internal static void NotifyVariableChanged ()
		{
			VariableChanged?.Invoke (null, EventArgs.Empty);
		}

		public static void Stop ()
		{
			if (!IsDebugging)
				return;

			foreach (var pair in sessions.ToArray ()) {
				pair.Key.Exit ();
				Cleanup (pair.Value);
			}
		}

		public static void StepInto ()
		{

			Runtime.AssertMainThread ();

			if (!IsDebugging || !IsPaused || CheckIsBusy ())
				return;

			currentSession.TrackActionTelemetry = true;
			currentSession.CurrentAction = DebuggerActionMetadata.ActionType.StepInto;

			currentSession.Session.StepLine ();
			NotifyLocationChanged ();
			DelayHandleStopQueue ();
		}

		public static void StepOver ()
		{
			Runtime.AssertMainThread ();

			if (!IsDebugging || !IsPaused || CheckIsBusy ())
				return;

			currentSession.TrackActionTelemetry = true;
			currentSession.CurrentAction = DebuggerActionMetadata.ActionType.StepOver;

			currentSession.Session.NextLine ();
			NotifyLocationChanged ();
			DelayHandleStopQueue ();
		}

		public static void StepOut ()
		{
			Runtime.AssertMainThread ();

			if (!IsDebugging || !IsPaused || CheckIsBusy ())
				return;

			currentSession.TrackActionTelemetry = true;
			currentSession.CurrentAction = DebuggerActionMetadata.ActionType.StepOut;

			currentSession.Session.Finish ();
			NotifyLocationChanged ();
			DelayHandleStopQueue ();
		}

		static CancellationTokenSource stepSwitchCts;
		static void DelayHandleStopQueue ()
		{
			stepSwitchCts?.Cancel ();
			if (StopsQueue.Count > 0) {
				stepSwitchCts = new CancellationTokenSource ();
				var token = stepSwitchCts.Token;
				Task.Delay (500, token).ContinueWith ((t) => {
					if (token.IsCancellationRequested)
						return;
					Runtime.RunInMainThread (() => {
						if (token.IsCancellationRequested)
							return;
						if (IsPaused)//If session is already paused(stepping finished in time), don't switch
							return;
						HandleStopQueue ();
					});
				});
			}
		}

		public static Backtrace CurrentCallStack {
			get { return currentBacktrace; }
		}

		public static SourceLocation NextStatementLocation {
			get {
				SourceLocation location = null;

				if (IsPaused)
					nextStatementLocations.TryGetValue (ActiveThread.Id, out location);

				return location;
			}
		}

		public static StackFrame CurrentFrame {
			get {
				if (currentBacktrace != null && currentFrame != -1)
					return currentBacktrace.GetFrame (currentFrame);

				return null;
			}
		}

		/// <summary>
		/// The deepest stack frame with source above the CurrentFrame
		/// </summary>
		public static StackFrame GetCurrentVisibleFrame ()
		{
			if (currentBacktrace != null && currentFrame != -1) {
				for (int idx = currentFrame; idx < currentBacktrace.FrameCount; idx++) {
					var frame = currentBacktrace.GetFrame (currentFrame);
					if (!frame.IsExternalCode)
						return frame;
				}
			}
			return null;
		}

		public static int CurrentFrameIndex {
			get {
				return currentFrame;
			}
			set {
				if (currentBacktrace != null && value < currentBacktrace.FrameCount) {
					currentFrame = value;
					Runtime.RunInMainThread (delegate {
						NotifyCurrentFrameChanged ();
					});
				} else
					currentFrame = -1;
			}
		}

		public static ThreadInfo ActiveThread {
			get {
				return currentSession?.Session.ActiveThread;
			}
			set {
				if (currentSession != null && currentSession.Session.GetProcesses () [0].GetThreads ().Contains (value)) {
					currentSession.Session.ActiveThread = value;
					SetCurrentBacktrace (value.Backtrace);
				} else {
					foreach (var session in sessions) {
						if (session.Key.GetProcesses () [0].GetThreads ().Contains (value)) {
							currentSession = session.Value;
							currentSession.Session.ActiveThread = value;
							SetCurrentBacktrace (value.Backtrace);
							return;
						}
					}
					throw new Exception ("Thread not found in any of active sessions.");
				}
			}
		}

		static void SetCurrentBacktrace (Backtrace bt)
		{
			currentBacktrace = bt;
			if (currentBacktrace != null)
				currentFrame = 0;
			else
				currentFrame = -1;

			Runtime.RunInMainThread (delegate {
				NotifyCallStackChanged ();
				NotifyCurrentFrameChanged ();
				NotifyLocationChanged ();
			});
		}

		public static async void ShowCurrentExecutionLine ()
		{
			Runtime.AssertMainThread ();
			if (currentBacktrace != null) {
				var sf = GetCurrentVisibleFrame ();
				if (sf != null && !string.IsNullOrEmpty (sf.SourceLocation.FileName) && System.IO.File.Exists (sf.SourceLocation.FileName) && sf.SourceLocation.Line != -1) {
					Document document = await IdeApp.Workbench.OpenDocument (sf.SourceLocation.FileName, null, sf.SourceLocation.Line, 1, OpenDocumentOptions.Debugger);
					OnDisableConditionalCompilation (new DocumentEventArgs (document));
				}
			}
		}

		public static async void ShowNextStatement ()
		{
			Runtime.AssertMainThread ();
			var location = NextStatementLocation;

			if (location != null && System.IO.File.Exists (location.FileName)) {
				Document document = await IdeApp.Workbench.OpenDocument (location.FileName, null, location.Line, 1, OpenDocumentOptions.Debugger);
				OnDisableConditionalCompilation (new DocumentEventArgs (document));
			} else {
				ShowCurrentExecutionLine ();
			}
		}

		public static bool CanDebugCommand (ExecutionCommand command)
		{
			return GetFactoryForCommand (command) != null;
		}

		public static DebuggerEngine [] GetDebuggerEngines ()
		{
			if (engines == null) {
				var list = new List<DebuggerEngine> ();

				foreach (DebuggerEngineExtensionNode node in AddinManager.GetExtensionNodes (FactoriesPath))
					list.Add (new DebuggerEngine (node));

				engines = list.ToArray ();
			}

			return engines;
		}

		public static Dictionary<string, ExpressionEvaluatorExtensionNode> GetExpressionEvaluators ()
		{
			if (evaluators == null) {
				var evgs = new Dictionary<string, ExpressionEvaluatorExtensionNode> (StringComparer.InvariantCultureIgnoreCase);
				foreach (ExpressionEvaluatorExtensionNode node in AddinManager.GetExtensionNodes (EvaluatorsPath))
					evgs.Add (node.extension, node);

				evaluators = evgs;
			}
			return evaluators;
		}

		static DebuggerEngine GetFactoryForCommand (ExecutionCommand cmd)
		{
			DebuggerEngine supportedEngine = null;

			// Get the default engine for the command if available,
			// or the first engine that supports the command otherwise

			foreach (DebuggerEngine factory in GetDebuggerEngines ()) {
				if (factory.CanDebugCommand (cmd)) {
					if (factory.IsDefaultDebugger (cmd))
						return factory;
					if (supportedEngine == null)
						supportedEngine = factory;
				}
			}
			return supportedEngine;
		}

		static void OnLineCountChanged (object ob, LineCountEventArgs a)
		{
			lock (breakpoints) {
				foreach (var bp in breakpoints.GetBreakpoints ()) {
					if (bp.FileName == a.TextFile.Name) {
						if (bp.Line > a.LineNumber) {
							var startIndex = a.TextFile.GetPositionFromLineColumn (bp.Line, bp.Column);
							var endIndex = a.TextFile.GetPositionFromLineColumn (bp.Line + 1, 0) - 1;

							if (endIndex < startIndex)
								endIndex = startIndex;

							var text = a.TextFile.GetText (startIndex, endIndex);

							// If the line that has the breakpoint is deleted, delete the breakpoint, otherwise update the line #.
							if (bp.Line + a.LineCount >= a.LineNumber && !string.IsNullOrWhiteSpace (text))
								breakpoints.UpdateBreakpointLine (bp, bp.Line + a.LineCount);
							else
								breakpoints.Remove (bp);
						} else if (bp.Line == a.LineNumber && a.LineCount < 0)
							breakpoints.Remove (bp);
					}
				}
			}
		}

		static void OnStoreUserPrefs (object s, UserPreferencesEventArgs args)
		{
			var baseDir = (args.Item as Solution)?.BaseDirectory;
			lock (breakpoints)
				args.Properties.SetValue ("MonoDevelop.Ide.DebuggingService.Breakpoints", breakpoints.Save (baseDir));
			args.Properties.SetValue ("MonoDevelop.Ide.DebuggingService.PinnedWatches", pinnedWatches);
		}

		static Task OnLoadUserPrefs (object s, UserPreferencesEventArgs args)
		{
			var elem = args.Properties.GetValue<XmlElement> ("MonoDevelop.Ide.DebuggingService.Breakpoints") ?? args.Properties.GetValue<XmlElement> ("MonoDevelop.Ide.DebuggingService");

			if (elem != null) {
				var baseDir = (args.Item as Solution)?.BaseDirectory;
				lock (breakpoints)
					breakpoints.Load (elem, baseDir);
			}

			PinnedWatchStore wstore = args.Properties.GetValue<PinnedWatchStore> ("MonoDevelop.Ide.DebuggingService.PinnedWatches");
			if (wstore != null)
				pinnedWatches.LoadFrom (wstore);

			lock (breakpoints)
				pinnedWatches.BindAll (breakpoints);

			lock (breakpoints)
				pinnedWatches.SetAllLiveUpdateBreakpoints (breakpoints);

			return Task.FromResult (true);
		}

		static void OnSolutionClosed (object s, EventArgs args)
		{
			lock (breakpoints)
				breakpoints.Clear ();
		}

		static Microsoft.CodeAnalysis.ISymbol GetLanguageItem (MonoDevelop.Ide.Gui.Document document, SourceLocation sourceLocation, string identifier)
		{
			var textBuffer = document.GetContent<ITextBuffer> (true);
			if (textBuffer == null)
				return null;

			var currentSnapshot = textBuffer.CurrentSnapshot;
			var roslynDocument = currentSnapshot.GetOpenDocumentInCurrentContextWithChanges ();
			if (roslynDocument == null)
				return null;

			var model = roslynDocument.GetSemanticModelAsync ().WaitAndGetResult ();
			if (model == null)
				return null;

			int index = identifier.LastIndexOf ("`", System.StringComparison.Ordinal);
			int arity = 0;
			if (index != -1) {
				try {
					arity = int.Parse (identifier.Substring (index + 1));
				} catch {
					return null;
				}
				identifier = identifier.Remove (index);
			}
			var line = currentSnapshot.GetLineFromLineNumber (sourceLocation.Line - 1);
			foreach (var symbol in model.LookupSymbols (line.Start.Position + sourceLocation.Column - 1, name: identifier)) {
				var typeSymbol = symbol as Microsoft.CodeAnalysis.INamedTypeSymbol;
				if (typeSymbol != null && (arity == 0 || arity == typeSymbol.Arity)) {
					return symbol;
				}
				var namespaceSymbol = symbol as Microsoft.CodeAnalysis.INamespaceSymbol;
				if (namespaceSymbol != null) {
					return namespaceSymbol;
				}
			}
			return null;
		}

		static string ResolveType (string identifier, SourceLocation location)
		{
			Document doc = IdeApp.Workbench.GetDocument (location.FileName);
			if (doc != null) {
				Microsoft.CodeAnalysis.ISymbol rr = null;
				if (doc.GetContent<ITextEditorResolver> (true) is ITextEditorResolver textEditorResolver) {
					rr = textEditorResolver.GetLanguageItem (doc.Editor.LocationToOffset (location.Line, 1), identifier);
				} else {
					rr = GetLanguageItem (doc, location, identifier);
				}
				var ns = rr as Microsoft.CodeAnalysis.INamespaceSymbol;
				if (ns != null)
					return ns.ToDisplayString (Microsoft.CodeAnalysis.SymbolDisplayFormat.CSharpErrorMessageFormat);
				var result = rr as Microsoft.CodeAnalysis.INamedTypeSymbol;
				if (result != null && !(result.TypeKind == Microsoft.CodeAnalysis.TypeKind.Dynamic && result.ToDisplayString (Microsoft.CodeAnalysis.SymbolDisplayFormat.CSharpErrorMessageFormat) == "dynamic")) {
					return result.ToDisplayString (new Microsoft.CodeAnalysis.SymbolDisplayFormat (
						typeQualificationStyle: Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
						miscellaneousOptions:
						Microsoft.CodeAnalysis.SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
						Microsoft.CodeAnalysis.SymbolDisplayMiscellaneousOptions.UseSpecialTypes));
				}
			}
			return null;
		}

		public static ExpressionEvaluatorExtensionNode EvaluatorForExtension (string extension)
		{
			ExpressionEvaluatorExtensionNode result;

			if (GetExpressionEvaluators ().TryGetValue (extension, out result))
				return result;

			return null;
		}

		static IExpressionEvaluator OnGetExpressionEvaluator (string extension)
		{
			var info = EvaluatorForExtension (extension);

			return info != null ? info.Evaluator : null;
		}

		static Task<CompletionData> GetExpressionCompletionDataAsync (string exp, StackFrame frame, CancellationToken token)
		{
			Document doc = IdeApp.Workbench.GetDocument (frame.SourceLocation.FileName);
			if (doc == null)
				return null;
			var completionProvider = doc.GetContent<IDebuggerCompletionProvider> (true);
			if (completionProvider == null)
				return null;
			return completionProvider.GetExpressionCompletionDataAsync (exp, frame, token);
		}

		public static async Task<CompletionData> GetCompletionDataAsync (StackFrame frame, string exp, CancellationToken token = default (CancellationToken))
		{
			var result = await GetExpressionCompletionDataAsync (exp, frame, token);
			if (result != null)
				return result;
			return frame.GetExpressionCompletionData (exp);
		}

		public static Task<Span> GetBreakpointSpanAsync (ITextDocument document, int position, CancellationToken cancellationToken = default (CancellationToken))
		{
			var doc = IdeApp.Workbench.GetDocument (document.FilePath);
			IBreakpointSpanResolver resolver = null;

			if (doc != null)
				resolver = doc.GetContent<IBreakpointSpanResolver> ();

			resolver = resolver ?? new DefaultBreakpointSpanResolver ();

			return resolver.GetBreakpointSpanAsync (document.TextBuffer, position, cancellationToken);
		}
	}

	class FeatureCheckerHandlerFactory : IExecutionHandler
	{
		public DebuggerFeatures SupportedFeatures { get; set; }

		public bool CanExecute (ExecutionCommand command)
		{
			SupportedFeatures = DebuggingService.GetSupportedFeaturesForCommand (command);
			return SupportedFeatures != DebuggerFeatures.None;
		}

		public ProcessAsyncOperation Execute (ExecutionCommand cmd, OperationConsole console)
		{
			// Never called
			throw new NotImplementedException ();
		}
	}

	class InternalDebugExecutionHandler : IExecutionHandler
	{
		readonly DebuggerEngine engine;

		public InternalDebugExecutionHandler (DebuggerEngine engine)
		{
			this.engine = engine;
		}

		public bool CanExecute (ExecutionCommand command)
		{
			return engine.CanDebugCommand (command);
		}

		public ProcessAsyncOperation Execute (ExecutionCommand command, OperationConsole console)
		{
			return DebuggingService.Run (command, console, engine);
		}
	}

	class StatusBarConnectionDialog : IConnectionDialog
	{
		#pragma warning disable 67 //never used
		public event EventHandler UserCancelled;
		#pragma warning restore 67

		public void SetMessage (DebuggerStartInfo dsi, string message, bool listening, int attemptNumber)
		{
			Gtk.Application.Invoke ((o, args) => {
				IdeApp.Workbench.StatusBar.ShowMessage (Ide.Gui.Stock.StatusConnecting, message);
			});
		}

		public void Dispose ()
		{
			Gtk.Application.Invoke ((o, args) => {
				IdeApp.Workbench.StatusBar.ShowReady ();
			});
		}
	}

	class GtkConnectionDialog : IConnectionDialog
	{
		static readonly string DefaultListenMessage = GettextCatalog.GetString ("Waiting for debugger to connect...");
		System.Threading.CancellationTokenSource cts;
		bool disposed;

		public event EventHandler UserCancelled;

		public void SetMessage (DebuggerStartInfo dsi, string message, bool listening, int attemptNumber)
		{
			//FIXME: we don't support changing the message
			if (disposed || cts != null)
				return;

			cts = new System.Threading.CancellationTokenSource ();

			//MessageService is threadsafe but we want this to be async
			Gtk.Application.Invoke ((o, args) => {
				RunDialog (message);
			});
		}

		void RunDialog (string message)
		{
			if (disposed)
				return;

			string title;

			if (message == null) {
				title = GettextCatalog.GetString ("Waiting for debugger");
			} else {
				message = message.Trim ();
				int i = message.IndexOfAny (new [] { '\n', '\r' });
				if (i > 0) {
					title = message.Substring (0, i).Trim ();
					message = message.Substring (i).Trim ();
				} else {
					title = message;
					message = null;
				}
			}

			var gm = new GenericMessage (title, message, cts.Token);
			gm.Buttons.Add (AlertButton.Cancel);
			gm.DefaultButton = 0;
			MessageService.GenericAlert (gm);
			cts = null;

			if (!disposed && UserCancelled != null) {
				UserCancelled (null, null);
			}
		}

		public void Dispose ()
		{
			if (disposed)
				return;
			disposed = true;
			var c = cts;
			if (c != null)
				c.Cancel ();
		}
	}
}