debugSession.ts 31.8 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 { IOpenerService } from 'vs/platform/opener/common/opener';
34
import { variableSetEmitter } from 'vs/workbench/contrib/debug/browser/variablesView';
I
isidor 已提交
35
import { CancellationTokenSource, CancellationToken } from 'vs/base/common/cancellation';
I
isidor 已提交
36
import { distinct } from 'vs/base/common/arrays';
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,
77
		@IOpenerService private readonly openerService: IOpenerService
I
isidor 已提交
78
	) {
A
Andre Weinand 已提交
79
		this.id = generateUuid();
80 81 82 83 84 85
		this._options = options || {};
		if (this.hasSeparateRepl()) {
			this.repl = new ReplModel();
		} else {
			this.repl = (this.parentSession as DebugSession).repl;
		}
86
		this.repl.onDidChangeElements(() => this._onDidChangeREPLElements.fire());
87 88
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

I
isidor 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
		try {
			const customTelemetryService = await dbgr.getCustomTelemetryService();
			const debugAdapter = await dbgr.createDebugAdapter(this);
			this.raw = new RawDebugSession(debugAdapter, dbgr, this.telemetryService, customTelemetryService, this.extensionHostDebugService, this.openerService);

			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 已提交
208
			});
I
isidor 已提交
209

I
isidor 已提交
210 211
			this.initialized = true;
			this._onDidChangeState.fire();
I
isidor 已提交
212 213 214 215 216 217
			this.model.setExceptionBreakpoints(this.raw!.capabilities.exceptionBreakpointFilters || []);
		} catch (err) {
			this.initialized = true;
			this._onDidChangeState.fire();
			throw err;
		}
I
isidor 已提交
218 219
	}

A
Andre Weinand 已提交
220 221 222
	/**
	 * launch or attach to the debuggee
	 */
I
isidor 已提交
223 224 225 226
	async launchOrAttach(config: IConfig): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
		}
A
Andre Weinand 已提交
227

I
isidor 已提交
228 229 230
		// __sessionID only used for EH debugging (but we add it always for now...)
		config.__sessionId = this.getId();
		await this.raw.launchOrAttach(config);
A
Andre Weinand 已提交
231 232 233 234 235 236

	}

	/**
	 * end the current debug adapter session
	 */
I
isidor 已提交
237 238 239 240 241 242 243 244 245 246
	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 已提交
247 248 249 250 251 252
		}
	}

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

		this.cancelAllRequests();
		await this.raw.disconnect(restart);
A
Andre Weinand 已提交
260 261 262 263 264
	}

	/**
	 * restart debug adapter session
	 */
I
isidor 已提交
265 266 267
	async restart(): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
268 269
		}

I
isidor 已提交
270 271 272
		this.cancelAllRequests();
		await this.raw.restart();
	}
A
Andre Weinand 已提交
273

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

279
		if (!this.raw.readyForBreakpoints) {
I
isidor 已提交
280
			return Promise.resolve(undefined);
A
Andre Weinand 已提交
281 282
		}

I
isidor 已提交
283
		const rawSource = this.getRawSource(modelUri);
A
Andre Weinand 已提交
284 285 286 287
		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 已提交
288 289 290
		if (rawSource.path) {
			rawSource.path = normalizeDriveLetter(rawSource.path);
		}
A
Andre Weinand 已提交
291

I
isidor 已提交
292
		const response = await this.raw.setBreakpoints({
A
Andre Weinand 已提交
293
			source: rawSource,
294 295
			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 已提交
296
			sourceModified
I
isidor 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
		});
		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 已提交
315
			if (response && response.body) {
I
isidor 已提交
316
				const data = new Map<string, DebugProtocol.Breakpoint>();
I
isidor 已提交
317 318
				for (let i = 0; i < fbpts.length; i++) {
					data.set(fbpts[i].getId(), response.body.breakpoints[i]);
A
Andre Weinand 已提交
319
				}
320
				this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
A
Andre Weinand 已提交
321
			}
I
isidor 已提交
322
		}
A
Andre Weinand 已提交
323 324
	}

I
isidor 已提交
325 326 327
	async sendExceptionBreakpoints(exbpts: IExceptionBreakpoint[]): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
328
		}
329

I
isidor 已提交
330 331 332
		if (this.raw.readyForBreakpoints) {
			await this.raw.setExceptionBreakpoints({ filters: exbpts.map(exb => exb.filter) });
		}
A
Andre Weinand 已提交
333 334
	}

I
isidor 已提交
335 336 337
	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 已提交
338
		}
I
isidor 已提交
339 340 341 342 343 344
		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 已提交
345 346
	}

I
isidor 已提交
347 348 349
	async sendDataBreakpoints(dataBreakpoints: IDataBreakpoint[]): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
I
isidor 已提交
350 351
		}

I
isidor 已提交
352 353 354 355 356 357 358 359
		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 已提交
360 361 362 363
			}
		}
	}

I
isidor 已提交
364
	async breakpointsLocations(uri: URI, lineNumber: number): Promise<IPosition[]> {
I
isidor 已提交
365 366 367
		if (!this.raw) {
			throw new Error('no debug adapter');
		}
I
isidor 已提交
368

I
isidor 已提交
369 370 371 372
		const source = this.getRawSource(uri);
		const response = await this.raw.breakpointLocations({ source, line: lineNumber });
		if (!response.body || !response.body.breakpoints) {
			return [];
I
isidor 已提交
373
		}
I
isidor 已提交
374 375 376 377

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

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

380
	customRequest(request: string, args: any): Promise<DebugProtocol.Response> {
I
isidor 已提交
381 382
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
383
		}
I
isidor 已提交
384 385

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

388
	stackTrace(threadId: number, startFrame: number, levels: number): Promise<DebugProtocol.StackTraceResponse> {
I
isidor 已提交
389 390
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
391
		}
I
isidor 已提交
392 393 394

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

I
isidor 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409
	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 已提交
410
		}
I
isidor 已提交
411 412

		return undefined;
A
Andre Weinand 已提交
413 414
	}

I
isidor 已提交
415
	scopes(frameId: number, threadId: number): Promise<DebugProtocol.ScopesResponse> {
I
isidor 已提交
416 417
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
418
		}
I
isidor 已提交
419 420 421

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

I
isidor 已提交
424
	variables(variablesReference: number, threadId: number | undefined, filter: 'indexed' | 'named' | undefined, start: number | undefined, count: number | undefined): Promise<DebugProtocol.VariablesResponse> {
I
isidor 已提交
425 426
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
427
		}
I
isidor 已提交
428 429 430

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

433
	evaluate(expression: string, frameId: number, context?: string): Promise<DebugProtocol.EvaluateResponse> {
I
isidor 已提交
434 435
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
436
		}
I
isidor 已提交
437 438

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

I
isidor 已提交
441 442 443
	async restartFrame(frameId: number, threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
444
		}
I
isidor 已提交
445 446

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

I
isidor 已提交
449 450 451
	async next(threadId: number): Promise<void> {
		if (!this.raw) {
			throw new Error('no debug adapter');
A
Andre Weinand 已提交
452
		}
I
isidor 已提交
453 454

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

I
isidor 已提交
521
	gotoTargets(source: DebugProtocol.Source, line: number, column?: number): Promise<DebugProtocol.GotoTargetsResponse> {
I
isidor 已提交
522 523
		if (!this.raw) {
			throw new Error('no debug adapter');
I
isidor 已提交
524
		}
I
isidor 已提交
525 526

		return this.raw.gotoTargets({ source, line, column });
I
isidor 已提交
527 528 529
	}

	goto(threadId: number, targetId: number): Promise<DebugProtocol.GotoResponse> {
I
isidor 已提交
530 531
		if (!this.raw) {
			throw new Error('no debug adapter');
I
isidor 已提交
532
		}
I
isidor 已提交
533 534

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

537
	loadSource(resource: URI): Promise<DebugProtocol.SourceResponse> {
538
		if (!this.raw) {
539
			return Promise.reject(new Error('no debug adapter'));
A
Andre Weinand 已提交
540 541 542 543 544 545 546 547
		}

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

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

I
isidor 已提交
555 556 557 558 559 560 561 562 563 564
	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 已提交
565 566 567
		}
	}

I
isidor 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	async completions(frameId: number | undefined, text: string, position: Position, overwriteBefore: number, token: CancellationToken): Promise<CompletionItem[]> {
		if (!this.raw) {
			return Promise.reject(new Error('no debug adapter'));
		}

		const response = await this.raw.completions({
			frameId,
			text,
			column: position.column,
			line: position.lineNumber,
		}, token);

		const result: CompletionItem[] = [];
		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,
						kind: completionKindFromString(item.type || 'property'),
						filterText: (item.start && item.length) ? text.substr(item.start, item.length).concat(item.label) : undefined,
						range: Range.fromPositions(position.delta(0, -(item.length || overwriteBefore)), position),
						sortText: item.sortText
A
Andre Weinand 已提交
591 592 593 594
					});
				}
			});
		}
I
isidor 已提交
595 596

		return result;
A
Andre Weinand 已提交
597 598 599 600
	}

	//---- threads

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

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

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

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

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

	//---- private

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

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

				return undefined;
I
isidor 已提交
716 717 718
			};

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

I
isidor 已提交
727 728 729 730 731 732 733 734 735 736 737 738 739
		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 已提交
740
							}
741

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

				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 已提交
755
				}
I
isidor 已提交
756 757
			}
			this._onDidChangeState.fire();
I
isidor 已提交
758 759
		}));

760
		this.rawListeners.push(this.raw.onDidThread(event => {
I
isidor 已提交
761 762 763 764
			if (event.body.reason === 'started') {
				// debounce to reduce threadsRequest frequency and improve performance
				if (!this.fetchThreadsScheduler) {
					this.fetchThreadsScheduler = new RunOnceScheduler(() => {
765
						this.fetchThreads();
I
isidor 已提交
766 767 768 769 770 771 772 773
					}, 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 已提交
774 775 776 777 778 779
				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 已提交
780 781 782
			}
		}));

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

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

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

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

				return;
			}

			// Make sure to append output in the correct order by properly waiting on preivous promises #33822
827
			const waitFor = outpuPromises.slice();
I
isidor 已提交
828
			const source = event.body.source && event.body.line ? {
I
isidor 已提交
829 830 831 832 833
				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 已提交
834
				const container = new ExpressionContainer(this, undefined, event.body.variablesReference, generateUuid());
I
isidor 已提交
835 836 837
				outpuPromises.push(container.getChildren().then(async children => {
					await Promise.all(waitFor);
					children.forEach(child => {
I
isidor 已提交
838
						// Since we can not display multiple trees in a row, we are displaying these variables one after the other (ignoring their names)
I
isidor 已提交
839
						(<any>child).name = null;
I
isidor 已提交
840
						this.appendToRepl(child, outputSeverity, source);
I
isidor 已提交
841
					});
I
isidor 已提交
842 843
				}));
			} else if (typeof event.body.output === 'string') {
I
isidor 已提交
844 845
				await Promise.all(waitFor);
				this.appendToRepl(event.body.output, outputSeverity, source);
I
isidor 已提交
846
			}
I
isidor 已提交
847 848 849

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

852
		this.rawListeners.push(this.raw.onDidBreakpoint(event => {
I
isidor 已提交
853
			const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined;
D
Dmitry Gozman 已提交
854 855
			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 已提交
856

I
isidor 已提交
857
			if (event.body.reason === 'new' && event.body.breakpoint.source && event.body.breakpoint.line) {
I
isidor 已提交
858 859 860 861 862 863 864
				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 已提交
865
					const data = new Map<string, DebugProtocol.Breakpoint>([[bps[0].getId(), event.body.breakpoint]]);
866
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
				}
			}

			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 已提交
884
					const data = new Map<string, DebugProtocol.Breakpoint>([[breakpoint.getId(), event.body.breakpoint]]);
885
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
886 887
				}
				if (functionBreakpoint) {
I
isidor 已提交
888
					const data = new Map<string, DebugProtocol.Breakpoint>([[functionBreakpoint.getId(), event.body.breakpoint]]);
889
					this.model.setBreakpointSessionData(this.getId(), this.capabilities, data);
I
isidor 已提交
890 891 892 893
				}
			}
		}));

894
		this.rawListeners.push(this.raw.onDidLoadedSource(event => {
I
isidor 已提交
895 896 897 898 899 900
			this._onDidLoadedSource.fire({
				reason: event.body.reason,
				source: this.getSource(event.body.source)
			});
		}));

901
		this.rawListeners.push(this.raw.onDidCustomEvent(event => {
I
isidor 已提交
902 903 904
			this._onDidCustomEvent.fire(event);
		}));

905
		this.rawListeners.push(this.raw.onDidExitAdapter(event => {
I
isidor 已提交
906
			this.initialized = true;
907
			this.model.setBreakpointSessionData(this.getId(), this.capabilities, undefined);
A
Andre Weinand 已提交
908
			this._onDidEndAdapter.fire(event);
909 910 911
		}));
	}

912
	shutdown(): void {
913
		dispose(this.rawListeners);
914 915
		if (this.raw) {
			this.raw.disconnect();
I
isidor 已提交
916
			this.raw.dispose();
917
		}
918
		this.raw = undefined;
919 920
		this.model.clearThreads(this.getId(), true);
		this._onDidChangeState.fire();
921 922 923 924
	}

	//---- sources

I
isidor 已提交
925
	getSourceForUri(uri: URI): Source | undefined {
I
isidor 已提交
926
		return this.sources.get(this.getUriKey(uri));
927 928
	}

I
isidor 已提交
929
	getSource(raw?: DebugProtocol.Source): Source {
930
		let source = new Source(raw, this.getId());
I
isidor 已提交
931
		const uriKey = this.getUriKey(source.uri);
A
Andre Weinand 已提交
932 933 934 935
		const found = this.sources.get(uriKey);
		if (found) {
			source = found;
			// merge attributes of new into existing
936 937 938 939 940 941
			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 已提交
942
			this.sources.set(uriKey, source);
943 944 945 946
		}

		return source;
	}
I
isidor 已提交
947

I
isidor 已提交
948 949 950 951 952 953 954 955 956 957
	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 已提交
958 959 960 961 962 963 964 965 966 967 968 969 970 971
	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 已提交
972
	private getUriKey(uri: URI): string {
A
Andre Weinand 已提交
973
		// TODO: the following code does not make sense if uri originates from a different platform
I
isidor 已提交
974 975
		return platform.isLinux ? uri.toString() : uri.toString().toLowerCase();
	}
I
isidor 已提交
976 977 978

	// REPL

I
isidor 已提交
979
	getReplElements(): IReplElement[] {
980 981 982
		return this.repl.getReplElements();
	}

983 984 985 986
	hasSeparateRepl(): boolean {
		return !this.parentSession || this._options.repl !== 'mergeWithParent';
	}

987 988
	removeReplExpressions(): void {
		this.repl.removeReplExpressions();
I
isidor 已提交
989 990
	}

991
	async addReplExpression(stackFrame: IStackFrame | undefined, name: string): Promise<void> {
992
		await this.repl.addReplExpression(this, stackFrame, name);
993 994
		// Evaluate all watch expressions and fetch variables again since repl evaluation might have changed some.
		variableSetEmitter.fire();
I
isidor 已提交
995 996
	}

997
	appendToRepl(data: string | IExpression, severity: severity, source?: IReplElementSource): void {
D
Dmitry Gozman 已提交
998
		this.repl.appendToRepl(this, data, severity, source);
I
isidor 已提交
999 1000
	}

1001
	logToRepl(sev: severity, args: any[], frame?: { uri: URI, line: number, column: number }) {
1002
		this.repl.logToRepl(this, sev, args, frame);
I
isidor 已提交
1003
	}
1004
}