-
Notifications
You must be signed in to change notification settings - Fork 296
/
Copy pathprocessPicker.ts
220 lines (191 loc) · 6.88 KB
/
processPicker.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { execSync } from 'child_process';
import { basename } from 'path';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import {
INodeAttachConfiguration,
nodeAttachConfigDefaults,
ResolvingNodeAttachConfiguration,
} from '../configuration';
import { processTree, analyseArguments } from './processTree/processTree';
import { readConfig, Configuration } from '../common/contributionUtils';
import { nearestDirectoryContaining } from '../common/urlUtils';
import { isSubdirectoryOf } from '../common/pathUtils';
const INSPECTOR_PORT_DEFAULT = 9229;
const localize = nls.loadMessageBundle();
interface IProcessItem extends vscode.QuickPickItem {
pidAndPort: string; // picker result
sortKey: number;
}
/**
* end user action for picking a process and attaching debugger to it
*/
export async function attachProcess() {
// We pick here, rather than just putting the command as the process ID, so
// that the cwd is set correctly in multi-root workspaces.
const processId = await pickProcess();
if (!processId) {
return;
}
const userDefaults = readConfig(vscode.workspace, Configuration.PickAndAttachDebugOptions);
const config: INodeAttachConfiguration = {
...nodeAttachConfigDefaults,
...userDefaults,
name: 'process',
processId,
};
await resolveProcessId(config, true);
await vscode.debug.startDebugging(
config.cwd ? vscode.workspace.getWorkspaceFolder(vscode.Uri.file(config.cwd)) : undefined,
config,
);
}
/**
* Resolves the requested process ID, and updates the config object
* appropriately. Returns true if the configuration was updated, false
* if it was cancelled.
*/
export async function resolveProcessId(config: ResolvingNodeAttachConfiguration, setCwd = false) {
// we resolve Process Picker early (before VS Code) so that we can probe the process for its protocol
const processId = config.processId?.trim();
const result = processId && decodePidAndPort(processId);
if (!result || isNaN(result.pid)) {
throw new Error(
localize(
'process.id.error',
"Attach to process: '{0}' doesn't look like a process id.",
processId,
),
);
}
if (!result.port) {
putPidInDebugMode(result.pid);
}
config.port = result.port || INSPECTOR_PORT_DEFAULT;
delete config.processId;
if (setCwd) {
const inferredWd = await inferWorkingDirectory(result.pid);
if (inferredWd) {
config.cwd = inferredWd;
}
}
}
async function inferWorkingDirectory(processId?: number) {
const inferredWd = processId && (await processTree.getWorkingDirectory(processId));
// If we couldn't infer the working directory, just use the first workspace folder
if (!inferredWd) {
return vscode.workspace.workspaceFolders?.[0].uri.fsPath;
}
const packageRoot = await nearestDirectoryContaining(inferredWd, 'package.json');
if (!packageRoot) {
return inferredWd;
}
// Find the working directory package root. If the original inferred working
// directory was inside a workspace folder, don't go past that.
const parentWorkspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(inferredWd));
return !parentWorkspaceFolder || isSubdirectoryOf(parentWorkspaceFolder.uri.fsPath, packageRoot)
? packageRoot
: parentWorkspaceFolder.uri.fsPath;
}
/**
* Process picker command (for launch config variable). Returns a string in
* the format `pid:port`, where port is optional.
*/
export async function pickProcess(): Promise<string | null> {
try {
const item = await listProcesses();
return item ? item.pidAndPort : null;
} catch (err) {
await vscode.window.showErrorMessage(
localize('process.picker.error', 'Process picker failed ({0})', err.message),
{ modal: true },
);
return null;
}
}
//---- private
const encodePidAndPort = (processId: number, port?: number) => `${processId}:${port ?? ''}`;
const decodePidAndPort = (encoded: string) => {
const [pid, port] = encoded.split(':');
return { pid: Number(pid), port: port ? Number(port) : undefined };
};
async function listProcesses(): Promise<IProcessItem> {
const nodeProcessPattern = /^(?:node|iojs)$/i;
let seq = 0; // default sort key
const quickPick = await vscode.window.createQuickPick<IProcessItem>();
quickPick.placeholder = localize('pickNodeProcess', 'Pick the node.js process to attach to');
quickPick.matchOnDescription = true;
quickPick.matchOnDetail = true;
quickPick.busy = true;
quickPick.show();
let hasPicked = false;
const itemPromise = new Promise<IProcessItem>(resolve => {
quickPick.onDidAccept(() => resolve(quickPick.selectedItems[0]));
quickPick.onDidHide(() => resolve(undefined));
});
processTree
.lookup<IProcessItem[]>((leaf, acc) => {
if (hasPicked) {
return acc;
}
if (process.platform === 'win32' && leaf.command.indexOf('\\??\\') === 0) {
// remove leading device specifier
leaf.command = leaf.command.replace('\\??\\', '');
}
const executableName = basename(leaf.command, '.exe');
const { port } = analyseArguments(leaf.args);
if (!port && !nodeProcessPattern.test(executableName)) {
return acc;
}
const newItem = {
label: executableName,
description: leaf.args,
pidAndPort: encodePidAndPort(leaf.pid, port),
sortKey: leaf.date ? leaf.date : seq++,
detail: port
? localize(
'process.id.port.signal',
'process id: {0}, debug port: {1} ({2})',
leaf.pid,
port,
'SIGUSR1',
)
: localize('process.id.signal', 'process id: {0} ({1})', leaf.pid, 'SIGUSR1'),
};
const index = acc.findIndex(item => item.sortKey < newItem.sortKey);
acc.splice(index === -1 ? acc.length : index, 0, newItem);
quickPick.items = acc;
return acc;
}, [])
.then(() => (quickPick.busy = false));
const item = await itemPromise;
hasPicked = true;
quickPick.dispose();
return item;
}
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,
),
);
}
}