rawDebugSession.ts 11.0 KB
Newer Older
E
Erich Gamma 已提交
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.
 *--------------------------------------------------------------------------------------------*/

6
import nls = require('vs/nls');
E
Erich Gamma 已提交
7 8 9 10
import cp = require('child_process');
import fs = require('fs');
import net = require('net');
import platform = require('vs/base/common/platform');
11
import { Action } from 'vs/base/common/actions';
E
Erich Gamma 已提交
12
import errors = require('vs/base/common/errors');
I
isidor 已提交
13
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
14
import severity from 'vs/base/common/severity';
15
import { AIAdapter } from 'vs/base/node/aiAdapter';
E
Erich Gamma 已提交
16 17 18 19
import debug = require('vs/workbench/parts/debug/common/debug');
import { Adapter } from 'vs/workbench/parts/debug/node/debugAdapter';
import v8 = require('vs/workbench/parts/debug/node/v8Protocol');
import stdfork = require('vs/base/node/stdFork');
20
import { IMessageService, CloseAction } from 'vs/platform/message/common/message';
E
Erich Gamma 已提交
21
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
22
import { shell } from 'electron';
E
Erich Gamma 已提交
23 24 25 26

export class RawDebugSession extends v8.V8Protocol implements debug.IRawDebugSession {
	private serverProcess: cp.ChildProcess;
	private socket: net.Socket = null;
I
isidor 已提交
27
	private cachedInitServer: TPromise<void>;
E
Erich Gamma 已提交
28 29
	private startTime: number;
	private stopServerPending: boolean;
30
	public isAttach: boolean;
31
	public restarted: boolean;
32
	public capabilities: DebugProtocol.Capabilites;
E
Erich Gamma 已提交
33 34 35 36 37

	constructor(
		private messageService: IMessageService,
		private telemetryService: ITelemetryService,
		private debugServerPort: number,
38 39
		private adapter: Adapter,
		private telemtryAdapter: AIAdapter
E
Erich Gamma 已提交
40 41
	) {
		super();
42
		this.capabilities = {};
E
Erich Gamma 已提交
43 44
	}

I
isidor 已提交
45
	private initServer(): TPromise<void> {
E
Erich Gamma 已提交
46 47 48 49 50 51 52 53 54
		if (this.cachedInitServer) {
			return this.cachedInitServer;
		}

		const serverPromise = this.debugServerPort ? this.connectServer(this.debugServerPort) : this.startServer();
		this.cachedInitServer = serverPromise.then(() => {
				this.startTime = new Date().getTime();
			}, err => {
				this.cachedInitServer = null;
I
isidor 已提交
55
				return TPromise.wrapError(err);
E
Erich Gamma 已提交
56 57 58 59 60 61 62 63
			}
		);

		return this.cachedInitServer;
	}

	protected send(command: string, args: any): TPromise<DebugProtocol.Response> {
		return this.initServer().then(() => super.send(command, args).then(response => response, (errorResponse: DebugProtocol.ErrorResponse) => {
I
isidor 已提交
64 65
			const error = errorResponse.body ? errorResponse.body.error : null;
			const message = error ? debug.formatPII(error.format, false, error.variables) : errorResponse.message;
E
Erich Gamma 已提交
66
			if (error && error.sendTelemetry) {
67 68
				this.telemetryService.publicLog('debugProtocolErrorResponse', { error: message });
				this.telemtryAdapter.log('debugProtocolErrorResponse', { error: message });
E
Erich Gamma 已提交
69 70
			}

71 72 73 74 75 76 77 78
			if (error && error.url) {
				const label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', "More Info");
				return TPromise.wrapError(errors.create(message, { actions: [CloseAction, new Action('debug.moreInfo', label, null, true, () => {
					shell.openExternal(error.url);
					return TPromise.as(null);
				})]}));
			}

I
isidor 已提交
79
			return TPromise.wrapError(new Error(message));
E
Erich Gamma 已提交
80 81 82 83
		}));
	}

	public initialize(args: DebugProtocol.InitializeRequestArguments): TPromise<DebugProtocol.InitializeResponse> {
I
isidor 已提交
84
		return this.send('initialize', args).then(response => {
85
			this.capabilities = response.body || this.capabilities;
I
isidor 已提交
86 87
			return response;
		});
E
Erich Gamma 已提交
88 89 90
	}

	public launch(args: DebugProtocol.LaunchRequestArguments): TPromise<DebugProtocol.LaunchResponse> {
91
		this.isAttach = false;
E
Erich Gamma 已提交
92 93 94 95
		return this.sendAndLazyEmit('launch', args);
	}

	public attach(args: DebugProtocol.AttachRequestArguments): TPromise<DebugProtocol.AttachResponse> {
96
		this.isAttach = true;
E
Erich Gamma 已提交
97 98 99
		return this.sendAndLazyEmit('attach', args);
	}

100
	public next(args: DebugProtocol.NextArguments): TPromise<DebugProtocol.NextResponse> {
E
Erich Gamma 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
		return this.sendAndLazyEmit('next', args);
	}

	public stepIn(args: DebugProtocol.StepInArguments): TPromise<DebugProtocol.StepInResponse> {
		return this.sendAndLazyEmit('stepIn', args);
	}

	public stepOut(args: DebugProtocol.StepOutArguments): TPromise<DebugProtocol.StepOutResponse> {
		return this.sendAndLazyEmit('stepOut', args);
	}

	public continue(args: DebugProtocol.ContinueArguments): TPromise<DebugProtocol.ContinueResponse> {
		return this.sendAndLazyEmit('continue', args);
	}

I
isidor 已提交
116 117 118
	// node sometimes sends "stopped" events earlier than the response for the "step" request.
	// due to this we only emit "continued" if we did not miss a stopped event.
	// we do not emit straight away to reduce viewlet flickering.
E
Erich Gamma 已提交
119
	private sendAndLazyEmit(command: string, args: any, eventType = debug.SessionEvents.CONTINUED): TPromise<DebugProtocol.Response> {
I
isidor 已提交
120
		const count = this.flowEventsCount;
E
Erich Gamma 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
		return this.send(command, args).then(response => {
			setTimeout(() => {
				if (this.flowEventsCount === count) {
					this.emit(eventType);
				}
			}, 500);

			return response;
		});
	}

	public pause(args: DebugProtocol.PauseArguments): TPromise<DebugProtocol.PauseResponse> {
		return this.send('pause', args);
	}

136 137 138 139 140
	public disconnect(restart = false, force = false): TPromise<DebugProtocol.DisconnectResponse> {
		if (this.stopServerPending && force) {
			return this.stopServer();
		}

E
Erich Gamma 已提交
141
		if ((this.serverProcess || this.socket) && !this.stopServerPending) {
142 143
			// point of no return: from now on don't report any errors
			this.stopServerPending = true;
144
			this.restarted = restart;
I
isidor 已提交
145
			return this.send('disconnect', { restart: restart }).then(() => this.stopServer(), () => this.stopServer());
E
Erich Gamma 已提交
146 147
		}

A
Alex Dima 已提交
148
		return TPromise.as(null);
E
Erich Gamma 已提交
149 150 151 152 153 154
	}

	public setBreakpoints(args: DebugProtocol.SetBreakpointsArguments): TPromise<DebugProtocol.SetBreakpointsResponse> {
		return this.send('setBreakpoints', args);
	}

I
isidor 已提交
155 156 157 158
	public setFunctionBreakpoints(args: DebugProtocol.SetFunctionBreakpointsArguments): TPromise<DebugProtocol.SetFunctionBreakpointsResponse> {
		return this.send('setFunctionBreakpoints', args);
	}

E
Erich Gamma 已提交
159 160 161 162
	public setExceptionBreakpoints(args: DebugProtocol.SetExceptionBreakpointsArguments): TPromise<DebugProtocol.SetExceptionBreakpointsResponse> {
		return this.send('setExceptionBreakpoints', args);
	}

163 164 165 166
	public configurationDone(): TPromise<DebugProtocol.ConfigurationDoneResponse> {
		return this.send('configurationDone', null);
	}

E
Erich Gamma 已提交
167 168 169 170 171 172 173 174
	public stackTrace(args: DebugProtocol.StackTraceArguments): TPromise<DebugProtocol.StackTraceResponse> {
		return this.send('stackTrace', args);
	}

	public scopes(args: DebugProtocol.ScopesArguments): TPromise<DebugProtocol.ScopesResponse> {
		return this.send('scopes', args);
	}

175
	public variables(args: DebugProtocol.VariablesArguments): TPromise<DebugProtocol.VariablesResponse> {
E
Erich Gamma 已提交
176 177 178
		return this.send('variables', args);
	}

179
	public source(args: DebugProtocol.SourceArguments): TPromise<DebugProtocol.SourceResponse> {
E
Erich Gamma 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
		return this.send('source', args);
	}

	public threads(): TPromise<DebugProtocol.ThreadsResponse> {
		return this.send('threads', null);
	}

	public evaluate(args: DebugProtocol.EvaluateArguments): TPromise<DebugProtocol.EvaluateResponse> {
		return this.send('evaluate', args);
	}

	public getLengthInSeconds(): number {
		return (new Date().getTime() - this.startTime) / 1000;
	}

	public getType(): string {
		return this.adapter.type;
	}

I
isidor 已提交
199 200
	private connectServer(port: number): TPromise<void> {
		return new TPromise<void>((c, e) => {
201
			this.socket = net.createConnection(port, '127.0.0.1', () => {
E
Erich Gamma 已提交
202 203 204 205 206 207 208 209 210
				this.connect(this.socket, <any>this.socket);
				c(null);
			});
			this.socket.on('error', (err: any) => {
				e(err);
			});
		});
	}

I
isidor 已提交
211
	private startServer(): TPromise<any> {
E
Erich Gamma 已提交
212
		if (!this.adapter.program) {
I
isidor 已提交
213
			return TPromise.wrapError(new Error(nls.localize('noDebugAdapterExtensionInstalled', "No extension installed for '{0}' debugging.", this.adapter.type)));
E
Erich Gamma 已提交
214 215 216 217 218 219
		}

		return this.getLaunchDetails().then(d => this.launchServer(d).then(() => {
			this.serverProcess.on('error', (err: Error) => this.onServerError(err));
			this.serverProcess.on('exit', (code: number, signal: string) => this.onServerExit());

I
isidor 已提交
220 221 222 223
			const sanitize = (s: string) => s.toString().replace(/\r?\n$/mg, '');
			// this.serverProcess.stdout.on('data', (data: string) => {
			// 	console.log('%c' + sanitize(data), 'background: #ddd; font-style: italic;');
			// });
E
Erich Gamma 已提交
224 225 226 227 228 229 230 231
			this.serverProcess.stderr.on('data', (data: string) => {
				console.log(sanitize(data));
			});

			this.connect(this.serverProcess.stdout, this.serverProcess.stdin);
		}));
	}

I
isidor 已提交
232 233
	private launchServer(launch: { command: string, argv: string[] }): TPromise<void> {
		return new TPromise<void>((c, e) => {
E
Erich Gamma 已提交
234
			if (launch.command === 'node') {
235
				stdfork.fork(launch.argv[0], launch.argv.slice(1), {}, (err, child) => {
E
Erich Gamma 已提交
236
					if (err) {
I
isidor 已提交
237
						e(new Error(nls.localize('unableToLaunchDebugAdapter', "Unable to launch debug adapter from {0}.", launch.argv[0])));
E
Erich Gamma 已提交
238 239
					}
					this.serverProcess = child;
I
isidor 已提交
240
					c(null);
E
Erich Gamma 已提交
241 242 243 244 245 246 247 248 249
				});
			} else {
				this.serverProcess = cp.spawn(launch.command, launch.argv, {
					stdio: [
						'pipe', 	// stdin
						'pipe', 	// stdout
						'pipe'		// stderr
					],
				});
I
isidor 已提交
250
				c(null);
E
Erich Gamma 已提交
251 252 253 254
			}
		});
	}

I
isidor 已提交
255
	private stopServer(): TPromise<any> {
E
Erich Gamma 已提交
256 257 258 259 260 261 262 263

		if (this.socket !== null) {
			this.socket.end();
			this.cachedInitServer = null;
			this.emit(debug.SessionEvents.SERVER_EXIT);
		}

		if (!this.serverProcess) {
I
isidor 已提交
264
			return TPromise.as(null);
E
Erich Gamma 已提交
265 266 267 268
		}

		this.stopServerPending = true;

I
isidor 已提交
269
		let ret: TPromise<void>;
E
Erich Gamma 已提交
270 271 272 273
		// when killing a process in windows its child
		// processes are *not* killed but become root
		// processes. Therefore we use TASKKILL.EXE
		if (platform.isWindows) {
I
isidor 已提交
274
			ret = new TPromise<void>((c, e) => {
I
isidor 已提交
275
				const killer = cp.exec(`taskkill /F /T /PID ${this.serverProcess.pid}`, function (err, stdout, stderr) {
E
Erich Gamma 已提交
276 277 278 279 280 281 282 283 284
					if (err) {
						return e(err);
					}
				});
				killer.on('exit', c);
				killer.on('error', e);
			});
		} else {
			this.serverProcess.kill('SIGTERM');
I
isidor 已提交
285
			ret = TPromise.as(null);
E
Erich Gamma 已提交
286 287 288 289 290 291
		}

		return ret;
	}

	private getLaunchDetails(): TPromise<{ command: string; argv: string[]; }> {
I
isidor 已提交
292
		return new TPromise((c, e) => {
E
Erich Gamma 已提交
293 294
			fs.exists(this.adapter.program, exists => {
				if (exists) {
295
					c(null);
E
Erich Gamma 已提交
296
				} else {
I
isidor 已提交
297
					e(new Error(nls.localize('debugAdapterBinNotFound', "DebugAdapter bin folder not found on path {0}.", this.adapter.program)));
E
Erich Gamma 已提交
298 299
				}
			});
300
		}).then(() => {
E
Erich Gamma 已提交
301 302 303
			if (this.adapter.runtime) {
				return {
					command: this.adapter.runtime,
304
					argv: (this.adapter.runtimeArgs || []).concat([this.adapter.program]).concat(this.adapter.args || [])
E
Erich Gamma 已提交
305 306 307 308
				};
			}

			return {
309 310
				command: this.adapter.program,
				argv: this.adapter.args || []
E
Erich Gamma 已提交
311 312 313 314
			};
		});
	}

315 316
	protected onServerError(err: Error): void {
		this.messageService.show(severity.Error, nls.localize('stoppingDebugAdapter', "{0}. Stopping the debug adapter.", err.message));
E
Erich Gamma 已提交
317 318 319 320 321 322 323
		this.stopServer().done(null, errors.onUnexpectedError);
	}

	private onServerExit(): void {
		this.serverProcess = null;
		this.cachedInitServer = null;
		if (!this.stopServerPending) {
324
			this.messageService.show(severity.Error, nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"));
E
Erich Gamma 已提交
325 326 327 328
		}
		this.emit(debug.SessionEvents.SERVER_EXIT);
	}
}