This repository was archived by the owner on Oct 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathprocessPicker.ts
More file actions
227 lines (183 loc) · 6.66 KB
/
processPicker.ts
File metadata and controls
227 lines (183 loc) · 6.66 KB
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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as nls from 'vscode-nls';
import * as vscode from 'vscode';
import { basename } from 'path';
import { getProcesses } from './processTree';
import { execSync } from 'child_process';
import { detectProtocolForPid, INSPECTOR_PORT_DEFAULT, LEGACY_PORT_DEFAULT } from './protocolDetection';
import { analyseArguments } from './protocolDetection';
const localize = nls.loadMessageBundle();
//---- extension.pickNodeProcess
interface ProcessItem extends vscode.QuickPickItem {
pidOrPort: string; // picker result
sortKey: number;
}
/**
* end user action for picking a process and attaching debugger to it
*/
export async function attachProcess() {
const result = await pickProcess(true); // ask for pids and ports!
if (result) {
const config = {
type: 'legacy-node',
request: 'attach',
name: 'process',
processId: result
};
await resolveProcessId(config);
return vscode.debug.startDebugging(undefined, config);
}
return undefined;
}
/**
* Process the special protocol/processId/port patterns that the process picker puts in the "processId" attribute.
*/
export async function resolveProcessId(config: vscode.DebugConfiguration) : Promise<void> {
let processId = config.processId.trim();
const matches = /^(inspector|legacy)?([0-9]+)(inspector|legacy)?([0-9]+)?$/.exec(processId);
if (matches && matches.length === 5) {
if (matches[2] && matches[3] && matches[4]) {
// process id and protocol and port
const pid = Number(matches[2]);
putPidInDebugMode(pid);
// debug port
config.port = Number(matches[4]);
config.protocol = matches[3];
delete config.processId;
} else {
// protocol and port
if (matches[1]) {
// debug port
config.port = Number(matches[2]);
config.protocol = matches[1];
delete config.processId;
} else {
// process id
const pid = Number(matches[2]);
putPidInDebugMode(pid);
const debugType = await determineDebugTypeForPidInDebugMode(config, pid);
if (debugType) {
// processID is handled, so turn this config into a normal port attach configuration
delete config.processId;
config.port = debugType === 'legacy-node2' ? INSPECTOR_PORT_DEFAULT : LEGACY_PORT_DEFAULT;
config.protocol = debugType === 'legacy-node2' ? 'inspector' : 'legacy';
} else {
throw new Error(localize('pid.error', "Attach to process: cannot put process '{0}' in debug mode.", processId));
}
}
}
} else {
throw new Error(localize('process.id.error', "Attach to process: '{0}' doesn't look like a process id.", processId));
}
}
/**
* Process picker command (for launch config variable)
* Returns as a string with these formats:
* - "12345": process id
* - "inspector12345": port number and inspector protocol
* - "legacy12345": port number and legacy protocol
* - null: abort launch silently
*/
export function pickProcess(ports?): Promise<string | null> {
return listProcesses(ports).then(items => {
let options: vscode.QuickPickOptions = {
placeHolder: localize('pickNodeProcess', "Pick the node.js process to attach to"),
matchOnDescription: true,
matchOnDetail: true
};
return vscode.window.showQuickPick(items, options).then(item => item ? item.pidOrPort : null);
}).catch(err => {
return vscode.window.showErrorMessage(localize('process.picker.error', "Process picker failed ({0})", err.message), { modal: true }).then(_ => null);
});
}
//---- private
function listProcesses(ports: boolean): Promise<ProcessItem[]> {
const items: ProcessItem[] = [];
const NODE = new RegExp('^(?:node|iojs)$', 'i');
let seq = 0; // default sort key
return getProcesses((pid: number, ppid: number, command: string, args: string, date: number) => {
if (process.platform === 'win32' && command.indexOf('\\??\\') === 0) {
// remove leading device specifier
command = command.replace('\\??\\', '');
}
const executable_name = basename(command, '.exe');
let port = -1;
let protocol: string | undefined = '';
let usePort = true;
if (ports) {
const x = analyseArguments(args);
usePort = x.usePort;
protocol = x.protocol;
port = x.port;
}
let description = '';
let pidOrPort = '';
if (usePort) {
if (protocol === 'inspector') {
description = localize('process.id.port', "process id: {0}, debug port: {1}", pid, port);
} else {
description = localize('process.id.port.legacy', "process id: {0}, debug port: {1} (legacy protocol)", pid, port);
}
pidOrPort = `${protocol}${port}`;
} else {
if (protocol && port > 0) {
description = localize('process.id.port.signal', "process id: {0}, debug port: {1} ({2})", pid, port, 'SIGUSR1');
pidOrPort = `${pid}${protocol}${port}`;
} else {
// no port given
if (NODE.test(executable_name)) {
description = localize('process.id.signal', "process id: {0} ({1})", pid, 'SIGUSR1');
pidOrPort = pid.toString();
}
}
}
if (description && pidOrPort) {
items.push({
// render data
label: executable_name,
description: args,
detail: description,
// picker result
pidOrPort: pidOrPort,
// sort key
sortKey: date ? date : seq++
});
}
}).then(() => items.sort((a, b) => b.sortKey - a.sortKey)); // sort items by process id, newest first
}
function putPidInDebugMode(pid: number): void {
try {
if (process.platform === 'win32') {
// regular node has an undocumented API function for forcing another node process into debug mode.
// (<any>process)._debugProcess(pid);
// But since we are running on Electron's node, process._debugProcess doesn't work (for unknown reasons).
// So we use a regular node instead:
const command = `node -e process._debugProcess(${pid})`;
execSync(command);
} else {
process.kill(pid, 'SIGUSR1');
}
} catch (e) {
throw new Error(localize('cannot.enable.debug.mode.error', "Attach to process: cannot enable debug mode for process '{0}' ({1}).", pid, e));
}
}
function determineDebugTypeForPidInDebugMode(config: any, pid: number): Promise<string | null> {
let debugProtocolP: Promise<string | null>;
if (config.port === INSPECTOR_PORT_DEFAULT) {
debugProtocolP = Promise.resolve('inspector');
} else if (config.port === LEGACY_PORT_DEFAULT) {
debugProtocolP = Promise.resolve('legacy');
} else if (config.protocol) {
debugProtocolP = Promise.resolve(config.protocol);
} else {
debugProtocolP = detectProtocolForPid(pid);
}
return debugProtocolP.then(debugProtocol => {
return debugProtocol === 'inspector' ? 'legacy-node2' :
debugProtocol === 'legacy' ? 'legacy-node' :
null;
});
}