debugSession.ts 32.3 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';
I
isidor 已提交
12
import { Position, IPosition } from 'vs/editor/common/core/position';
I
isidor 已提交
13
import * as aria from 'vs/base/browser/ui/aria/aria';
14
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';
15
import { Source } from 'vs/workbench/contrib/debug/common/debugSource';
16
import { mixin } from 'vs/base/common/objects';
17
import { Thread, ExpressionContainer, DebugModel } from 'vs/workbench/contrib/debug/common/debugModel';
A
Andre Weinand 已提交
18
import { RawDebugSession } from 'vs/workbench/contrib/debug/browser/rawDebugSession';
19
import { IProductService } from 'vs/platform/product/common/productService';
I
isidor 已提交
20
import { IWorkspaceFolder, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
I
isidor 已提交
21 22 23
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { generateUuid } from 'vs/base/common/uuid';
24
import { IHostService } from 'vs/workbench/services/host/browser/host';
25
import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';
I
isidor 已提交
26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
A
Andre Weinand 已提交
27
import { normalizeDriveLetter } from 'vs/base/common/labels';
I
isidor 已提交
28 29
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
30
import { ReplModel } from 'vs/workbench/contrib/debug/common/replModel';
31
import { IOpenerService } from 'vs/platform/opener/common/opener';
32
import { variableSetEmitter } from 'vs/workbench/contrib/debug/browser/variablesView';
I
isidor 已提交
33
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
I
isidor 已提交
34
import { distinct } from 'vs/base/common/arrays';
I
isidor 已提交
35
import { INotificationService } from 'vs/platform/notification/common/notification';
I
isidor 已提交
36
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
I
isidor 已提交
37

38
export class DebugSession implements IDebugSession {
39

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

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

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

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

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

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

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

		const toDispose: IDisposable[] = [];
		toDispose.push(this.repl.onDidChangeElements(() => this._onDidChangeREPLElements.fire()));
A
Alex Dima 已提交
91 92 93 94 95 96
		if (lifecycleService) {
			toDispose.push(lifecycleService.onShutdown(() => {
				this.shutdown();
				dispose(toDispose);
			}));
		}
97 98
	}

A
Andre Weinand 已提交
99 100 101 102
	getId(): string {
		return this.id;
	}

103 104 105 106 107 108 109 110
	setSubId(subId: string | undefined) {
		this._subId = subId;
	}

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

I
isidor 已提交
111
	get configuration(): IConfig {
112 113 114
		return this._configuration.resolved;
	}

I
isidor 已提交
115
	get unresolvedConfiguration(): IConfig | undefined {
116 117 118
		return this._configuration.unresolved;
	}

I
isidor 已提交
119
	get parentSession(): IDebugSession | undefined {
120
		return this._options.parentSession;
I
isidor 已提交
121 122
	}

I
isidor 已提交
123
	setConfiguration(configuration: { resolved: IConfig, unresolved: IConfig | undefined }) {
I
isidor 已提交
124 125 126
		this._configuration = configuration;
	}

I
isidor 已提交
127 128
	getLabel(): string {
		const includeRoot = this.workspaceContextService.getWorkspace().folders.length > 1;
129 130 131 132 133 134 135
		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 已提交
136 137 138
	}

	get state(): State {
I
isidor 已提交
139 140 141
		if (!this.initialized) {
			return State.Initializing;
		}
142 143 144 145
		if (!this.raw) {
			return State.Inactive;
		}

146
		const focusedThread = this.debugService.getViewModel().focusedThread;
I
isidor 已提交
147
		if (focusedThread && focusedThread.session === this) {
148 149 150 151
			return focusedThread.stopped ? State.Stopped : State.Running;
		}
		if (this.getAllThreads().some(t => t.stopped)) {
			return State.Stopped;
A
Andre Weinand 已提交
152
		}
153

154
		return State.Running;
A
Andre Weinand 已提交
155 156 157
	}

	get capabilities(): DebugProtocol.Capabilities {
158
		return this.raw ? this.raw.capabilities : Object.create(null);
159 160
	}

A
Andre Weinand 已提交
161
	//---- events
162
	get onDidChangeState(): Event<void> {
I
isidor 已提交
163
		return this._onDidChangeState.event;
164 165
	}

A
Andre Weinand 已提交
166 167 168 169
	get onDidEndAdapter(): Event<AdapterEndEvent> {
		return this._onDidEndAdapter.event;
	}

I
isidor 已提交
170 171 172 173
	get onDidChangeReplElements(): Event<void> {
		return this._onDidChangeREPLElements.event;
	}

174 175 176 177
	get onDidChangeName(): Event<string> {
		return this._onDidChangeName.event;
	}

A
Andre Weinand 已提交
178 179
	//---- DAP events

A
Andre Weinand 已提交
180
	get onDidCustomEvent(): Event<DebugProtocol.Event> {
I
isidor 已提交
181 182 183
		return this._onDidCustomEvent.event;
	}

A
Andre Weinand 已提交
184 185
	get onDidLoadedSource(): Event<LoadedSourceEvent> {
		return this._onDidLoadedSource.event;
186 187
	}

A
Andre Weinand 已提交
188 189 190 191 192
	//---- DAP requests

	/**
	 * create and initialize a new debug adapter for this session
	 */
I
isidor 已提交
193
	async initialize(dbgr: IDebugger): Promise<void> {
194

195
		if (this.raw) {
196
			// if there was already a connection make sure to remove old listeners
197
			this.shutdown();
I
isidor 已提交
198
		}
199

I
isidor 已提交
200 201 202
		try {
			const customTelemetryService = await dbgr.getCustomTelemetryService();
			const debugAdapter = await dbgr.createDebugAdapter(this);
I
isidor 已提交
203
			this.raw = new RawDebugSession(debugAdapter, dbgr, this.telemetryService, customTelemetryService, this.extensionHostDebugService, this.openerService, this.notificationService);
I
isidor 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217

			await this.raw.start();
			this.registerListeners();
			await this.raw!.initialize({
				clientID: 'vscode',
				clientName: this.productService.nameLong,
				adapterID: this.configuration.type,
				pathFormat: 'path',
				linesStartAt1: true,
				columnsStartAt1: true,
				supportsVariableType: true, // #8858
				supportsVariablePaging: true, // #9537
				supportsRunInTerminalRequest: true, // #10574
				locale: platform.locale
I
isidor 已提交
218
			});
I
isidor 已提交
219

I
isidor 已提交
220 221
			this.initialized = true;
			this._onDidChangeState.fire();
I
isidor 已提交
222 223 224 225
			this.model.setExceptionBreakpoints(this.raw!.capabilities.exceptionBreakpointFilters || []);
		} catch (err) {
			this.initialized = true;
			this._onDidChangeState.fire();
I
isidor 已提交
226
			this.shutdown();
I
isidor 已提交
227 228
			throw err;
		}
I
isidor 已提交
229 230
	}

A
Andre Weinand 已提交
231 232 233
	/**
	 * launch or attach to the debuggee
	 */
I
isidor 已提交
234 235 236 237
	async launchOrAttach(config: IConfig): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
		}
A
Andre Weinand 已提交
238

I
isidor 已提交
239 240
		// __sessionID only used for EH debugging (but we add it always for now...)
		config.__sessionId = this.getId();
I
isidor 已提交
241 242 243 244 245 246
		try {
			await this.raw.launchOrAttach(config);
		} catch (err) {
			this.shutdown();
			throw err;
		}
A
Andre Weinand 已提交
247 248 249 250 251
	}

	/**
	 * end the current debug adapter session
	 */
I
isidor 已提交
252 253 254 255 256 257 258 259 260 261
	async terminate(restart = false): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
		}

		this.cancelAllRequests();
		if (this.raw.capabilities.supportsTerminateRequest && this._configuration.resolved.request === 'launch') {
			await this.raw.terminate(restart);
		} else {
			await this.raw.disconnect(restart);
A
Andre Weinand 已提交
262 263 264 265 266 267
		}
	}

	/**
	 * end the current debug adapter session
	 */
I
isidor 已提交
268 269 270
	async disconnect(restart = false): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
271
		}
I
isidor 已提交
272 273 274

		this.cancelAllRequests();
		await this.raw.disconnect(restart);
A
Andre Weinand 已提交
275 276 277 278 279
	}

	/**
	 * restart debug adapter session
	 */
I
isidor 已提交
280 281 282
	async restart(): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
283 284
		}

I
isidor 已提交
285 286 287
		this.cancelAllRequests();
		await this.raw.restart();
	}
A
Andre Weinand 已提交
288

I
isidor 已提交
289
	async sendBreakpoints(modelUri: URI, breakpointsToSend: IBreakpoint[], sourceModified: boolean): Promise<void> {
290
		if (!this.raw) {
I
isidor 已提交
291
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
292 293
		}

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

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

I
isidor 已提交
307
		const response = await this.raw.setBreakpoints({
A
Andre Weinand 已提交
308
			source: rawSource,
309 310
			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 已提交
311
			sourceModified
I
isidor 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
		});
		if (response && response.body) {
			const data = new Map<string, DebugProtocol.Breakpoint>();
			for (let i = 0; i < breakpointsToSend.length; i++) {
				data.set(breakpointsToSend[i].getId(), response.body.breakpoints[i]);
			}

			this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
		}
	}

	async sendFunctionBreakpoints(fbpts: IFunctionBreakpoint[]): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
		}

		if (this.raw.readyForBreakpoints) {
			const response = await this.raw.setFunctionBreakpoints({ breakpoints: fbpts });
A
Andre Weinand 已提交
330
			if (response && response.body) {
I
isidor 已提交
331
				const data = new Map<string, DebugProtocol.Breakpoint>();
I
isidor 已提交
332 333
				for (let i = 0; i < fbpts.length; i++) {
					data.set(fbpts[i].getId(), response.body.breakpoints[i]);
A
Andre Weinand 已提交
334
				}
335
				this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
A
Andre Weinand 已提交
336
			}
I
isidor 已提交
337
		}
A
Andre Weinand 已提交
338 339
	}

I
isidor 已提交
340 341 342
	async sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
343
		}
344

I
isidor 已提交
345 346 347
		if (this.raw.readyForBreakpoints) {
			await this.raw.setExceptionBreakpoints({ filters: exbpts.map(exb => exb.filter) });
		}
A
Andre Weinand 已提交
348 349
	}

I
isidor 已提交
350 351 352
	async dataBreakpointInfo(name: string, variablesReference?: number): Promise<{ dataId: string | null, description: string, canPersist?: boolean }> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
353
		}
I
isidor 已提交
354 355 356 357 358 359
		if (!this.raw.readyForBreakpoints) {
			throw new Error(nls.localize('sessionNotReadyForBreakpoints', "Session is not ready for breakpoints"));
		}

		const response = await this.raw.dataBreakpointInfo({ name, variablesReference });
		return response.body;
A
Andre Weinand 已提交
360 361
	}

I
isidor 已提交
362 363 364
	async sendDataBreakpoints(dataBreakpoints: IDataBreakpoint[]): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
I
isidor 已提交
365 366
		}

I
isidor 已提交
367 368 369 370 371 372 373 374
		if (this.raw.readyForBreakpoints) {
			const response = await this.raw.setDataBreakpoints({ breakpoints: dataBreakpoints });
			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]);
				}
				this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
375 376 377 378
			}
		}
	}

I
isidor 已提交
379
	async breakpointsLocations(uri: URI, lineNumber: number): Promise<IPosition[]> {
I
isidor 已提交
380 381 382
		if (!this.raw) {
			throw new Error('no debug adapter');
		}
I
isidor 已提交
383

I
isidor 已提交
384 385 386 387
		const source = this.getRawSource(uri);
		const response = await this.raw.breakpointLocations({ source, line: lineNumber });
		if (!response.body || !response.body.breakpoints) {
			return [];
I
isidor 已提交
388
		}
I
isidor 已提交
389 390 391 392

		const positions = response.body.breakpoints.map(bp => ({ lineNumber: bp.line, column: bp.column || 1 }));

		return distinct(positions, p => `${p.lineNumber}:${p.column}`);
I
isidor 已提交
393 394
	}

395
	customRequest(request: string, args: any): Promise<DebugProtocol.Response> {
I
isidor 已提交
396 397
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
398
		}
I
isidor 已提交
399 400

		return this.raw.custom(request, args);
A
Andre Weinand 已提交
401 402
	}

403
	stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse> {
I
isidor 已提交
404 405
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
406
		}
I
isidor 已提交
407 408 409

		const token = this.getNewCancellationToken(threadId);
		return this.raw.stackTrace({ threadId, startFrame, levels }, token);
A
Andre Weinand 已提交
410 411
	}

I
isidor 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424
	async exceptionInfo(threadId: number): Promise<IExceptionInfo | undefined> {
		if (!this.raw) {
			throw new Error('no debug adapter');
		}

		const response = await this.raw.exceptionInfo({ threadId });
		if (response) {
			return {
				id: response.body.exceptionId,
				description: response.body.description,
				breakMode: response.body.breakMode,
				details: response.body.details
			};
A
Andre Weinand 已提交
425
		}
I
isidor 已提交
426 427

		return undefined;
A
Andre Weinand 已提交
428 429
	}

I
isidor 已提交
430
	scopes(frameId: number, threadId: number): Promise<DebugProtocol.ScopesResponse> {
I
isidor 已提交
431 432
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
433
		}
I
isidor 已提交
434 435 436

		const token = this.getNewCancellationToken(threadId);
		return this.raw.scopes({ frameId }, token);
A
Andre Weinand 已提交
437 438
	}

I
isidor 已提交
439
	variables(variablesReference: number, threadId: number | undefined, filter: 'indexed' | 'named' | undefined, start: number | undefined, count: number | undefined): Promise<DebugProtocol.VariablesResponse> {
I
isidor 已提交
440 441
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
442
		}
I
isidor 已提交
443 444 445

		const token = threadId ? this.getNewCancellationToken(threadId) : undefined;
		return this.raw.variables({ variablesReference, filter, start, count }, token);
A
Andre Weinand 已提交
446 447
	}

448
	evaluate(expression: string, frameId: number, context?: string): Promise<DebugProtocol.EvaluateResponse> {
I
isidor 已提交
449 450
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
451
		}
I
isidor 已提交
452 453

		return this.raw.evaluate({ expression, frameId, context });
A
Andre Weinand 已提交
454 455
	}

I
isidor 已提交
456 457 458
	async restartFrame(frameId: number, threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
459
		}
I
isidor 已提交
460 461

		await this.raw.restartFrame({ frameId }, threadId);
A
Andre Weinand 已提交
462 463
	}

I
isidor 已提交
464 465 466
	async next(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
467
		}
I
isidor 已提交
468 469

		await this.raw.next({ threadId });
A
Andre Weinand 已提交
470 471
	}

I
isidor 已提交
472 473 474
	async stepIn(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
475
		}
I
isidor 已提交
476 477

		await this.raw.stepIn({ threadId });
A
Andre Weinand 已提交
478 479
	}

I
isidor 已提交
480 481 482
	async stepOut(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
483
		}
I
isidor 已提交
484 485

		await this.raw.stepOut({ threadId });
A
Andre Weinand 已提交
486 487
	}

I
isidor 已提交
488 489 490
	async stepBack(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
491
		}
I
isidor 已提交
492 493

		await this.raw.stepBack({ threadId });
A
Andre Weinand 已提交
494 495
	}

I
isidor 已提交
496 497 498
	async continue(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
499
		}
I
isidor 已提交
500 501

		await this.raw.continue({ threadId });
A
Andre Weinand 已提交
502 503
	}

I
isidor 已提交
504 505 506
	async reverseContinue(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
507
		}
I
isidor 已提交
508 509

		await this.raw.reverseContinue({ threadId });
A
Andre Weinand 已提交
510 511
	}

I
isidor 已提交
512 513 514
	async pause(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
515
		}
I
isidor 已提交
516 517

		await this.raw.pause({ threadId });
A
Andre Weinand 已提交
518 519
	}

I
isidor 已提交
520 521 522
	async terminateThreads(threadIds?: number[]): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
523
		}
I
isidor 已提交
524 525

		await this.raw.terminateThreads({ threadIds });
A
Andre Weinand 已提交
526 527
	}

528
	setVariable(variablesReference: number, name: string, value: string): Promise<DebugProtocol.SetVariableResponse> {
I
isidor 已提交
529 530
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
531
		}
I
isidor 已提交
532 533

		return this.raw.setVariable({ variablesReference, name, value });
A
Andre Weinand 已提交
534 535
	}

I
isidor 已提交
536
	gotoTargets(source: DebugProtocol.Source, line: number, column?: number): Promise<DebugProtocol.GotoTargetsResponse> {
I
isidor 已提交
537 538
		if (!this.raw) {
			throw new Error('no debug adapter');
I
isidor 已提交
539
		}
I
isidor 已提交
540 541

		return this.raw.gotoTargets({ source, line, column });
I
isidor 已提交
542 543 544
	}

	goto(threadId: number, targetId: number): Promise<DebugProtocol.GotoResponse> {
I
isidor 已提交
545 546
		if (!this.raw) {
			throw new Error('no debug adapter');
I
isidor 已提交
547
		}
I
isidor 已提交
548 549

		return this.raw.goto({ threadId, targetId });
I
isidor 已提交
550 551
	}

552
	loadSource(resource: URI): Promise<DebugProtocol.SourceResponse> {
553
		if (!this.raw) {
554
			return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
555 556 557 558 559 560 561 562
		}

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

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

I
isidor 已提交
570 571 572 573 574 575 576 577 578 579
	async getLoadedSources(): Promise<Source[]> {
		if (!this.raw) {
			return Promise.reject(new Error('no debug adapter'));
		}

		const response = await this.raw.loadedSources({});
		if (response.body && response.body.sources) {
			return response.body.sources.map(src => this.getSource(src));
		} else {
			return [];
A
Andre Weinand 已提交
580 581 582
		}
	}

583
	async completions(frameId: number | undefined, text: string, position: Position, overwriteBefore: number, token: CancellationToken): Promise<DebugProtocol.CompletionsResponse> {
I
isidor 已提交
584 585 586 587
		if (!this.raw) {
			return Promise.reject(new Error('no debug adapter'));
		}

588
		return this.raw.completions({
I
isidor 已提交
589 590 591 592 593
			frameId,
			text,
			column: position.column,
			line: position.lineNumber,
		}, token);
A
Andre Weinand 已提交
594 595 596 597
	}

	//---- threads

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

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

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

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

I
isidor 已提交
678 679 680
	private async fetchThreads(stoppedDetails?: IRawStoppedDetails): Promise<void> {
		if (this.raw) {
			const response = await this.raw.threads();
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
				});
			}
I
isidor 已提交
688
		}
A
Andre Weinand 已提交
689 690
	}

691 692 693 694 695
	initializeForTest(raw: RawDebugSession): void {
		this.raw = raw;
		this.registerListeners();
	}

A
Andre Weinand 已提交
696 697
	//---- private

I
isidor 已提交
698
	private registerListeners(): void {
I
isidor 已提交
699 700 701 702
		if (!this.raw) {
			return;
		}

I
isidor 已提交
703
		this.rawListeners.push(this.raw.onDidInitialize(async () => {
I
isidor 已提交
704
			aria.status(nls.localize('debuggingStarted', "Debugging started."));
I
isidor 已提交
705
			const sendConfigurationDone = async () => {
706
				if (this.raw && this.raw.capabilities.supportsConfigurationDoneRequest) {
I
isidor 已提交
707 708 709
					try {
						await this.raw.configurationDone();
					} catch (e) {
I
isidor 已提交
710
						// Disconnect the debug session on configuration done error #10596
711 712
						if (this.raw) {
							this.raw.disconnect();
I
isidor 已提交
713
						}
I
isidor 已提交
714
					}
I
isidor 已提交
715
				}
716 717

				return undefined;
I
isidor 已提交
718 719 720
			};

			// Send all breakpoints
I
isidor 已提交
721 722
			try {
				await this.debugService.sendAllBreakpoints(this);
I
isidor 已提交
723
			} finally {
I
isidor 已提交
724
				await sendConfigurationDone();
I
isidor 已提交
725
				await this.fetchThreads();
I
isidor 已提交
726
			}
I
isidor 已提交
727 728
		}));

I
isidor 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741
		this.rawListeners.push(this.raw.onDidStop(async event => {
			await this.fetchThreads(event.body);
			const thread = typeof event.body.threadId === 'number' ? this.getThread(event.body.threadId) : undefined;
			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
				const promises = this.model.fetchCallStack(<Thread>thread);
				const focus = async () => {
					if (!event.body.preserveFocusHint && thread.getCallStack().length) {
						await this.debugService.focusStackFrame(undefined, thread);
						if (thread.stoppedDetails) {
							if (this.configurationService.getValue<IDebugConfiguration>('debug').openDebug === 'openOnDebugBreak') {
								this.viewletService.openViewlet(VIEWLET_ID);
I
isidor 已提交
742
							}
743

I
isidor 已提交
744 745 746
							if (this.configurationService.getValue<IDebugConfiguration>('debug').focusWindowOnBreak) {
								this.hostService.focus();
							}
747
						}
I
isidor 已提交
748 749 750 751 752 753 754 755 756
					}
				};

				await promises.topCallStack;
				focus();
				await promises.wholeCallStack;
				if (!this.debugService.getViewModel().focusedStackFrame) {
					// The top stack frame can be deemphesized so try to focus again #68616
					focus();
I
isidor 已提交
757
				}
I
isidor 已提交
758 759
			}
			this._onDidChangeState.fire();
I
isidor 已提交
760 761
		}));

762
		this.rawListeners.push(this.raw.onDidThread(event => {
I
isidor 已提交
763 764 765 766
			if (event.body.reason === 'started') {
				// debounce to reduce threadsRequest frequency and improve performance
				if (!this.fetchThreadsScheduler) {
					this.fetchThreadsScheduler = new RunOnceScheduler(() => {
767
						this.fetchThreads();
I
isidor 已提交
768 769 770 771 772 773 774 775
					}, 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);
I
isidor 已提交
776 777 778 779 780 781
				const viewModel = this.debugService.getViewModel();
				const focusedThread = viewModel.focusedThread;
				if (focusedThread && event.body.threadId === focusedThread.threadId) {
					// De-focus the thread in case it was focused
					this.debugService.focusStackFrame(undefined, undefined, viewModel.focusedSession, false);
				}
I
isidor 已提交
782 783 784
			}
		}));

I
isidor 已提交
785
		this.rawListeners.push(this.raw.onDidTerminateDebugee(async event => {
I
isidor 已提交
786 787
			aria.status(nls.localize('debuggingStopped', "Debugging stopped."));
			if (event.body && event.body.restart) {
I
isidor 已提交
788
				await this.debugService.restartSession(this, event.body.restart);
I
isidor 已提交
789
			} else if (this.raw) {
I
isidor 已提交
790
				await this.raw.disconnect();
I
isidor 已提交
791 792 793
			}
		}));

794
		this.rawListeners.push(this.raw.onDidContinued(event => {
I
isidor 已提交
795
			const threadId = event.body.allThreadsContinued !== false ? undefined : event.body.threadId;
I
isidor 已提交
796 797 798 799 800 801 802 803 804 805
			if (threadId) {
				const tokens = this.cancellationMap.get(threadId);
				this.cancellationMap.delete(threadId);
				if (tokens) {
					tokens.forEach(t => t.cancel());
				}
			} else {
				this.cancelAllRequests();
			}

I
isidor 已提交
806
			this.model.clearThreads(this.getId(), false, threadId);
807
			this._onDidChangeState.fire();
I
isidor 已提交
808 809
		}));

810
		let outpuPromises: Promise<void>[] = [];
I
isidor 已提交
811
		this.rawListeners.push(this.raw.onDidOutput(async event => {
I
isidor 已提交
812
			if (!event.body || !this.raw) {
I
isidor 已提交
813 814 815 816 817 818 819
				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
820
				if (this.raw.customTelemetryService && this.telemetryService.isOptedIn) {
I
isidor 已提交
821
					// __GDPR__TODO__ We're sending events in the name of the debug extension and we can not ensure that those are declared correctly.
822
					this.raw.customTelemetryService.publicLog(event.body.output, event.body.data);
I
isidor 已提交
823 824 825 826 827 828
				}

				return;
			}

			// Make sure to append output in the correct order by properly waiting on preivous promises #33822
829
			const waitFor = outpuPromises.slice();
I
isidor 已提交
830
			const source = event.body.source && event.body.line ? {
I
isidor 已提交
831 832 833 834
				lineNumber: event.body.line,
				column: event.body.column ? event.body.column : 1,
				source: this.getSource(event.body.source)
			} : undefined;
I
isidor 已提交
835 836 837 838 839 840 841 842 843 844 845

			if (event.body.group === 'start' || event.body.group === 'startCollapsed') {
				const expanded = event.body.group === 'start';
				this.repl.startGroup(event.body.output || '', expanded, source);
				return;
			}
			if (event.body.group === 'end') {
				this.repl.endGroup();
				// Do not return, the end event can have additional output in it
			}

I
isidor 已提交
846
			if (event.body.variablesReference) {
I
isidor 已提交
847
				const container = new ExpressionContainer(this, undefined, event.body.variablesReference, generateUuid());
I
isidor 已提交
848 849 850
				outpuPromises.push(container.getChildren().then(async children => {
					await Promise.all(waitFor);
					children.forEach(child => {
I
isidor 已提交
851
						// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
I
isidor 已提交
852
						(<any>child).name = null;
I
isidor 已提交
853
						this.appendToRepl(child, outputSeverity, source);
I
isidor 已提交
854
					});
I
isidor 已提交
855 856
				}));
			} else if (typeof event.body.output === 'string') {
I
isidor 已提交
857 858
				await Promise.all(waitFor);
				this.appendToRepl(event.body.output, outputSeverity, source);
I
isidor 已提交
859
			}
I
isidor 已提交
860 861 862

			await Promise.all(outpuPromises);
			outpuPromises = [];
I
isidor 已提交
863 864
		}));

865
		this.rawListeners.push(this.raw.onDidBreakpoint(event => {
I
isidor 已提交
866
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
D
Dmitry Gozman 已提交
867 868
			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 已提交
869

I
isidor 已提交
870
			if (event.body.reason === 'new' && event.body.breakpoint.source && event.body.breakpoint.line) {
I
isidor 已提交
871 872 873 874 875 876 877
				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 已提交
878
					const data = new Map<string, DebugProtocol.Breakpoint>([[bps[0].getId(), event.body.breakpoint]]);
879
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
				}
			}

			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 已提交
897
					const data = new Map<string, DebugProtocol.Breakpoint>([[breakpoint.getId(), event.body.breakpoint]]);
898
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
899 900
				}
				if (functionBreakpoint) {
I
isidor 已提交
901
					const data = new Map<string, DebugProtocol.Breakpoint>([[functionBreakpoint.getId(), event.body.breakpoint]]);
902
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
903 904 905 906
				}
			}
		}));

907
		this.rawListeners.push(this.raw.onDidLoadedSource(event => {
I
isidor 已提交
908 909 910 911 912 913
			this._onDidLoadedSource.fire({
				reason: event.body.reason,
				source: this.getSource(event.body.source)
			});
		}));

914
		this.rawListeners.push(this.raw.onDidCustomEvent(event => {
I
isidor 已提交
915 916 917
			this._onDidCustomEvent.fire(event);
		}));

918
		this.rawListeners.push(this.raw.onDidExitAdapter(event => {
I
isidor 已提交
919
			this.initialized = true;
920
			this.model.setBreakpointSessionData(this.getId(), this.capabilities, undefined);
I
isidor 已提交
921
			this.shutdown();
A
Andre Weinand 已提交
922
			this._onDidEndAdapter.fire(event);
923 924 925
		}));
	}

I
isidor 已提交
926 927
	// Disconnects and clears state. Session can be initialized again for a new connection.
	private shutdown(): void {
928
		dispose(this.rawListeners);
I
isidor 已提交
929
		if (this.raw) {
I
isidor 已提交
930 931
			this.raw.disconnect();
			this.raw.dispose();
I
isidor 已提交
932 933
			this.raw = undefined;
		}
I
isidor 已提交
934 935
		this.fetchThreadsScheduler = undefined;
		this.model.clearThreads(this.getId(), true);
936
		this._onDidChangeState.fire();
937 938 939 940
	}

	//---- sources

I
isidor 已提交
941
	getSourceForUri(uri: URI): Source | undefined {
I
isidor 已提交
942
		return this.sources.get(this.getUriKey(uri));
943 944
	}

I
isidor 已提交
945
	getSource(raw?: DebugProtocol.Source): Source {
946
		let source = new Source(raw, this.getId());
I
isidor 已提交
947
		const uriKey = this.getUriKey(source.uri);
A
Andre Weinand 已提交
948 949 950 951
		const found = this.sources.get(uriKey);
		if (found) {
			source = found;
			// merge attributes of new into existing
952 953 954 955 956 957
			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 已提交
958
			this.sources.set(uriKey, source);
959 960 961 962
		}

		return source;
	}
I
isidor 已提交
963

I
isidor 已提交
964 965 966 967 968 969 970 971 972 973
	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 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987
	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 已提交
988
	private getUriKey(uri: URI): string {
A
Andre Weinand 已提交
989
		// TODO: the following code does not make sense if uri originates from a different platform
I
isidor 已提交
990 991
		return platform.isLinux ? uri.toString() : uri.toString().toLowerCase();
	}
I
isidor 已提交
992 993 994

	// REPL

I
isidor 已提交
995
	getReplElements(): IReplElement[] {
996 997 998
		return this.repl.getReplElements();
	}

999 1000 1001 1002
	hasSeparateRepl(): boolean {
		return !this.parentSession || this._options.repl !== 'mergeWithParent';
	}

1003 1004
	removeReplExpressions(): void {
		this.repl.removeReplExpressions();
I
isidor 已提交
1005 1006
	}

1007
	async addReplExpression(stackFrame: IStackFrame | undefined, name: string): Promise<void> {
1008
		await this.repl.addReplExpression(this, stackFrame, name);
1009 1010
		// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
		variableSetEmitter.fire();
I
isidor 已提交
1011 1012
	}

1013
	appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void {
D
Dmitry Gozman 已提交
1014
		this.repl.appendToRepl(this, data, severity, source);
I
isidor 已提交
1015 1016
	}

1017
	logToRepl(sev: severity, args: any[], frame?: { uri: URI, line: number, column: number }) {
1018
		this.repl.logToRepl(this, sev, args, frame);
I
isidor 已提交
1019
	}
1020
}