debugSession.ts 32.9 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';
I
isidor 已提交
34
import { INotificationService } from 'vs/platform/notification/common/notification';
35
import { IOpenerService } from 'vs/platform/opener/common/opener';
36
import { variableSetEmitter } from 'vs/workbench/contrib/debug/browser/variablesView';
I
isidor 已提交
37
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
I
isidor 已提交
38
import { distinct } from 'vs/base/common/arrays';
I
isidor 已提交
39

40
export class DebugSession implements IDebugSession {
41

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

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

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

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

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

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

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

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

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

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

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

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

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

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

I
isidor 已提交
120 121
	getLabel(): string {
		const includeRoot = this.workspaceContextService.getWorkspace().folders.length > 1;
122 123 124 125 126 127 128
		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 已提交
129 130 131
	}

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

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

147
		return State.Running;
A
Andre Weinand 已提交
148 149 150
	}

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

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

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

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

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

A
Andre Weinand 已提交
171 172
	//---- DAP events

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

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

A
Andre Weinand 已提交
181 182 183 184 185
	//---- DAP requests

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

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

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

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

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

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

					this.registerListeners();

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

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

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

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

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

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

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

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

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

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

I
isidor 已提交
296
		const rawSource = this.getRawSource(modelUri);
A
Andre Weinand 已提交
297 298 299 300
		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 已提交
301 302 303
		if (rawSource.path) {
			rawSource.path = normalizeDriveLetter(rawSource.path);
		}
A
Andre Weinand 已提交
304

305
		return this.raw.setBreakpoints({
A
Andre Weinand 已提交
306
			source: rawSource,
307 308
			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 已提交
309 310 311
			sourceModified
		}).then(response => {
			if (response && response.body) {
I
isidor 已提交
312
				const data = new Map<string, DebugProtocol.Breakpoint>();
A
Andre Weinand 已提交
313
				for (let i = 0; i < breakpointsToSend.length; i++) {
I
isidor 已提交
314
					data.set(breakpointsToSend[i].getId(), response.body.breakpoints[i]);
A
Andre Weinand 已提交
315
				}
316

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

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

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

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

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

I
isidor 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
	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]);
						}
371
						this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
372 373 374 375 376 377 378 379
					}
				});
			}
			return Promise.resolve(undefined);
		}
		return Promise.reject(new Error('no debug adapter'));
	}

I
isidor 已提交
380 381 382 383 384 385
	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 });
			const positions = response.body.breakpoints.map(bp => ({ lineNumber: bp.line, column: bp.column || 1 }));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

I
isidor 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529
	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'));
	}

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

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

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

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

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

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

573
				const result: CompletionItem[] = [];
A
Andre Weinand 已提交
574 575 576 577 578 579
				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 已提交
580 581
								kind: completionKindFromString(item.type || 'property'),
								filterText: (item.start && item.length) ? text.substr(item.start, item.length).concat(item.label) : undefined,
I
isidor 已提交
582 583
								range: Range.fromPositions(position.delta(0, -(item.length || overwriteBefore)), position),
								sortText: item.sortText
A
Andre Weinand 已提交
584 585 586 587 588 589 590 591
							});
						}
					});
				}

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

	//---- threads

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

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

607
	clearThreads(removeThreads: boolean, reference: number | undefined = undefined): void {
A
Andre Weinand 已提交
608
		if (reference !== undefined && reference !== null) {
609 610
			const thread = this.threads.get(reference);
			if (thread) {
A
Andre Weinand 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
				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 {
634
		const threadIds: number[] = [];
I
isidor 已提交
635
		data.threads.forEach(thread => {
636
			threadIds.push(thread.id);
I
isidor 已提交
637 638 639 640 641 642 643 644 645
			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 已提交
646
			}
I
isidor 已提交
647
		});
648 649 650 651 652 653
		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 已提交
654

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

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

	//---- private

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

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

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

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

719
		this.rawListeners.push(this.raw.onDidStop(event => {
720
			this.fetchThreads(event.body).then(() => {
I
isidor 已提交
721
				const thread = typeof event.body.threadId === 'number' ? this.getThread(event.body.threadId) : undefined;
I
isidor 已提交
722 723 724
				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
725 726
					const promises = this.model.fetchCallStack(<Thread>thread);
					const focus = () => {
I
isidor 已提交
727 728 729 730 731 732
						if (!event.body.preserveFocusHint && thread.getCallStack().length) {
							this.debugService.focusStackFrame(undefined, thread);
							if (thread.stoppedDetails) {
								if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
									this.viewletService.openViewlet(VIEWLET_ID);
								}
733

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

					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 已提交
747 748
					});
				}
749
			}).then(() => this._onDidChangeState.fire());
I
isidor 已提交
750 751
		}));

752
		this.rawListeners.push(this.raw.onDidThread(event => {
I
isidor 已提交
753 754 755 756
			if (event.body.reason === 'started') {
				// debounce to reduce threadsRequest frequency and improve performance
				if (!this.fetchThreadsScheduler) {
					this.fetchThreadsScheduler = new RunOnceScheduler(() => {
757
						this.fetchThreads();
I
isidor 已提交
758 759 760 761 762 763 764 765 766 767 768
					}, 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);
			}
		}));

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

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

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

794
		let outpuPromises: Promise<void>[] = [];
795
		this.rawListeners.push(this.raw.onDidOutput(event => {
I
isidor 已提交
796
			if (!event.body || !this.raw) {
I
isidor 已提交
797 798 799 800 801 802 803
				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
804
				if (this.raw.customTelemetryService && this.telemetryService.isOptedIn) {
I
isidor 已提交
805
					// __GDPR__TODO__ We're sending events in the name of the debug extension and we can not ensure that those are declared correctly.
806
					this.raw.customTelemetryService.publicLog(event.body.output, event.body.data);
I
isidor 已提交
807 808 809 810 811 812
				}

				return;
			}

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

834
		this.rawListeners.push(this.raw.onDidBreakpoint(event => {
I
isidor 已提交
835
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
D
Dmitry Gozman 已提交
836 837
			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 已提交
838

I
isidor 已提交
839
			if (event.body.reason === 'new' && event.body.breakpoint.source && event.body.breakpoint.line) {
I
isidor 已提交
840 841 842 843 844 845 846
				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 已提交
847
					const data = new Map<string, DebugProtocol.Breakpoint>([[bps[0].getId(), event.body.breakpoint]]);
848
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
				}
			}

			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 已提交
866
					const data = new Map<string, DebugProtocol.Breakpoint>([[breakpoint.getId(), event.body.breakpoint]]);
867
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
868 869
				}
				if (functionBreakpoint) {
I
isidor 已提交
870
					const data = new Map<string, DebugProtocol.Breakpoint>([[functionBreakpoint.getId(), event.body.breakpoint]]);
871
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
872 873 874 875
				}
			}
		}));

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

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

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

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

	//---- sources

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

I
isidor 已提交
911
	getSource(raw?: DebugProtocol.Source): Source {
912
		let source = new Source(raw, this.getId());
I
isidor 已提交
913
		const uriKey = this.getUriKey(source.uri);
A
Andre Weinand 已提交
914 915 916 917
		const found = this.sources.get(uriKey);
		if (found) {
			source = found;
			// merge attributes of new into existing
918 919 920 921 922 923
			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 已提交
924
			this.sources.set(uriKey, source);
925 926 927 928
		}

		return source;
	}
I
isidor 已提交
929

I
isidor 已提交
930 931 932 933 934 935 936 937 938 939
	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 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953
	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 已提交
954
	private getUriKey(uri: URI): string {
A
Andre Weinand 已提交
955
		// TODO: the following code does not make sense if uri originates from a different platform
I
isidor 已提交
956 957
		return platform.isLinux ? uri.toString() : uri.toString().toLowerCase();
	}
I
isidor 已提交
958 959 960

	// REPL

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

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

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

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

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

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