-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
debugAdapter.ts
386 lines (337 loc) · 12.4 KB
/
debugAdapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { exists } from 'vs/base/node/pfs';
import * as cp from 'child_process';
import * as stream from 'stream';
import * as nls from 'vs/nls';
import * as net from 'net';
import * as path from 'vs/base/common/path';
import * as strings from 'vs/base/common/strings';
import * as objects from 'vs/base/common/objects';
import * as platform from 'vs/base/common/platform';
import { ExtensionsChannelId } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IOutputService } from 'vs/workbench/contrib/output/common/output';
import { IDebugAdapterExecutable, IDebuggerContribution, IPlatformSpecificAdapterContribution, IDebugAdapterServer } from 'vs/workbench/contrib/debug/common/debug';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { AbstractDebugAdapter } from '../common/abstractDebugAdapter';
/**
* An implementation that communicates via two streams with the debug adapter.
*/
export abstract class StreamDebugAdapter extends AbstractDebugAdapter {
private static readonly TWO_CRLF = '\r\n\r\n';
private static readonly HEADER_LINESEPARATOR = /\r?\n/; // allow for non-RFC 2822 conforming line separators
private static readonly HEADER_FIELDSEPARATOR = /: */;
private outputStream: stream.Writable;
private rawData: Buffer;
private contentLength: number;
constructor() {
super();
}
protected connect(readable: stream.Readable, writable: stream.Writable): void {
this.outputStream = writable;
this.rawData = Buffer.allocUnsafe(0);
this.contentLength = -1;
readable.on('data', (data: Buffer) => this.handleData(data));
}
sendMessage(message: DebugProtocol.ProtocolMessage): void {
if (this.outputStream) {
const json = JSON.stringify(message);
this.outputStream.write(`Content-Length: ${Buffer.byteLength(json, 'utf8')}${StreamDebugAdapter.TWO_CRLF}${json}`, 'utf8');
}
}
private handleData(data: Buffer): void {
this.rawData = Buffer.concat([this.rawData, data]);
while (true) {
if (this.contentLength >= 0) {
if (this.rawData.length >= this.contentLength) {
const message = this.rawData.toString('utf8', 0, this.contentLength);
this.rawData = this.rawData.slice(this.contentLength);
this.contentLength = -1;
if (message.length > 0) {
try {
this.acceptMessage(<DebugProtocol.ProtocolMessage>JSON.parse(message));
} catch (e) {
this._onError.fire(new Error((e.message || e) + '\n' + message));
}
}
continue; // there may be more complete messages to process
}
} else {
const idx = this.rawData.indexOf(StreamDebugAdapter.TWO_CRLF);
if (idx !== -1) {
const header = this.rawData.toString('utf8', 0, idx);
const lines = header.split(StreamDebugAdapter.HEADER_LINESEPARATOR);
for (const h of lines) {
const kvPair = h.split(StreamDebugAdapter.HEADER_FIELDSEPARATOR);
if (kvPair[0] === 'Content-Length') {
this.contentLength = Number(kvPair[1]);
}
}
this.rawData = this.rawData.slice(idx + StreamDebugAdapter.TWO_CRLF.length);
continue;
}
}
break;
}
}
}
/**
* An implementation that connects to a debug adapter via a socket.
*/
export class SocketDebugAdapter extends StreamDebugAdapter {
private socket?: net.Socket;
constructor(private adapterServer: IDebugAdapterServer) {
super();
}
startSession(): Promise<void> {
return new Promise<void>((resolve, reject) => {
let connected = false;
this.socket = net.createConnection(this.adapterServer.port, this.adapterServer.host || '127.0.0.1', () => {
this.connect(this.socket!, this.socket!);
resolve();
connected = true;
});
this.socket.on('close', () => {
if (connected) {
this._onError.fire(new Error('connection closed'));
} else {
reject(new Error('connection closed'));
}
});
this.socket.on('error', error => {
if (connected) {
this._onError.fire(error);
} else {
reject(error);
}
});
});
}
stopSession(): Promise<void> {
// Cancel all sent promises on disconnect so debug trees are not left in a broken state #3666.
this.cancelPending();
if (this.socket) {
this.socket.end();
this.socket = undefined;
}
return Promise.resolve(undefined);
}
}
/**
* An implementation that launches the debug adapter as a separate process and communicates via stdin/stdout.
*/
export class ExecutableDebugAdapter extends StreamDebugAdapter {
private serverProcess: cp.ChildProcess;
constructor(private adapterExecutable: IDebugAdapterExecutable, private debugType: string, private readonly outputService?: IOutputService) {
super();
}
async startSession(): Promise<void> {
const command = this.adapterExecutable.command;
const args = this.adapterExecutable.args;
const options = this.adapterExecutable.options || {};
try {
// verify executables asynchronously
if (command) {
if (path.isAbsolute(command)) {
const commandExists = await exists(command);
if (!commandExists) {
throw new Error(nls.localize('debugAdapterBinNotFound', "Debug adapter executable '{0}' does not exist.", command));
}
} else {
// relative path
if (command.indexOf('/') < 0 && command.indexOf('\\') < 0) {
// no separators: command looks like a runtime name like 'node' or 'mono'
// TODO: check that the runtime is available on PATH
}
}
} else {
throw new Error(nls.localize({ key: 'debugAdapterCannotDetermineExecutable', comment: ['Adapter executable file not found'] },
"Cannot determine executable for debug adapter '{0}'.", this.debugType));
}
let env = objects.mixin({}, process.env);
if (options.env) {
env = objects.mixin(env, options.env);
}
delete env.VSCODE_PREVENT_FOREIGN_INSPECT;
if (command === 'node') {
if (Array.isArray(args) && args.length > 0) {
const isElectron = !!process.env['ELECTRON_RUN_AS_NODE'] || !!process.versions['electron'];
const forkOptions: cp.ForkOptions = {
env: env,
execArgv: isElectron ? ['-e', 'delete process.env.ELECTRON_RUN_AS_NODE;require(process.argv[1])'] : [],
silent: true
};
if (options.cwd) {
forkOptions.cwd = options.cwd;
}
const child = cp.fork(args[0], args.slice(1), forkOptions);
if (!child.pid) {
throw new Error(nls.localize('unableToLaunchDebugAdapter', "Unable to launch debug adapter from '{0}'.", args[0]));
}
this.serverProcess = child;
} else {
throw new Error(nls.localize('unableToLaunchDebugAdapterNoArgs', "Unable to launch debug adapter."));
}
} else {
const spawnOptions: cp.SpawnOptions = {
env: env
};
if (options.cwd) {
spawnOptions.cwd = options.cwd;
}
this.serverProcess = cp.spawn(command, args, spawnOptions);
}
this.serverProcess.on('error', err => {
this._onError.fire(err);
});
this.serverProcess.on('exit', (code, signal) => {
this._onExit.fire(code);
});
this.serverProcess.stdout.on('close', () => {
this._onError.fire(new Error('read error'));
});
this.serverProcess.stdout.on('error', error => {
this._onError.fire(error);
});
this.serverProcess.stdin.on('error', error => {
this._onError.fire(error);
});
const outputService = this.outputService;
if (outputService) {
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;');
// });
this.serverProcess.stderr.on('data', (data: string) => {
const channel = outputService.getChannel(ExtensionsChannelId);
if (channel) {
channel.append(sanitize(data));
}
});
}
// finally connect to the DA
this.connect(this.serverProcess.stdout, this.serverProcess.stdin);
} catch (err) {
this._onError.fire(err);
}
}
stopSession(): Promise<void> {
// Cancel all sent promises on disconnect so debug trees are not left in a broken state #3666.
this.cancelPending();
if (!this.serverProcess) {
return Promise.resolve(undefined);
}
// when killing a process in windows its child
// processes are *not* killed but become root
// processes. Therefore we use TASKKILL.EXE
if (platform.isWindows) {
return new Promise<void>((c, e) => {
const killer = cp.exec(`taskkill /F /T /PID ${this.serverProcess.pid}`, function (err, stdout, stderr) {
if (err) {
return e(err);
}
});
killer.on('exit', c);
killer.on('error', e);
});
} else {
this.serverProcess.kill('SIGTERM');
return Promise.resolve(undefined);
}
}
private static extract(platformContribution: IPlatformSpecificAdapterContribution, extensionFolderPath: string): IDebuggerContribution | undefined {
if (!platformContribution) {
return undefined;
}
const result: IDebuggerContribution = Object.create(null);
if (platformContribution.runtime) {
if (platformContribution.runtime.indexOf('./') === 0) { // TODO
result.runtime = path.join(extensionFolderPath, platformContribution.runtime);
} else {
result.runtime = platformContribution.runtime;
}
}
if (platformContribution.runtimeArgs) {
result.runtimeArgs = platformContribution.runtimeArgs;
}
if (platformContribution.program) {
if (!path.isAbsolute(platformContribution.program)) {
result.program = path.join(extensionFolderPath, platformContribution.program);
} else {
result.program = platformContribution.program;
}
}
if (platformContribution.args) {
result.args = platformContribution.args;
}
const contribution = platformContribution as IDebuggerContribution;
if (contribution.win) {
result.win = ExecutableDebugAdapter.extract(contribution.win, extensionFolderPath);
}
if (contribution.winx86) {
result.winx86 = ExecutableDebugAdapter.extract(contribution.winx86, extensionFolderPath);
}
if (contribution.windows) {
result.windows = ExecutableDebugAdapter.extract(contribution.windows, extensionFolderPath);
}
if (contribution.osx) {
result.osx = ExecutableDebugAdapter.extract(contribution.osx, extensionFolderPath);
}
if (contribution.linux) {
result.linux = ExecutableDebugAdapter.extract(contribution.linux, extensionFolderPath);
}
return result;
}
static platformAdapterExecutable(extensionDescriptions: IExtensionDescription[], debugType: string): IDebugAdapterExecutable | undefined {
let result: IDebuggerContribution = Object.create(null);
debugType = debugType.toLowerCase();
// merge all contributions into one
for (const ed of extensionDescriptions) {
if (ed.contributes) {
const debuggers = <IDebuggerContribution[]>ed.contributes['debuggers'];
if (debuggers && debuggers.length > 0) {
debuggers.filter(dbg => typeof dbg.type === 'string' && strings.equalsIgnoreCase(dbg.type, debugType)).forEach(dbg => {
// extract relevant attributes and make them absolute where needed
const extractedDbg = ExecutableDebugAdapter.extract(dbg, ed.extensionLocation.fsPath);
// merge
result = objects.mixin(result, extractedDbg, ed.isBuiltin);
});
}
}
}
// select the right platform
let platformInfo: IPlatformSpecificAdapterContribution | undefined;
if (platform.isWindows && !process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432')) {
platformInfo = result.winx86 || result.win || result.windows;
} else if (platform.isWindows) {
platformInfo = result.win || result.windows;
} else if (platform.isMacintosh) {
platformInfo = result.osx;
} else if (platform.isLinux) {
platformInfo = result.linux;
}
platformInfo = platformInfo || result;
// these are the relevant attributes
let program = platformInfo.program || result.program;
const args = platformInfo.args || result.args;
let runtime = platformInfo.runtime || result.runtime;
const runtimeArgs = platformInfo.runtimeArgs || result.runtimeArgs;
if (runtime) {
return {
type: 'executable',
command: runtime,
args: (runtimeArgs || []).concat(typeof program === 'string' ? [program] : []).concat(args || [])
};
} else if (program) {
return {
type: 'executable',
command: program,
args: args || []
};
}
// nothing found
return undefined;
}
}