debugSession.ts 32.7 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

I
isidor 已提交
6
import { URI } from 'vs/base/common/uri';
7
import * as resources from 'vs/base/common/resources';
I
isidor 已提交
8 9 10 11
import * as nls from 'vs/nls';
import * as platform from 'vs/base/common/platform';
import severity from 'vs/base/common/severity';
import { Event, Emitter } from 'vs/base/common/event';
12
import { CompletionItem, completionKindFromString } from 'vs/editor/common/modes';
I
isidor 已提交
13
import { Position, IPosition } from 'vs/editor/common/core/position';
I
isidor 已提交
14
import * as aria from 'vs/base/browser/ui/aria/aria';
15
import { IDebugSession, IConfig, IThread, IRawModelUpdate, IDebugService, IRawStoppedDetails, State, LoadedSourceEvent, IFunctionBreakpoint, IExceptionBreakpoint, IBreakpoint, IExceptionInfo, AdapterEndEvent, IDebugger, VIEWLET_ID, IDebugConfiguration, IReplElement, IStackFrame, IExpression, IReplElementSource, IDataBreakpoint, IDebugSessionOptions } from 'vs/workbench/contrib/debug/common/debug';
16
import { Source } from 'vs/workbench/contrib/debug/common/debugSource';
17
import { mixin } from 'vs/base/common/objects';
18
import { Thread, ExpressionContainer, DebugModel } from 'vs/workbench/contrib/debug/common/debugModel';
A
Andre Weinand 已提交
19
import { RawDebugSession } from 'vs/workbench/contrib/debug/browser/rawDebugSession';
20
import { IProductService } from 'vs/platform/product/common/productService';
I
isidor 已提交
21
import { IWorkspaceFolder, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
I
isidor 已提交
22 23 24
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { generateUuid } from 'vs/base/common/uuid';
25
import { IHostService } from 'vs/workbench/services/host/browser/host';
26
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
I
isidor 已提交
27
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
A
Andre Weinand 已提交
28
import { normalizeDriveLetter } from 'vs/base/common/labels';
29
import { Range } from 'vs/editor/common/core/range';
I
isidor 已提交
30 31
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
32
import { ReplModel } from 'vs/workbench/contrib/debug/common/replModel';
33
import { onUnexpectedError } from 'vs/base/common/errors';
34
import { IOpenerService } from 'vs/platform/opener/common/opener';
35
import { variableSetEmitter } from 'vs/workbench/contrib/debug/browser/variablesView';
I
isidor 已提交
36
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
I
isidor 已提交
37
import { distinct } from 'vs/base/common/arrays';
I
isidor 已提交
38

39
export class DebugSession implements IDebugSession {
40

A
Andre Weinand 已提交
41
	private id: string;
42
	private _subId: string | undefined;
I
isidor 已提交
43
	private raw: RawDebugSession | undefined;
I
isidor 已提交
44
	private initialized = false;
45
	private _options: IDebugSessionOptions;
A
Andre Weinand 已提交
46

I
isidor 已提交
47 48
	private sources = new Map<string, Source>();
	private threads = new Map<number, Thread>();
I
isidor 已提交
49
	private cancellationMap = new Map<number, CancellationTokenSource[]>();
I
isidor 已提交
50
	private rawListeners: IDisposable[] = [];
I
isidor 已提交
51
	private fetchThreadsScheduler: RunOnceScheduler | undefined;
52
	private repl: ReplModel;
A
Andre Weinand 已提交
53

54
	private readonly _onDidChangeState = new Emitter<void>();
A
Andre Weinand 已提交
55 56
	private readonly _onDidEndAdapter = new Emitter<AdapterEndEvent>();

I
isidor 已提交
57
	private readonly _onDidLoadedSource = new Emitter<LoadedSourceEvent>();
A
Andre Weinand 已提交
58
	private readonly _onDidCustomEvent = new Emitter<DebugProtocol.Event>();
A
Andre Weinand 已提交
59

I
isidor 已提交
60
	private readonly _onDidChangeREPLElements = new Emitter<void>();
61

62 63 64
	private name: string | undefined;
	private readonly _onDidChangeName = new Emitter<string>();

I
isidor 已提交
65
	constructor(
I
isidor 已提交
66
		private _configuration: { resolved: IConfig, unresolved: IConfig | undefined },
I
isidor 已提交
67
		public root: IWorkspaceFolder | undefined,
68
		private model: DebugModel,
69
		options: IDebugSessionOptions | undefined,
70 71
		@IDebugService private readonly debugService: IDebugService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
72
		@IHostService private readonly hostService: IHostService,
73 74
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IViewletService private readonly viewletService: IViewletService,
A
Andre Weinand 已提交
75
		@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
A
Andre Weinand 已提交
76
		@IProductService private readonly productService: IProductService,
77
		@IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService,
78
		@IOpenerService private readonly openerService: IOpenerService
I
isidor 已提交
79
	) {
A
Andre Weinand 已提交
80
		this.id = generateUuid();
81 82 83 84 85 86
		this._options = options || {};
		if (this.hasSeparateRepl()) {
			this.repl = new ReplModel();
		} else {
			this.repl = (this.parentSession as DebugSession).repl;
		}
87
		this.repl.onDidChangeElements(() => this._onDidChangeREPLElements.fire());
88 89
	}

A
Andre Weinand 已提交
90 91 92 93
	getId(): string {
		return this.id;
	}

94 95 96 97 98 99 100 101
	setSubId(subId: string | undefined) {
		this._subId = subId;
	}

	get subId(): string | undefined {
		return this._subId;
	}

I
isidor 已提交
102
	get configuration(): IConfig {
103 104 105
		return this._configuration.resolved;
	}

I
isidor 已提交
106
	get unresolvedConfiguration(): IConfig | undefined {
107 108 109
		return this._configuration.unresolved;
	}

I
isidor 已提交
110
	get parentSession(): IDebugSession | undefined {
111
		return this._options.parentSession;
I
isidor 已提交
112 113
	}

I
isidor 已提交
114
	setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig | undefined }) {
I
isidor 已提交
115 116 117
		this._configuration = configuration;
	}

I
isidor 已提交
118 119
	getLabel(): string {
		const includeRoot = this.workspaceContextService.getWorkspace().folders.length > 1;
120 121 122 123 124 125 126
		const name = this.name || this.configuration.name;
		return includeRoot && this.root ? `${name} (${resources.basenameOrAuthority(this.root.uri)})` : name;
	}

	setName(name: string): void {
		this.name = name;
		this._onDidChangeName.fire(name);
I
isidor 已提交
127 128 129
	}

	get state(): State {
I
isidor 已提交
130 131 132
		if (!this.initialized) {
			return State.Initializing;
		}
133 134 135 136
		if (!this.raw) {
			return State.Inactive;
		}

137
		const focusedThread = this.debugService.getViewModel().focusedThread;
I
isidor 已提交
138
		if (focusedThread && focusedThread.session === this) {
139 140 141 142
			return focusedThread.stopped ? State.Stopped : State.Running;
		}
		if (this.getAllThreads().some(t => t.stopped)) {
			return State.Stopped;
A
Andre Weinand 已提交
143
		}
144

145
		return State.Running;
A
Andre Weinand 已提交
146 147 148
	}

	get capabilities(): DebugProtocol.Capabilities {
149
		return this.raw ? this.raw.capabilities : Object.create(null);
150 151
	}

A
Andre Weinand 已提交
152
	//---- events
153
	get onDidChangeState(): Event<void> {
I
isidor 已提交
154
		return this._onDidChangeState.event;
155 156
	}

A
Andre Weinand 已提交
157 158 159 160
	get onDidEndAdapter(): Event<AdapterEndEvent> {
		return this._onDidEndAdapter.event;
	}

I
isidor 已提交
161 162 163 164
	get onDidChangeReplElements(): Event<void> {
		return this._onDidChangeREPLElements.event;
	}

165 166 167 168
	get onDidChangeName(): Event<string> {
		return this._onDidChangeName.event;
	}

A
Andre Weinand 已提交
169 170
	//---- DAP events

A
Andre Weinand 已提交
171
	get onDidCustomEvent(): Event<DebugProtocol.Event> {
I
isidor 已提交
172 173 174
		return this._onDidCustomEvent.event;
	}

A
Andre Weinand 已提交
175 176
	get onDidLoadedSource(): Event<LoadedSourceEvent> {
		return this._onDidLoadedSource.event;
177 178
	}

A
Andre Weinand 已提交
179 180 181 182 183
	//---- DAP requests

	/**
	 * create and initialize a new debug adapter for this session
	 */
J
Johannes Rieken 已提交
184
	initialize(dbgr: IDebugger): Promise<void> {
185

186
		if (this.raw) {
187
			// if there was already a connection make sure to remove old listeners
188
			this.shutdown();
I
isidor 已提交
189
		}
190

I
isidor 已提交
191
		return dbgr.getCustomTelemetryService().then(customTelemetryService => {
192

A
Andre Weinand 已提交
193
			return dbgr.createDebugAdapter(this).then(debugAdapter => {
A
Andre Weinand 已提交
194

195
				this.raw = new RawDebugSession(debugAdapter, dbgr, this.telemetryService, customTelemetryService, this.extensionHostDebugService, this.openerService);
A
Andre Weinand 已提交
196

I
isidor 已提交
197
				return this.raw.start().then(() => {
A
Andre Weinand 已提交
198 199 200

					this.registerListeners();

I
isidor 已提交
201
					return this.raw!.initialize({
A
Andre Weinand 已提交
202
						clientID: 'vscode',
203
						clientName: this.productService.nameLong,
A
Andre Weinand 已提交
204 205 206 207 208 209 210 211
						adapterID: this.configuration.type,
						pathFormat: 'path',
						linesStartAt1: true,
						columnsStartAt1: true,
						supportsVariableType: true, // #8858
						supportsVariablePaging: true, // #9537
						supportsRunInTerminalRequest: true, // #10574
						locale: platform.locale
212
					}).then(() => {
I
isidor 已提交
213
						this.initialized = true;
214
						this._onDidChangeState.fire();
I
isidor 已提交
215
						this.model.setExceptionBreakpoints(this.raw!.capabilities.exceptionBreakpointFilters || []);
A
Andre Weinand 已提交
216 217
					});
				});
I
isidor 已提交
218
			});
I
isidor 已提交
219 220 221 222
		}).then(undefined, err => {
			this.initialized = true;
			this._onDidChangeState.fire();
			return Promise.reject(err);
I
isidor 已提交
223 224 225
		});
	}

A
Andre Weinand 已提交
226 227 228
	/**
	 * launch or attach to the debuggee
	 */
229
	launchOrAttach(config: IConfig): Promise<void> {
230
		if (this.raw) {
A
Andre Weinand 已提交
231 232 233 234

			// __sessionID only used for EH debugging (but we add it always for now...)
			config.__sessionId = this.getId();

235
			return this.raw.launchOrAttach(config).then(result => {
R
Rob Lourens 已提交
236
				return undefined;
A
Andre Weinand 已提交
237 238
			});
		}
239
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
240 241 242 243 244
	}

	/**
	 * end the current debug adapter session
	 */
245
	terminate(restart = false): Promise<void> {
246
		if (this.raw) {
I
isidor 已提交
247
			this.cancelAllRequests();
248 249
			if (this.raw.capabilities.supportsTerminateRequest && this._configuration.resolved.request === 'launch') {
				return this.raw.terminate(restart).then(response => {
R
Rob Lourens 已提交
250
					return undefined;
A
Andre Weinand 已提交
251 252
				});
			}
253
			return this.raw.disconnect(restart).then(response => {
R
Rob Lourens 已提交
254
				return undefined;
A
Andre Weinand 已提交
255 256
			});
		}
257
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
258 259 260 261 262
	}

	/**
	 * end the current debug adapter session
	 */
263
	disconnect(restart = false): Promise<void> {
264
		if (this.raw) {
I
isidor 已提交
265
			this.cancelAllRequests();
266
			return this.raw.disconnect(restart).then(response => {
R
Rob Lourens 已提交
267
				return undefined;
A
Andre Weinand 已提交
268 269
			});
		}
270
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
271 272 273 274 275
	}

	/**
	 * restart debug adapter session
	 */
276
	restart(): Promise<void> {
277
		if (this.raw) {
I
isidor 已提交
278
			this.cancelAllRequests();
279
			return this.raw.restart().then(() => undefined);
A
Andre Weinand 已提交
280
		}
281
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
282 283
	}

284
	sendBreakpoints(modelUri: URI, breakpointsToSend: IBreakpoint[], sourceModified: boolean): Promise<void> {
A
Andre Weinand 已提交
285

286
		if (!this.raw) {
287
			return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
288 289
		}

290
		if (!this.raw.readyForBreakpoints) {
I
isidor 已提交
291
			return Promise.resolve(undefined);
A
Andre Weinand 已提交
292 293
		}

I
isidor 已提交
294
		const rawSource = this.getRawSource(modelUri);
A
Andre Weinand 已提交
295 296 297 298
		if (breakpointsToSend.length && !rawSource.adapterData) {
			rawSource.adapterData = breakpointsToSend[0].adapterData;
		}
		// Normalize all drive letters going out from vscode to debug adapters so we are consistent with our resolving #43959
I
isidor 已提交
299 300 301
		if (rawSource.path) {
			rawSource.path = normalizeDriveLetter(rawSource.path);
		}
A
Andre Weinand 已提交
302

303
		return this.raw.setBreakpoints({
A
Andre Weinand 已提交
304
			source: rawSource,
305 306
			lines: breakpointsToSend.map(bp => bp.sessionAgnosticData.lineNumber),
			breakpoints: breakpointsToSend.map(bp => ({ line: bp.sessionAgnosticData.lineNumber, column: bp.sessionAgnosticData.column, condition: bp.condition, hitCondition: bp.hitCondition, logMessage: bp.logMessage })),
A
Andre Weinand 已提交
307 308 309
			sourceModified
		}).then(response => {
			if (response && response.body) {
I
isidor 已提交
310
				const data = new Map<string, DebugProtocol.Breakpoint>();
A
Andre Weinand 已提交
311
				for (let i = 0; i < breakpointsToSend.length; i++) {
I
isidor 已提交
312
					data.set(breakpointsToSend[i].getId(), response.body.breakpoints[i]);
A
Andre Weinand 已提交
313
				}
314

315
				this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
A
Andre Weinand 已提交
316 317 318 319
			}
		});
	}

320
	sendFunctionBreakpoints(fbpts: IFunctionBreakpoint[]): Promise<void> {
321 322 323
		if (this.raw) {
			if (this.raw.readyForBreakpoints) {
				return this.raw.setFunctionBreakpoints({ breakpoints: fbpts }).then(response => {
A
Andre Weinand 已提交
324
					if (response && response.body) {
I
isidor 已提交
325
						const data = new Map<string, DebugProtocol.Breakpoint>();
A
Andre Weinand 已提交
326
						for (let i = 0; i < fbpts.length; i++) {
I
isidor 已提交
327
							data.set(fbpts[i].getId(), response.body.breakpoints[i]);
A
Andre Weinand 已提交
328
						}
329
						this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
A
Andre Weinand 已提交
330 331 332
					}
				});
			}
333

334
			return Promise.resolve(undefined);
A
Andre Weinand 已提交
335
		}
336

337
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
338 339
	}

340
	sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void> {
341
		if (this.raw) {
I
isidor 已提交
342
			if (this.raw.readyForBreakpoints) {
343
				return this.raw.setExceptionBreakpoints({ filters: exbpts.map(exb => exb.filter) }).then(() => undefined);
A
Andre Weinand 已提交
344
			}
R
Rob Lourens 已提交
345
			return Promise.resolve(undefined);
A
Andre Weinand 已提交
346
		}
347
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
348 349
	}

I
isidor 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	dataBreakpointInfo(name: string, variablesReference?: number): Promise<{ dataId: string | null, description: string, canPersist?: boolean }> {
		if (this.raw) {
			if (this.raw.readyForBreakpoints) {
				return this.raw.dataBreakpointInfo({ name, variablesReference }).then(response => response.body);
			}
			return Promise.reject(new Error(nls.localize('sessionNotReadyForBreakpoints', "Session is not ready for breakpoints")));
		}
		return Promise.reject(new Error('no debug adapter'));
	}

	sendDataBreakpoints(dataBreakpoints: IDataBreakpoint[]): Promise<void> {
		if (this.raw) {
			if (this.raw.readyForBreakpoints) {
				return this.raw.setDataBreakpoints({ breakpoints: dataBreakpoints }).then(response => {
					if (response && response.body) {
						const data = new Map<string, DebugProtocol.Breakpoint>();
						for (let i = 0; i < dataBreakpoints.length; i++) {
							data.set(dataBreakpoints[i].getId(), response.body.breakpoints[i]);
						}
369
						this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
370 371 372 373 374 375 376 377
					}
				});
			}
			return Promise.resolve(undefined);
		}
		return Promise.reject(new Error('no debug adapter'));
	}

I
isidor 已提交
378 379 380 381
	async breakpointsLocations(uri: URI, lineNumber: number): Promise<IPosition[]> {
		if (this.raw) {
			const source = this.getRawSource(uri);
			const response = await this.raw.breakpointLocations({ source, line: lineNumber });
I
isidor 已提交
382 383 384 385
			if (!response.body || !response.body.breakpoints) {
				return [];
			}

I
isidor 已提交
386 387
			const positions = response.body.breakpoints.map(bp => ({ lineNumber: bp.line, column: bp.column || 1 }));

388
			return distinct(positions, p => `${p.lineNumber}:${p.column}`);
I
isidor 已提交
389 390 391 392
		}
		return Promise.reject(new Error('no debug adapter'));
	}

393
	customRequest(request: string, args: any): Promise<DebugProtocol.Response> {
394 395
		if (this.raw) {
			return this.raw.custom(request, args);
A
Andre Weinand 已提交
396
		}
397
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
398 399
	}

400
	stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse> {
401
		if (this.raw) {
I
isidor 已提交
402 403
			const token = this.getNewCancellationToken(threadId);
			return this.raw.stackTrace({ threadId, startFrame, levels }, token);
A
Andre Weinand 已提交
404
		}
405
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
406 407
	}

I
isidor 已提交
408
	exceptionInfo(threadId: number): Promise<IExceptionInfo | undefined> {
409 410
		if (this.raw) {
			return this.raw.exceptionInfo({ threadId }).then(response => {
A
Andre Weinand 已提交
411 412 413 414 415 416 417 418
				if (response) {
					return {
						id: response.body.exceptionId,
						description: response.body.description,
						breakMode: response.body.breakMode,
						details: response.body.details
					};
				}
I
isidor 已提交
419
				return undefined;
A
Andre Weinand 已提交
420 421
			});
		}
422
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
423 424
	}

I
isidor 已提交
425
	scopes(frameId: number, threadId: number): Promise<DebugProtocol.ScopesResponse> {
426
		if (this.raw) {
I
isidor 已提交
427 428
			const token = this.getNewCancellationToken(threadId);
			return this.raw.scopes({ frameId }, token);
A
Andre Weinand 已提交
429
		}
430
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
431 432
	}

I
isidor 已提交
433
	variables(variablesReference: number, threadId: number | undefined, filter: 'indexed' | 'named' | undefined, start: number | undefined, count: number | undefined): Promise<DebugProtocol.VariablesResponse> {
434
		if (this.raw) {
I
isidor 已提交
435 436
			const token = threadId ? this.getNewCancellationToken(threadId) : undefined;
			return this.raw.variables({ variablesReference, filter, start, count }, token);
A
Andre Weinand 已提交
437
		}
I
isidor 已提交
438
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
439 440
	}

441
	evaluate(expression: string, frameId: number, context?: string): Promise<DebugProtocol.EvaluateResponse> {
442 443
		if (this.raw) {
			return this.raw.evaluate({ expression, frameId, context });
A
Andre Weinand 已提交
444
		}
445
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
446 447
	}

448
	restartFrame(frameId: number, threadId: number): Promise<void> {
449
		if (this.raw) {
450
			return this.raw.restartFrame({ frameId }, threadId).then(() => undefined);
A
Andre Weinand 已提交
451
		}
452
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
453 454
	}

455
	next(threadId: number): Promise<void> {
456
		if (this.raw) {
457
			return this.raw.next({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
458
		}
459
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
460 461
	}

462
	stepIn(threadId: number): Promise<void> {
463
		if (this.raw) {
464
			return this.raw.stepIn({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
465
		}
466
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
467 468
	}

469
	stepOut(threadId: number): Promise<void> {
470
		if (this.raw) {
471
			return this.raw.stepOut({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
472
		}
473
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
474 475
	}

476
	stepBack(threadId: number): Promise<void> {
477
		if (this.raw) {
478
			return this.raw.stepBack({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
479
		}
480
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
481 482
	}

483
	continue(threadId: number): Promise<void> {
484
		if (this.raw) {
485
			return this.raw.continue({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
486
		}
487
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
488 489
	}

490
	reverseContinue(threadId: number): Promise<void> {
491
		if (this.raw) {
492
			return this.raw.reverseContinue({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
493
		}
494
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
495 496
	}

497
	pause(threadId: number): Promise<void> {
498
		if (this.raw) {
499
			return this.raw.pause({ threadId }).then(() => undefined);
A
Andre Weinand 已提交
500
		}
501
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
502 503
	}

504
	terminateThreads(threadIds?: number[]): Promise<void> {
505
		if (this.raw) {
506
			return this.raw.terminateThreads({ threadIds }).then(() => undefined);
A
Andre Weinand 已提交
507
		}
508
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
509 510
	}

511
	setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse> {
512 513
		if (this.raw) {
			return this.raw.setVariable({ variablesReference, name, value });
A
Andre Weinand 已提交
514
		}
515
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
516 517
	}

I
isidor 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531
	gotoTargets(source: DebugProtocol.Source, line: number, column?: number): Promise<DebugProtocol.GotoTargetsResponse> {
		if (this.raw) {
			return this.raw.gotoTargets({ source, line, column });
		}
		return Promise.reject(new Error('no debug adapter'));
	}

	goto(threadId: number, targetId: number): Promise<DebugProtocol.GotoResponse> {
		if (this.raw) {
			return this.raw.goto({ threadId, targetId });
		}
		return Promise.reject(new Error('no debug adapter'));
	}

532
	loadSource(resource: URI): Promise<DebugProtocol.SourceResponse> {
A
Andre Weinand 已提交
533

534
		if (!this.raw) {
535
			return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
536 537 538 539 540 541 542 543
		}

		const source = this.getSourceForUri(resource);
		let rawSource: DebugProtocol.Source;
		if (source) {
			rawSource = source.raw;
		} else {
			// create a Source
544 545
			const data = Source.getEncodedDebugData(resource);
			rawSource = { path: data.path, sourceReference: data.sourceReference };
A
Andre Weinand 已提交
546 547
		}

I
isidor 已提交
548
		return this.raw.source({ sourceReference: rawSource.sourceReference || 0, source: rawSource });
A
Andre Weinand 已提交
549 550
	}

551
	getLoadedSources(): Promise<Source[]> {
552 553
		if (this.raw) {
			return this.raw.loadedSources({}).then(response => {
554 555 556 557 558
				if (response.body && response.body.sources) {
					return response.body.sources.map(src => this.getSource(src));
				} else {
					return [];
				}
A
Andre Weinand 已提交
559 560 561 562
			}, () => {
				return [];
			});
		}
563
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
564 565
	}

I
isidor 已提交
566
	completions(frameId: number | undefined, text: string, position: Position, overwriteBefore: number, token: CancellationToken): Promise<CompletionItem[]> {
567 568
		if (this.raw) {
			return this.raw.completions({
A
Andre Weinand 已提交
569 570 571
				frameId,
				text,
				column: position.column,
I
isidor 已提交
572 573
				line: position.lineNumber,
			}, token).then(response => {
A
Andre Weinand 已提交
574

575
				const result: CompletionItem[] = [];
A
Andre Weinand 已提交
576 577 578 579 580 581
				if (response && response.body && response.body.targets) {
					response.body.targets.forEach(item => {
						if (item && item.label) {
							result.push({
								label: item.label,
								insertText: item.text || item.label,
I
isidor 已提交
582 583
								kind: completionKindFromString(item.type || 'property'),
								filterText: (item.start && item.length) ? text.substr(item.start, item.length).concat(item.label) : undefined,
I
isidor 已提交
584 585
								range: Range.fromPositions(position.delta(0, -(item.length || overwriteBefore)), position),
								sortText: item.sortText
A
Andre Weinand 已提交
586 587 588 589 590 591 592 593
							});
						}
					});
				}

				return result;
			});
		}
594
		return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
595 596 597 598
	}

	//---- threads

I
isidor 已提交
599
	getThread(threadId: number): Thread | undefined {
A
Andre Weinand 已提交
600 601 602 603 604 605 606 607 608
		return this.threads.get(threadId);
	}

	getAllThreads(): IThread[] {
		const result: IThread[] = [];
		this.threads.forEach(t => result.push(t));
		return result;
	}

609
	clearThreads(removeThreads: boolean, reference: number | undefined = undefined): void {
A
Andre Weinand 已提交
610
		if (reference !== undefined && reference !== null) {
611 612
			const thread = this.threads.get(reference);
			if (thread) {
A
Andre Weinand 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
				thread.clearCallStack();
				thread.stoppedDetails = undefined;
				thread.stopped = false;

				if (removeThreads) {
					this.threads.delete(reference);
				}
			}
		} else {
			this.threads.forEach(thread => {
				thread.clearCallStack();
				thread.stoppedDetails = undefined;
				thread.stopped = false;
			});

			if (removeThreads) {
				this.threads.clear();
				ExpressionContainer.allValues.clear();
			}
		}
	}

	rawUpdate(data: IRawModelUpdate): void {
636
		const threadIds: number[] = [];
I
isidor 已提交
637
		data.threads.forEach(thread => {
638
			threadIds.push(thread.id);
I
isidor 已提交
639 640 641 642 643 644 645 646 647
			if (!this.threads.has(thread.id)) {
				// A new thread came in, initialize it.
				this.threads.set(thread.id, new Thread(this, thread.name, thread.id));
			} else if (thread.name) {
				// Just the thread name got updated #18244
				const oldThread = this.threads.get(thread.id);
				if (oldThread) {
					oldThread.name = thread.name;
				}
I
isidor 已提交
648
			}
I
isidor 已提交
649
		});
650 651 652 653 654 655
		this.threads.forEach(t => {
			// Remove all old threads which are no longer part of the update #75980
			if (threadIds.indexOf(t.threadId) === -1) {
				this.threads.delete(t.threadId);
			}
		});
A
Andre Weinand 已提交
656

I
isidor 已提交
657 658
		const stoppedDetails = data.stoppedDetails;
		if (stoppedDetails) {
A
Andre Weinand 已提交
659 660
			// Set the availability of the threads' callstacks depending on
			// whether the thread is stopped or not
I
isidor 已提交
661
			if (stoppedDetails.allThreadsStopped) {
A
Andre Weinand 已提交
662
				this.threads.forEach(thread => {
I
isidor 已提交
663
					thread.stoppedDetails = thread.threadId === stoppedDetails.threadId ? stoppedDetails : { reason: undefined };
A
Andre Weinand 已提交
664 665 666
					thread.stopped = true;
					thread.clearCallStack();
				});
I
isidor 已提交
667
			} else {
I
isidor 已提交
668
				const thread = typeof stoppedDetails.threadId === 'number' ? this.threads.get(stoppedDetails.threadId) : undefined;
I
isidor 已提交
669 670
				if (thread) {
					// One thread is stopped, only update that thread.
I
isidor 已提交
671
					thread.stoppedDetails = stoppedDetails;
I
isidor 已提交
672 673 674
					thread.clearCallStack();
					thread.stopped = true;
				}
A
Andre Weinand 已提交
675 676 677 678
			}
		}
	}

679
	private fetchThreads(stoppedDetails?: IRawStoppedDetails): Promise<void> {
I
isidor 已提交
680
		return this.raw ? this.raw.threads().then(response => {
A
Andre Weinand 已提交
681
			if (response && response.body && response.body.threads) {
I
isidor 已提交
682 683 684 685
				this.model.rawUpdate({
					sessionId: this.getId(),
					threads: response.body.threads,
					stoppedDetails
A
Andre Weinand 已提交
686 687
				});
			}
688
		}) : Promise.resolve(undefined);
A
Andre Weinand 已提交
689 690 691 692
	}

	//---- private

I
isidor 已提交
693
	private registerListeners(): void {
I
isidor 已提交
694 695 696 697
		if (!this.raw) {
			return;
		}

698
		this.rawListeners.push(this.raw.onDidInitialize(() => {
I
isidor 已提交
699 700
			aria.status(nls.localize('debuggingStarted', "Debugging started."));
			const sendConfigurationDone = () => {
701
				if (this.raw && this.raw.capabilities.supportsConfigurationDoneRequest) {
702
					return this.raw.configurationDone().then(undefined, () => {
I
isidor 已提交
703
						// Disconnect the debug session on configuration done error #10596
704 705
						if (this.raw) {
							this.raw.disconnect();
I
isidor 已提交
706 707 708
						}
					});
				}
709 710

				return undefined;
I
isidor 已提交
711 712 713
			};

			// Send all breakpoints
714
			this.debugService.sendAllBreakpoints(this).then(sendConfigurationDone, sendConfigurationDone)
715
				.then(() => this.fetchThreads());
I
isidor 已提交
716 717
		}));

718
		this.rawListeners.push(this.raw.onDidStop(event => {
719
			this.fetchThreads(event.body).then(() => {
I
isidor 已提交
720
				const thread = typeof event.body.threadId === 'number' ? this.getThread(event.body.threadId) : undefined;
I
isidor 已提交
721 722 723
				if (thread) {
					// Call fetch call stack twice, the first only return the top stack frame.
					// Second retrieves the rest of the call stack. For performance reasons #25605
724
					const promises = this.model.fetchCallStack(<Thread>thread);
I
isidor 已提交
725
					const focus = async () => {
I
isidor 已提交
726
						if (!event.body.preserveFocusHint && thread.getCallStack().length) {
I
isidor 已提交
727
							await this.debugService.focusStackFrame(undefined, thread);
I
isidor 已提交
728 729 730 731
							if (thread.stoppedDetails) {
								if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
									this.viewletService.openViewlet(VIEWLET_ID);
								}
732

I
isidor 已提交
733
								if (this.configurationService.getValue<IDebugConfiguration>('debug').focusWindowOnBreak) {
734
									this.hostService.focus();
735
								}
I
isidor 已提交
736 737
							}
						}
738 739 740 741 742 743 744 745
					};

					promises.topCallStack.then(focus);
					promises.wholeCallStack.then(() => {
						if (!this.debugService.getViewModel().focusedStackFrame) {
							// The top stack frame can be deemphesized so try to focus again #68616
							focus();
						}
I
isidor 已提交
746 747
					});
				}
748
			}).then(() => this._onDidChangeState.fire());
I
isidor 已提交
749 750
		}));

751
		this.rawListeners.push(this.raw.onDidThread(event => {
I
isidor 已提交
752 753 754 755
			if (event.body.reason === 'started') {
				// debounce to reduce threadsRequest frequency and improve performance
				if (!this.fetchThreadsScheduler) {
					this.fetchThreadsScheduler = new RunOnceScheduler(() => {
756
						this.fetchThreads();
I
isidor 已提交
757 758 759 760 761 762 763 764 765 766 767
					}, 100);
					this.rawListeners.push(this.fetchThreadsScheduler);
				}
				if (!this.fetchThreadsScheduler.isScheduled()) {
					this.fetchThreadsScheduler.schedule();
				}
			} else if (event.body.reason === 'exited') {
				this.model.clearThreads(this.getId(), true, event.body.threadId);
			}
		}));

768
		this.rawListeners.push(this.raw.onDidTerminateDebugee(event => {
I
isidor 已提交
769 770
			aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
			if (event.body && event.body.restart) {
R
Rob Lourens 已提交
771
				this.debugService.restartSession(this, event.body.restart).then(undefined, onUnexpectedError);
I
isidor 已提交
772
			} else if (this.raw) {
773
				this.raw.disconnect();
I
isidor 已提交
774 775 776
			}
		}));

777
		this.rawListeners.push(this.raw.onDidContinued(event => {
I
isidor 已提交
778
			const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
I
isidor 已提交
779 780 781 782 783 784 785 786 787 788
			if (threadId) {
				const tokens = this.cancellationMap.get(threadId);
				this.cancellationMap.delete(threadId);
				if (tokens) {
					tokens.forEach(t => t.cancel());
				}
			} else {
				this.cancelAllRequests();
			}

I
isidor 已提交
789
			this.model.clearThreads(this.getId(), false, threadId);
790
			this._onDidChangeState.fire();
I
isidor 已提交
791 792
		}));

793
		let outpuPromises: Promise<void>[] = [];
794
		this.rawListeners.push(this.raw.onDidOutput(event => {
I
isidor 已提交
795
			if (!event.body || !this.raw) {
I
isidor 已提交
796 797 798 799 800 801 802
				return;
			}

			const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info;
			if (event.body.category === 'telemetry') {
				// only log telemetry events from debug adapter if the debug extension provided the telemetry key
				// and the user opted in telemetry
803
				if (this.raw.customTelemetryService && this.telemetryService.isOptedIn) {
I
isidor 已提交
804
					// __GDPR__TODO__ We're sending events in the name of the debug extension and we can not ensure that those are declared correctly.
805
					this.raw.customTelemetryService.publicLog(event.body.output, event.body.data);
I
isidor 已提交
806 807 808 809 810 811
				}

				return;
			}

			// Make sure to append output in the correct order by properly waiting on preivous promises #33822
812
			const waitFor = outpuPromises.slice();
I
isidor 已提交
813
			const source = event.body.source && event.body.line ? {
I
isidor 已提交
814 815 816 817 818
				lineNumber: event.body.line,
				column: event.body.column ? event.body.column : 1,
				source: this.getSource(event.body.source)
			} : undefined;
			if (event.body.variablesReference) {
I
isidor 已提交
819
				const container = new ExpressionContainer(this, undefined, event.body.variablesReference, generateUuid());
820
				outpuPromises.push(container.getChildren().then(children => {
I
isidor 已提交
821
					return Promise.all(waitFor).then(() => children.forEach(child => {
I
isidor 已提交
822
						// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
I
isidor 已提交
823
						(<any>child).name = null;
I
isidor 已提交
824
						this.appendToRepl(child, outputSeverity, source);
I
isidor 已提交
825 826 827
					}));
				}));
			} else if (typeof event.body.output === 'string') {
I
isidor 已提交
828
				Promise.all(waitFor).then(() => this.appendToRepl(event.body.output, outputSeverity, source));
I
isidor 已提交
829
			}
830
			Promise.all(outpuPromises).then(() => outpuPromises = []);
I
isidor 已提交
831 832
		}));

833
		this.rawListeners.push(this.raw.onDidBreakpoint(event => {
I
isidor 已提交
834
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
D
Dmitry Gozman 已提交
835 836
			const breakpoint = this.model.getBreakpoints().filter(bp => bp.getIdFromAdapter(this.getId()) === id).pop();
			const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.getIdFromAdapter(this.getId()) === id).pop();
I
isidor 已提交
837

I
isidor 已提交
838
			if (event.body.reason === 'new' && event.body.breakpoint.source && event.body.breakpoint.line) {
I
isidor 已提交
839 840 841 842 843 844 845
				const source = this.getSource(event.body.breakpoint.source);
				const bps = this.model.addBreakpoints(source.uri, [{
					column: event.body.breakpoint.column,
					enabled: true,
					lineNumber: event.body.breakpoint.line,
				}], false);
				if (bps.length === 1) {
I
isidor 已提交
846
					const data = new Map<string, DebugProtocol.Breakpoint>([[bps[0].getId(), event.body.breakpoint]]);
847
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
				}
			}

			if (event.body.reason === 'removed') {
				if (breakpoint) {
					this.model.removeBreakpoints([breakpoint]);
				}
				if (functionBreakpoint) {
					this.model.removeFunctionBreakpoints(functionBreakpoint.getId());
				}
			}

			if (event.body.reason === 'changed') {
				if (breakpoint) {
					if (!breakpoint.column) {
						event.body.breakpoint.column = undefined;
					}
I
isidor 已提交
865
					const data = new Map<string, DebugProtocol.Breakpoint>([[breakpoint.getId(), event.body.breakpoint]]);
866
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
867 868
				}
				if (functionBreakpoint) {
I
isidor 已提交
869
					const data = new Map<string, DebugProtocol.Breakpoint>([[functionBreakpoint.getId(), event.body.breakpoint]]);
870
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
871 872 873 874
				}
			}
		}));

875
		this.rawListeners.push(this.raw.onDidLoadedSource(event => {
I
isidor 已提交
876 877 878 879 880 881
			this._onDidLoadedSource.fire({
				reason: event.body.reason,
				source: this.getSource(event.body.source)
			});
		}));

882
		this.rawListeners.push(this.raw.onDidCustomEvent(event => {
I
isidor 已提交
883 884 885
			this._onDidCustomEvent.fire(event);
		}));

886
		this.rawListeners.push(this.raw.onDidExitAdapter(event => {
I
isidor 已提交
887
			this.initialized = true;
888
			this.model.setBreakpointSessionData(this.getId(), this.capabilities, undefined);
A
Andre Weinand 已提交
889
			this._onDidEndAdapter.fire(event);
890 891 892
		}));
	}

893
	shutdown(): void {
894
		dispose(this.rawListeners);
895 896
		if (this.raw) {
			this.raw.disconnect();
I
isidor 已提交
897
			this.raw.dispose();
898
		}
899
		this.raw = undefined;
900 901
		this.model.clearThreads(this.getId(), true);
		this._onDidChangeState.fire();
902 903 904 905
	}

	//---- sources

I
isidor 已提交
906
	getSourceForUri(uri: URI): Source | undefined {
I
isidor 已提交
907
		return this.sources.get(this.getUriKey(uri));
908 909
	}

I
isidor 已提交
910
	getSource(raw?: DebugProtocol.Source): Source {
911
		let source = new Source(raw, this.getId());
I
isidor 已提交
912
		const uriKey = this.getUriKey(source.uri);
A
Andre Weinand 已提交
913 914 915 916
		const found = this.sources.get(uriKey);
		if (found) {
			source = found;
			// merge attributes of new into existing
917 918 919 920 921 922
			source.raw = mixin(source.raw, raw);
			if (source.raw && raw) {
				// Always take the latest presentation hint from adapter #42139
				source.raw.presentationHint = raw.presentationHint;
			}
		} else {
I
isidor 已提交
923
			this.sources.set(uriKey, source);
924 925 926 927
		}

		return source;
	}
I
isidor 已提交
928

I
isidor 已提交
929 930 931 932 933 934 935 936 937 938
	private getRawSource(uri: URI): DebugProtocol.Source {
		const source = this.getSourceForUri(uri);
		if (source) {
			return source.raw;
		} else {
			const data = Source.getEncodedDebugData(uri);
			return { name: data.name, path: data.path, sourceReference: data.sourceReference };
		}
	}

I
isidor 已提交
939 940 941 942 943 944 945 946 947 948 949 950 951 952
	private getNewCancellationToken(threadId: number): CancellationToken {
		const tokenSource = new CancellationTokenSource();
		const tokens = this.cancellationMap.get(threadId) || [];
		tokens.push(tokenSource);
		this.cancellationMap.set(threadId, tokens);

		return tokenSource.token;
	}

	private cancelAllRequests(): void {
		this.cancellationMap.forEach(tokens => tokens.forEach(t => t.cancel()));
		this.cancellationMap.clear();
	}

I
isidor 已提交
953
	private getUriKey(uri: URI): string {
A
Andre Weinand 已提交
954
		// TODO: the following code does not make sense if uri originates from a different platform
I
isidor 已提交
955 956
		return platform.isLinux ? uri.toString() : uri.toString().toLowerCase();
	}
I
isidor 已提交
957 958 959

	// REPL

I
isidor 已提交
960
	getReplElements(): IReplElement[] {
961 962 963
		return this.repl.getReplElements();
	}

964 965 966 967
	hasSeparateRepl(): boolean {
		return !this.parentSession || this._options.repl !== 'mergeWithParent';
	}

968 969
	removeReplExpressions(): void {
		this.repl.removeReplExpressions();
I
isidor 已提交
970 971
	}

972
	async addReplExpression(stackFrame: IStackFrame | undefined, name: string): Promise<void> {
973
		await this.repl.addReplExpression(this, stackFrame, name);
974 975
		// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
		variableSetEmitter.fire();
I
isidor 已提交
976 977
	}

978
	appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void {
D
Dmitry Gozman 已提交
979
		this.repl.appendToRepl(this, data, severity, source);
I
isidor 已提交
980 981
	}

982
	logToRepl(sev: severity, args: any[], frame?: { uri: URI, line: number, column: number }) {
983
		this.repl.logToRepl(this, sev, args, frame);
I
isidor 已提交
984
	}
985
}