-
Notifications
You must be signed in to change notification settings - Fork 29.5k
/
debugService.ts
1184 lines (996 loc) · 48.4 KB
/
debugService.ts
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.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { Event, Emitter } from 'vs/base/common/event';
import * as resources from 'vs/base/common/resources';
import { URI as uri } from 'vs/base/common/uri';
import { first, distinct } from 'vs/base/common/arrays';
import { isObject, isUndefinedOrNull } from 'vs/base/common/types';
import * as errors from 'vs/base/common/errors';
import severity from 'vs/base/common/severity';
import { TPromise } from 'vs/base/common/winjs.base';
import * as aria from 'vs/base/browser/ui/aria/aria';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, RawObjectReplElement } from 'vs/workbench/parts/debug/common/debugModel';
import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel';
import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions';
import { ConfigurationManager } from 'vs/workbench/parts/debug/electron-browser/debugConfigurationManager';
import Constants from 'vs/workbench/parts/markers/electron-browser/constants';
import { ITaskService, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService';
import { TaskError } from 'vs/workbench/parts/tasks/common/taskSystem';
import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL, EXTENSION_RELOAD_BROADCAST_CHANNEL, EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL } from 'vs/platform/extensions/common/extensionHost';
import { IBroadcastService } from 'vs/platform/broadcast/electron-browser/broadcastService';
import { IRemoteConsoleLog, parse, getFirstFrame } from 'vs/base/node/console';
import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/parts/tasks/common/tasks';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IAction, Action } from 'vs/base/common/actions';
import { deepClone, equals } from 'vs/base/common/objects';
import { DebugSession } from 'vs/workbench/parts/debug/electron-browser/debugSession';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IReplElementSource, IEnablement, IBreakpoint, IBreakpointData, IExpression, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent } from 'vs/workbench/parts/debug/common/debug';
import { isExtensionHostDebugging } from 'vs/workbench/parts/debug/common/debugUtils';
const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';
const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';
const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';
const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';
const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';
function once(kind: TaskEventKind, event: Event<TaskEvent>): Event<TaskEvent> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
if (e.kind === kind) {
result.dispose();
return listener.call(thisArgs, e);
}
}, null, disposables);
return result;
};
}
const enum TaskRunResult {
Failure,
Success
}
export class DebugService implements IDebugService {
_serviceBrand: any;
private readonly _onDidChangeState: Emitter<State>;
private readonly _onDidNewSession: Emitter<IDebugSession>;
private readonly _onWillNewSession: Emitter<IDebugSession>;
private readonly _onDidEndSession: Emitter<IDebugSession>;
private model: DebugModel;
private viewModel: ViewModel;
private configurationManager: ConfigurationManager;
private allSessions = new Map<string, IDebugSession>();
private toDispose: IDisposable[];
private debugType: IContextKey<string>;
private debugState: IContextKey<string>;
private inDebugMode: IContextKey<boolean>;
private breakpointsToSendOnResourceSaved: Set<string>;
private initializing = false;
private previousState: State;
constructor(
@IStorageService private storageService: IStorageService,
@IEditorService private editorService: IEditorService,
@ITextFileService private textFileService: ITextFileService,
@IViewletService private viewletService: IViewletService,
@IPanelService private panelService: IPanelService,
@INotificationService private notificationService: INotificationService,
@IDialogService private dialogService: IDialogService,
@IPartService private partService: IPartService,
@IWindowService private windowService: IWindowService,
@IBroadcastService private broadcastService: IBroadcastService,
@ITelemetryService private telemetryService: ITelemetryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IInstantiationService private instantiationService: IInstantiationService,
@IExtensionService private extensionService: IExtensionService,
@IMarkerService private markerService: IMarkerService,
@ITaskService private taskService: ITaskService,
@IFileService private fileService: IFileService,
@IConfigurationService private configurationService: IConfigurationService,
) {
this.toDispose = [];
this.breakpointsToSendOnResourceSaved = new Set<string>();
this._onDidChangeState = new Emitter<State>();
this._onDidNewSession = new Emitter<IDebugSession>();
this._onWillNewSession = new Emitter<IDebugSession>();
this._onDidEndSession = new Emitter<IDebugSession>();
this.configurationManager = this.instantiationService.createInstance(ConfigurationManager);
this.toDispose.push(this.configurationManager);
this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);
this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);
this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);
this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),
this.loadExceptionBreakpoints(), this.loadWatchExpressions(), this.textFileService);
this.toDispose.push(this.model);
this.viewModel = new ViewModel(contextKeyService);
this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e)));
this.lifecycleService.onShutdown(this.store, this);
this.lifecycleService.onShutdown(this.dispose, this);
this.toDispose.push(this.broadcastService.onBroadcast(broadcast => {
const session = this.getSession(broadcast.payload.debugId);
if (session) {
switch (broadcast.channel) {
case EXTENSION_ATTACH_BROADCAST_CHANNEL:
// EH was started in debug mode -> attach to it
session.configuration.request = 'attach';
session.configuration.port = broadcast.payload.port;
this.launchOrAttachToSession(session);
break;
case EXTENSION_TERMINATE_BROADCAST_CHANNEL:
// EH was terminated
session.disconnect();
break;
case EXTENSION_LOG_BROADCAST_CHANNEL:
// extension logged output -> show it in REPL
this.addToRepl(session, broadcast.payload.logEntry);
break;
}
}
}, this));
this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => {
this.onStateChange();
}));
this.toDispose.push(this.viewModel.onDidFocusSession(session => {
const id = session ? session.getId() : undefined;
this.model.setBreakpointsSessionId(id);
this.onStateChange();
}));
}
getSession(sessionId: string): IDebugSession {
return this.allSessions.get(sessionId);
}
getModel(): IDebugModel {
return this.model;
}
getViewModel(): IViewModel {
return this.viewModel;
}
getConfigurationManager(): IConfigurationManager {
return this.configurationManager;
}
sourceIsNotAvailable(uri: uri): void {
this.model.sourceIsNotAvailable(uri);
}
dispose(): void {
this.toDispose = dispose(this.toDispose);
}
//---- state management
get state(): State {
const focusedSession = this.viewModel.focusedSession;
if (focusedSession) {
return focusedSession.state;
}
return this.initializing ? State.Initializing : State.Inactive;
}
private startInitializingState() {
if (!this.initializing) {
this.initializing = true;
this.onStateChange();
}
}
private endInitializingState() {
if (this.initializing) {
this.initializing = false;
this.onStateChange();
}
}
private onStateChange(): void {
const state = this.state;
if (this.previousState !== state) {
const stateLabel = State[state];
if (stateLabel) {
this.debugState.set(stateLabel.toLowerCase());
this.inDebugMode.set(state !== State.Inactive);
}
this.previousState = state;
this._onDidChangeState.fire(state);
}
}
get onDidChangeState(): Event<State> {
return this._onDidChangeState.event;
}
get onDidNewSession(): Event<IDebugSession> {
return this._onDidNewSession.event;
}
get onWillNewSession(): Event<IDebugSession> {
return this._onWillNewSession.event;
}
get onDidEndSession(): Event<IDebugSession> {
return this._onDidEndSession.event;
}
//---- life cycle management
/**
* main entry point
* properly manages compounds, checks for errors and handles the initializing state.
*/
startDebugging(launch: ILaunch, configOrName?: IConfig | string, noDebug = false, unresolvedConfig?: IConfig, ): TPromise<boolean> {
this.startInitializingState();
// make sure to save all files and that the configuration is up to date
return this.extensionService.activateByEvent('onDebug').then(() =>
this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() =>
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
// If it is the very first start debugging we need to clear the repl and our sessions map
if (this.model.getSessions().length === 0) {
this.removeReplExpressions();
this.allSessions.clear();
}
let config: IConfig, compound: ICompound;
if (!configOrName) {
configOrName = this.configurationManager.selectedConfiguration.name;
}
if (typeof configOrName === 'string' && launch) {
config = launch.getConfiguration(configOrName);
compound = launch.getCompound(configOrName);
const sessions = this.model.getSessions();
const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName);
if (sessions.some(s => s.getName(false) === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) {
return Promise.reject(new Error(alreadyRunningMessage));
}
if (compound && compound.configurations && sessions.some(p => compound.configurations.indexOf(p.getName(false)) !== -1)) {
return Promise.reject(new Error(alreadyRunningMessage));
}
} else if (typeof configOrName !== 'string') {
config = configOrName;
}
if (compound) {
// we are starting a compound debug, first do some error checking and than start each configuration in the compound
if (!compound.configurations) {
return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] },
"Compound must have \"configurations\" attribute set in order to start multiple configurations.")));
}
return Promise.all(compound.configurations.map(configData => {
const name = typeof configData === 'string' ? configData : configData.name;
if (name === compound.name) {
return Promise.resolve(false);
}
let launchForName: ILaunch;
if (typeof configData === 'string') {
const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name));
if (launchesContainingName.length === 1) {
launchForName = launchesContainingName[0];
} else if (launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) {
// If there are multiple launches containing the configuration give priority to the configuration in the current launch
launchForName = launch;
} else {
return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name)
: nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)));
}
} else if (configData.folder) {
const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name));
if (launchesMatchingConfigData.length === 1) {
launchForName = launchesMatchingConfigData[0];
} else {
return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)));
}
}
return this.createSession(launchForName, launchForName.getConfiguration(name), unresolvedConfig, noDebug);
})).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully
}
if (configOrName && !config) {
const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) :
nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist.");
return Promise.reject(new Error(message));
}
return this.createSession(launch, config, unresolvedConfig, noDebug);
})
))).then(success => {
// make sure to get out of initializing state, and propagate the result
this.endInitializingState();
return success;
}, err => {
this.endInitializingState();
return Promise.reject(err);
});
}
/**
* gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks
*/
private createSession(launch: ILaunch, config: IConfig, unresolvedConfig: IConfig, noDebug: boolean): TPromise<boolean> {
// We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes.
// Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config.
let type: string;
if (config) {
type = config.type;
} else {
// a no-folder workspace has no launch.config
config = Object.create(null);
}
unresolvedConfig = unresolvedConfig || deepClone(config);
if (noDebug) {
config.noDebug = true;
}
const debuggerThenable: Thenable<void> = type ? Promise.resolve(null) : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; });
return debuggerThenable.then(() =>
this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config).then(config => {
// a falsy config indicates an aborted launch
if (config && config.type) {
return this.substituteVariables(launch, config).then(resolvedConfig => {
if (!resolvedConfig) {
// User canceled resolving of interactive variables, silently return
return false;
}
if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) {
let message: string;
if (config.request !== 'attach' && config.request !== 'launch') {
message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request)
: nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request');
} else {
message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) :
nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration.");
}
return this.showError(message).then(() => false);
}
const workspace = launch ? launch.workspace : undefined;
return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => {
if (result === TaskRunResult.Success) {
return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig });
}
return false;
});
}, err => {
if (err && err.message) {
return this.showError(err.message).then(() => false);
}
if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved on disk and that you have a debug extension installed for that file type."))
.then(() => false);
}
return launch && launch.openConfigFile(false, true).then(() => false);
});
}
if (launch && type && config === null) { // show launch.json only for "config" being "null".
return launch.openConfigFile(false, true, type).then(() => false);
}
return false;
})
);
}
/**
* instantiates the new session, initializes the session, registers session listeners and reports telemetry
*/
private doCreateSession(root: IWorkspaceFolder, configuration: { resolved: IConfig, unresolved: IConfig }): TPromise<boolean> {
const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model);
this.allSessions.set(session.getId(), session);
// register listeners as the very first thing!
this.registerSessionListeners(session);
// since the Session is now properly registered under its ID and hooked, we can announce it
// this event doesn't go to extensions
this._onWillNewSession.fire(session);
return this.launchOrAttachToSession(session).then(() => {
// since the initialized response has arrived announce the new Session (including extensions)
this._onDidNewSession.fire(session);
const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions;
if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) {
this.panelService.openPanel(REPL_ID, false);
}
const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug;
// Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug'
if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) {
this.viewletService.openViewlet(VIEWLET_ID);
}
this.viewModel.firstSessionStart = false;
this.debugType.set(session.configuration.type);
if (this.model.getSessions().length > 1) {
this.viewModel.setMultiSessionView(true);
}
return this.telemetryDebugSessionStart(root, session.configuration.type);
}).then(() => true, (error: Error | string) => {
if (errors.isPromiseCanceledError(error)) {
// don't show 'canceled' error messages to the user #7906
return Promise.resolve(undefined);
}
// Show the repl if some error got logged there #5870
if (this.model.getReplElements().length > 0) {
this.panelService.openPanel(REPL_ID, false);
}
if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) {
// ignore attach timeouts in auto attach mode
return Promise.resolve(undefined);
}
const errorMessage = error instanceof Error ? error.message : error;
this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage);
return this.showError(errorMessage, errors.isErrorWithActions(error) ? error.actions : []).then(() => false);
});
}
private launchOrAttachToSession(session: IDebugSession, focus = true): TPromise<void> {
const dbgr = this.configurationManager.getDebugger(session.configuration.type);
return session.initialize(dbgr).then(() => {
return session.launchOrAttach(session.configuration).then(() => {
if (focus) {
this.focusStackFrame(undefined, undefined, session);
}
});
}).then(undefined, err => {
session.shutdown();
return Promise.reject(err);
});
}
private registerSessionListeners(session: IDebugSession): void {
this.toDispose.push(session.onDidChangeState(() => {
if (session.state === State.Running && this.viewModel.focusedSession && this.viewModel.focusedSession.getId() === session.getId()) {
this.focusStackFrame(undefined);
}
}));
this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => {
if (adapterExitEvent.error) {
this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString()));
}
// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905
if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {
this.broadcastService.broadcast({
channel: EXTENSION_CLOSE_EXTHOST_BROADCAST_CHANNEL,
payload: [session.root.uri.toString()]
});
}
this.telemetryDebugSessionStop(session, adapterExitEvent);
if (session.configuration.postDebugTask) {
this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err =>
this.notificationService.error(err)
);
}
session.shutdown();
this._onDidEndSession.fire(session);
const focusedSession = this.viewModel.focusedSession;
if (focusedSession && focusedSession.getId() === session.getId()) {
this.focusStackFrame(undefined);
}
if (this.model.getSessions().length === 0) {
this.debugType.reset();
this.viewModel.setMultiSessionView(false);
if (this.partService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) {
this.viewletService.openViewlet(EXPLORER_VIEWLET_ID);
}
}
}));
}
restartSession(session: IDebugSession, restartData?: any): TPromise<any> {
return this.textFileService.saveAll().then(() => {
// Do not run preLaunch and postDebug tasks for automatic restarts
const isAutoRestart = !!restartData;
const taskThenable: Thenable<TaskRunResult> = isAutoRestart ? Promise.resolve(TaskRunResult.Success) :
this.runTask(session.root, session.configuration.postDebugTask).then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask));
return taskThenable.then(taskRunResult => {
if (taskRunResult !== TaskRunResult.Success) {
return;
}
if (session.capabilities.supportsRestartRequest) {
return session.restart().then(() => void 0);
}
const shouldFocus = this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId();
if (isExtensionHostDebugging(session.configuration) && session.root) {
return this.broadcastService.broadcast({
channel: EXTENSION_RELOAD_BROADCAST_CHANNEL,
payload: [session.root.uri.toString()]
});
}
// If the restart is automatic -> disconnect, otherwise -> terminate #55064
return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => {
return new Promise<void>((c, e) => {
setTimeout(() => {
// Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration
let needsToSubstitute = false;
let unresolved: IConfig;
const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined;
if (launch) {
unresolved = launch.getConfiguration(session.configuration.name);
if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) {
// Take the type from the session since the debug extension might overwrite it #21316
unresolved.type = session.configuration.type;
unresolved.noDebug = session.configuration.noDebug;
needsToSubstitute = true;
}
}
let substitutionThenable: Thenable<IConfig> = Promise.resolve(session.configuration);
if (needsToSubstitute) {
substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved)
.then(resolved => this.substituteVariables(launch, resolved));
}
substitutionThenable.then(resolved => {
session.setConfiguration({ resolved, unresolved });
session.configuration.__restart = restartData;
this.launchOrAttachToSession(session, shouldFocus).then(() => {
this._onDidNewSession.fire(session);
c(null);
}, err => e(err));
});
}, 300);
});
});
});
});
}
stopSession(session: IDebugSession): TPromise<any> {
if (session) {
return session.terminate();
}
const sessions = this.model.getSessions();
return Promise.all(sessions.map(s => s.terminate()));
}
private substituteVariables(launch: ILaunch | undefined, config: IConfig): TPromise<IConfig> {
const dbg = this.configurationManager.getDebugger(config.type);
if (dbg) {
let folder: IWorkspaceFolder = undefined;
if (launch && launch.workspace) {
folder = launch.workspace;
} else {
const folders = this.contextService.getWorkspace().folders;
if (folders.length === 1) {
folder = folders[0];
}
}
return dbg.substituteVariables(folder, config).then(config => {
return config;
}, (err: Error) => {
this.showError(err.message);
return undefined; // bail out
});
}
return Promise.resolve(config);
}
private showError(message: string, actions: IAction[] = []): TPromise<void> {
const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL);
actions.push(configureAction);
return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => {
if (choice < actions.length) {
return actions[choice].run();
}
return void 0;
});
}
//---- task management
private runTaskAndCheckErrors(root: IWorkspaceFolder, taskId: string | TaskIdentifier): TPromise<TaskRunResult> {
const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success));
return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => {
const errorCount = taskId ? this.markerService.getStatistics().errors : 0;
const successExitCode = taskSummary && taskSummary.exitCode === 0;
const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0;
if (successExitCode || (errorCount === 0 && !failureExitCode)) {
return <any>TaskRunResult.Success;
}
const taskLabel = typeof taskId === 'string' ? taskId : taskId.name;
const message = errorCount > 1
? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", taskLabel)
: errorCount === 1
? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", taskLabel)
: nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode);
const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => {
return this.panelService.openPanel(Constants.MARKERS_PANEL_ID).then(() => TaskRunResult.Failure);
});
return this.showError(message, [debugAnywayAction, showErrorsAction]);
}, (err: TaskError) => {
return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]);
});
}
private runTask(root: IWorkspaceFolder, taskId: string | TaskIdentifier): TPromise<ITaskSummary> {
if (!taskId) {
return Promise.resolve(null);
}
if (!root) {
return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type)));
}
// run a task before starting a debug session
return this.taskService.getTask(root, taskId).then(task => {
if (!task) {
const errorMessage = typeof taskId === 'string'
? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId)
: nls.localize('DebugTaskNotFound', "Could not find the specified task.");
return Promise.reject(errors.create(errorMessage));
}
// If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340
let taskStarted = false;
const promise = this.taskService.getActiveTasks().then(tasks => {
if (tasks.filter(t => t._id === task._id).length) {
// task is already running - nothing to do.
return Promise.resolve(null);
}
const taskPromise = this.taskService.run(task);
if (task.isBackground) {
return new Promise((c, e) => once(TaskEventKind.Inactive, this.taskService.onDidStateChange)(() => {
taskStarted = true;
c(null);
}));
}
return taskPromise;
});
return new Promise((c, e) => {
promise.then(result => {
taskStarted = true;
c(result);
}, error => e(error));
setTimeout(() => {
if (!taskStarted) {
const errorMessage = typeof taskId === 'string'
? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.")
: nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId));
e({ severity: severity.Error, message: errorMessage });
}
}, 10000);
});
});
}
//---- focus management
tryToAutoFocusStackFrame(thread: IThread): TPromise<any> {
const callStack = thread.getCallStack();
if (!callStack.length || (this.viewModel.focusedStackFrame && this.viewModel.focusedStackFrame.thread.getId() === thread.getId())) {
return Promise.resolve(null);
}
// focus first stack frame from top that has source location if no other stack frame is focused
const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, undefined);
if (!stackFrameToFocus) {
return Promise.resolve(null);
}
this.focusStackFrame(stackFrameToFocus);
if (thread.stoppedDetails) {
if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
this.viewletService.openViewlet(VIEWLET_ID);
}
this.windowService.focusWindow();
aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", thread.stoppedDetails.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.range.startLineNumber));
}
return stackFrameToFocus.openInEditor(this.editorService, true);
}
focusStackFrame(stackFrame: IStackFrame, thread?: IThread, session?: IDebugSession, explicit?: boolean): void {
if (!session) {
if (stackFrame || thread) {
session = stackFrame ? stackFrame.thread.session : thread.session;
} else {
const sessions = this.model.getSessions();
session = sessions.length ? sessions[0] : undefined;
}
}
if (!thread) {
if (stackFrame) {
thread = stackFrame.thread;
} else {
const threads = session ? session.getAllThreads() : undefined;
thread = threads && threads.length ? threads[0] : undefined;
}
}
if (!stackFrame) {
if (thread) {
const callStack = thread.getCallStack();
stackFrame = callStack && callStack.length ? callStack[0] : null;
}
}
this.viewModel.setFocus(stackFrame, thread, session, explicit);
}
//---- REPL
addReplExpression(name: string): TPromise<void> {
return this.model.addReplExpression(this.viewModel.focusedSession, this.viewModel.focusedStackFrame, name)
// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
.then(() => this.focusStackFrame(this.viewModel.focusedStackFrame, this.viewModel.focusedThread, this.viewModel.focusedSession));
}
removeReplExpressions(): void {
this.model.removeReplExpressions();
}
private addToRepl(session: IDebugSession, extensionOutput: IRemoteConsoleLog) {
let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info;
const { args, stack } = parse(extensionOutput);
let source: IReplElementSource;
if (stack) {
const frame = getFirstFrame(stack);
if (frame) {
source = {
column: frame.column,
lineNumber: frame.line,
source: session.getSource({
name: resources.basenameOrAuthority(frame.uri),
path: frame.uri.fsPath
})
};
}
}
// add output for each argument logged
let simpleVals: any[] = [];
for (let i = 0; i < args.length; i++) {
let a = args[i];
// undefined gets printed as 'undefined'
if (typeof a === 'undefined') {
simpleVals.push('undefined');
}
// null gets printed as 'null'
else if (a === null) {
simpleVals.push('null');
}
// objects & arrays are special because we want to inspect them in the REPL
else if (isObject(a) || Array.isArray(a)) {
// flush any existing simple values logged
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' '), sev, source);
simpleVals = [];
}
// show object
this.logToRepl(new RawObjectReplElement((<any>a).prototype, a, undefined, nls.localize('snapshotObj', "Only primitive values are shown for this object.")), sev, source);
}
// string: watch out for % replacement directive
// string substitution and formatting @ https://developer.chrome.com/devtools/docs/console
else if (typeof a === 'string') {
let buf = '';
for (let j = 0, len = a.length; j < len; j++) {
if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd' || a[j + 1] === 'O')) {
i++; // read over substitution
buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace
j++; // read over directive
} else {
buf += a[j];
}
}
simpleVals.push(buf);
}
// number or boolean is joined together
else {
simpleVals.push(a);
}
}
// flush simple values
// always append a new line for output coming from an extension such that separate logs go to separate lines #23695
if (simpleVals.length) {
this.logToRepl(simpleVals.join(' ') + '\n', sev, source);
}
}
logToRepl(value: string | IExpression, sev = severity.Info, source?: IReplElementSource): void {
const clearAnsiSequence = '\u001b[2J';
if (typeof value === 'string' && value.indexOf(clearAnsiSequence) >= 0) {
// [2J is the ansi escape sequence for clearing the display http://ascii-table.com/ansi-escape-sequences.php
this.model.removeReplExpressions();
this.model.appendToRepl(nls.localize('consoleCleared', "Console was cleared"), severity.Ignore);
value = value.substr(value.lastIndexOf(clearAnsiSequence) + clearAnsiSequence.length);
}
this.model.appendToRepl(value, sev, source);
}
//---- watches
addWatchExpression(name: string): void {
const we = this.model.addWatchExpression(name);
this.viewModel.setSelectedExpression(we);
}
renameWatchExpression(id: string, newName: string): void {
return this.model.renameWatchExpression(id, newName);
}
moveWatchExpression(id: string, position: number): void {
this.model.moveWatchExpression(id, position);
}
removeWatchExpressions(id?: string): void {
this.model.removeWatchExpressions(id);
}
//---- breakpoints
enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): TPromise<void> {
if (breakpoint) {
this.model.setEnablement(breakpoint, enable);
if (breakpoint instanceof Breakpoint) {
return this.sendBreakpoints(breakpoint.uri);
} else if (breakpoint instanceof FunctionBreakpoint) {
return this.sendFunctionBreakpoints();
}
return this.sendExceptionBreakpoints();
}
this.model.enableOrDisableAllBreakpoints(enable);
return this.sendAllBreakpoints();
}
addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[]): TPromise<IBreakpoint[]> {
const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints);
breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath)));
return this.sendBreakpoints(uri).then(() => breakpoints);
}
updateBreakpoints(uri: uri, data: { [id: string]: DebugProtocol.Breakpoint }, sendOnResourceSaved: boolean): void {
this.model.updateBreakpoints(data);
if (sendOnResourceSaved) {
this.breakpointsToSendOnResourceSaved.add(uri.toString());
} else {
this.sendBreakpoints(uri);
}
}
removeBreakpoints(id?: string): TPromise<any> {
const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id);
toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath)));
const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri);
this.model.removeBreakpoints(toRemove);
return Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri)));
}
setBreakpointsActivated(activated: boolean): TPromise<void> {
this.model.setBreakpointsActivated(activated);
return this.sendAllBreakpoints();
}
addFunctionBreakpoint(name?: string, id?: string): void {
const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);
this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint);
}
renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> {
this.model.renameFunctionBreakpoint(id, newFunctionName);
return this.sendFunctionBreakpoints();
}
removeFunctionBreakpoints(id?: string): TPromise<void> {
this.model.removeFunctionBreakpoints(id);
return this.sendFunctionBreakpoints();
}
sendAllBreakpoints(session?: IDebugSession): TPromise<any> {
return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session)))
.then(() => this.sendFunctionBreakpoints(session))
// send exception breakpoints at the end since some debug adapters rely on the order
.then(() => this.sendExceptionBreakpoints(session));
}
private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): TPromise<void> {
const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true });
return this.sendToOneOrAllSessions(session, s => {
return s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified).then(data => {
if (data) {
this.model.setBreakpointSessionData(s.getId(), data);
}
});
});
}
private sendFunctionBreakpoints(session?: IDebugSession): TPromise<void> {