-
Notifications
You must be signed in to change notification settings - Fork 250
/
main.ts
496 lines (440 loc) · 19.8 KB
/
main.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import {
workspace, window, commands, debug, extensions,
ExtensionContext, WorkspaceConfiguration, WorkspaceFolder, CancellationToken, ConfigurationScope,
DebugConfigurationProvider, DebugConfiguration, DebugAdapterDescriptorFactory, DebugSession, DebugAdapterExecutable,
DebugAdapterDescriptor, Uri, ConfigurationTarget, DebugAdapterInlineImplementation
} from 'vscode';
import { inspect } from 'util';
import { ChildProcess } from 'child_process';
import * as path from 'path';
import * as os from 'os';
import * as crypto from 'crypto';
import stringArgv from 'string-argv';
import * as webview from './webview';
import * as util from './configUtils';
import * as adapter from './novsc/adapter';
import * as install from './install';
import { Cargo, expandCargo } from './cargo';
import { pickProcess } from './pickProcess';
import { AdapterSettings } from './novsc/adapterMessages';
import { ModuleTreeDataProvider as ModulesView } from './modulesView';
import { ExcludedCallersView } from './excludedCallersView';
import { mergeValues } from './novsc/expand';
import { pickSymbol } from './symbols';
import { ReverseAdapterConnector } from './novsc/reverseConnector';
import { UriLaunchServer, RpcLaunchServer } from './externalLaunch';
import { AdapterSettingManager as AdapterSettingsManager } from './adapterSettings';
export let output = window.createOutputChannel('LLDB');
export function getExtensionConfig(scope?: ConfigurationScope, subkey?: string): WorkspaceConfiguration {
let key = 'lldb';
if (subkey) key += '.' + subkey;
return workspace.getConfiguration(key, scope);
}
let extension: Extension;
// Main entry point
export function activate(context: ExtensionContext) {
extension = new Extension(context);
extension.onActivate();
}
export function deactivate() {
extension.onDeactivate();
}
class Extension implements DebugConfigurationProvider, DebugAdapterDescriptorFactory {
context: ExtensionContext;
settingsManager: AdapterSettingsManager;
webviewManager: webview.WebviewManager;
loadedModules: ModulesView;
excludedCallers: ExcludedCallersView;
rpcServer: RpcLaunchServer;
constructor(context: ExtensionContext) {
this.context = context;
this.webviewManager = new webview.WebviewManager(context);
let subscriptions = context.subscriptions;
subscriptions.push(debug.registerDebugConfigurationProvider('lldb', this));
subscriptions.push(debug.registerDebugAdapterDescriptorFactory('lldb', this));
subscriptions.push(commands.registerCommand('lldb.diagnose', () => this.runDiagnostics()));
subscriptions.push(commands.registerCommand('lldb.getCargoLaunchConfigs', () => this.getCargoLaunchConfigs()));
subscriptions.push(commands.registerCommand('lldb.pickMyProcess', (config) => pickProcess(context, false, config)));
subscriptions.push(commands.registerCommand('lldb.pickProcess', (config) => pickProcess(context, true, config)));
subscriptions.push(commands.registerCommand('lldb.attach', () => this.attach()));
subscriptions.push(commands.registerCommand('lldb.alternateBackend', () => this.alternateBackend()));
subscriptions.push(commands.registerCommand('lldb.commandPrompt', () => this.commandPrompt()));
subscriptions.push(commands.registerCommand('lldb.symbols', () => pickSymbol(debug.activeDebugSession)));
subscriptions.push(commands.registerCommand('lldb.viewMemory', () => this.viewMemory()));
subscriptions.push(workspace.onDidChangeConfiguration(event => {
if (event.affectsConfiguration('lldb.library')) {
this.adapterDylibsCache = null;
}
if (event.affectsConfiguration('lldb.rpcServer')) {
this.updateRpcServer();
}
}));
this.settingsManager = new AdapterSettingsManager(context);
this.loadedModules = new ModulesView(context);
subscriptions.push(window.registerTreeDataProvider('lldb.loadedModules', this.loadedModules));
this.excludedCallers = new ExcludedCallersView(context);
this.excludedCallers.loadState();
subscriptions.push(window.registerTreeDataProvider('lldb.excludedCallers', this.excludedCallers));
subscriptions.push(window.registerUriHandler(new UriLaunchServer()));
this.updateRpcServer();
}
async onActivate() {
let pkg = extensions.getExtension('vadimcn.vscode-lldb').packageJSON;
let currVersion = pkg.version;
let lastVersion = this.context.globalState.get('lastLaunchedVersion');
let lldbConfig = getExtensionConfig();
if (currVersion != lastVersion && !lldbConfig.get('suppressUpdateNotifications')) {
this.context.globalState.update('lastLaunchedVersion', currVersion);
if (lastVersion != undefined) {
let buttons = ['What\'s new?', 'Don\'t show this again'];
let choice = await window.showInformationMessage('CodeLLDB extension has been updated', ...buttons);
if (choice === buttons[0]) {
let changelog = path.join(this.context.extensionPath, 'CHANGELOG.md')
let uri = Uri.file(changelog);
await commands.executeCommand('markdown.showPreview', uri, null, { locked: true });
} else if (choice == buttons[1]) {
lldbConfig.update('suppressUpdateNotifications', true, ConfigurationTarget.Global);
}
}
}
install.ensurePlatformPackage(this.context, output, false);
}
onDeactivate() {
if (this.rpcServer) {
this.rpcServer.close();
}
}
updateRpcServer() {
if (this.rpcServer) {
output.appendLine('Stopping RPC server');
this.rpcServer.close();
this.rpcServer = null;
}
let config = getExtensionConfig();
let options = config.get('rpcServer') as any;
if (options) {
output.appendLine(`Starting RPC server with: ${inspect(options)}`);
this.rpcServer = new RpcLaunchServer({ token: options.token });
this.rpcServer.listen(options)
}
}
async provideDebugConfigurations(
workspaceFolder: WorkspaceFolder | undefined,
cancellation?: CancellationToken
): Promise<DebugConfiguration[]> {
try {
let cargo = new Cargo(workspaceFolder, cancellation);
let debugConfigs = await cargo.getLaunchConfigs();
if (debugConfigs.length > 0) {
let response = await window.showInformationMessage(
'Cargo.toml has been detected in this workspace.\r\n' +
'Would you like to generate launch configurations for its targets?', { modal: true }, 'Yes', 'No');
if (response == 'Yes') {
return debugConfigs;
}
}
} catch (err) {
output.appendLine(err.toString());
}
return [{
type: 'lldb',
request: 'launch',
name: 'Debug',
program: '${workspaceFolder}/<executable file>',
args: [],
cwd: '${workspaceFolder}'
}];
}
// Invoked by VSCode to initiate a new debugging session.
async resolveDebugConfiguration(
folder: WorkspaceFolder | undefined,
launchConfig: DebugConfiguration,
cancellation?: CancellationToken
): Promise<DebugConfiguration> {
output.clear();
output.appendLine(`Initial debug configuration: ${inspect(launchConfig)}`);
if (launchConfig.type === undefined) {
await window.showErrorMessage('Cannot start debugging because no launch configuration has been provided.', { modal: true });
return null;
}
if (!await this.checkPrerequisites(folder))
return undefined;
let launchDefaults = getExtensionConfig(folder, 'launch');
this.mergeWorkspaceSettings(launchConfig, launchDefaults);
let dbgconfigConfig = getExtensionConfig(folder, 'dbgconfig');
launchConfig = util.expandDbgConfig(launchConfig, dbgconfigConfig);
// Transform "request":"custom" to "request":"launch" + "custom":true
if (launchConfig.request == 'custom') {
launchConfig.request = 'launch';
launchConfig.custom = true;
}
if (typeof launchConfig.args == 'string') {
launchConfig.args = stringArgv(launchConfig.args);
}
launchConfig.relativePathBase = launchConfig.relativePathBase || folder?.uri.fsPath || workspace.rootPath;
// Deal with Cargo
if (launchConfig.cargo != undefined) {
let cargo = new Cargo(folder, cancellation);
let program = await cargo.getProgramFromCargoConfig(launchConfig.cargo);
delete launchConfig.cargo;
// Expand ${cargo:program}.
launchConfig = expandCargo(launchConfig, { program: program });
if (launchConfig.program == undefined) {
launchConfig.program = program;
}
// Add 'rust' to sourceLanguages, since this project obviously (ha!) involves Rust.
if (!launchConfig.sourceLanguages)
launchConfig.sourceLanguages = [];
launchConfig.sourceLanguages.push('rust');
}
launchConfig._adapterSettings = this.settingsManager.getAdapterSettings(folder);
output.appendLine(`Resolved debug configuration: ${inspect(launchConfig)}`);
return launchConfig;
}
async createDebugAdapterDescriptor(session: DebugSession, executable: DebugAdapterExecutable | undefined): Promise<DebugAdapterDescriptor> {
let settings = this.settingsManager.getAdapterSettings(session.workspaceFolder);
let adapterSettings: AdapterSettings = {
evaluateForHovers: settings.evaluateForHovers,
commandCompletions: settings.commandCompletions,
};
if (session.configuration.sourceLanguages) {
adapterSettings.sourceLanguages = session.configuration.sourceLanguages;
delete session.configuration.sourceLanguages;
}
let authToken = crypto.randomBytes(16).toString('base64');
let connector = new ReverseAdapterConnector(authToken);
let port = await connector.listen();
try {
await this.startDebugAdapter(session.workspaceFolder, adapterSettings, port, authToken);
await connector.accept();
return new DebugAdapterInlineImplementation(connector);
} catch (err) {
this.analyzeStartupError(err);
throw err;
}
}
async analyzeStartupError(err: Error) {
output.appendLine(err.toString());
output.show(true)
let e = <any>err;
let diagnostics = 'Run diagnostics';
let actionAsync;
if (e.code == 'ENOENT') {
actionAsync = window.showErrorMessage(
`Could not start debugging because executable "${e.path}" was not found.`,
diagnostics);
} else if (e.code == 'Timeout' || e.code == 'Handshake') {
actionAsync = window.showErrorMessage(err.message, diagnostics);
} else {
actionAsync = window.showErrorMessage('Could not start debugging.', diagnostics);
}
if ((await actionAsync) == diagnostics) {
await this.runDiagnostics();
}
}
// Merge workspace launch defaults into debug configuration.
mergeWorkspaceSettings(debugConfig: DebugConfiguration, launchConfig: WorkspaceConfiguration) {
let mergeConfig = (key: string, reverseSeq: boolean = false) => {
let launchValue = debugConfig[key];
let defaultValue = launchConfig.get(key);
let value = mergeValues(launchValue, defaultValue, reverseSeq);
if (!util.isEmpty(value))
debugConfig[key] = value;
}
mergeConfig('initCommands');
mergeConfig('preRunCommands');
mergeConfig('postRunCommands');
mergeConfig('preTerminateCommands', true);
mergeConfig('exitCommands', true);
mergeConfig('env');
mergeConfig('envFile');
mergeConfig('cwd');
mergeConfig('terminal');
mergeConfig('stdio');
mergeConfig('expressions');
mergeConfig('sourceMap');
mergeConfig('relativePathBase');
mergeConfig('sourceLanguages');
mergeConfig('debugServer');
mergeConfig('breakpointMode');
}
async getCargoLaunchConfigs() {
try {
let folder = (workspace.workspaceFolders.length == 1) ?
workspace.workspaceFolders[0] :
await window.showWorkspaceFolderPick();
let cargo = new Cargo(folder);
let configurations = await cargo.getLaunchConfigs();
let debugConfigs = {
version: '0.2.0',
configurations: configurations,
}
let doc = await workspace.openTextDocument({
language: 'jsonc',
content: JSON.stringify(debugConfigs, null, 4),
});
await window.showTextDocument(doc, 1, false);
} catch (err) {
output.show();
window.showErrorMessage(err.toString());
}
}
async startDebugAdapter(
folder: WorkspaceFolder | undefined,
adapterSettings: AdapterSettings,
connectPort: number,
authToken: string
): Promise<ChildProcess> {
let config = getExtensionConfig(folder);
let adapterEnv = config.get('adapterEnv', {});
let verboseLogging = config.get<boolean>('verboseLogging');
let [liblldb] = await this.getAdapterDylibs(config);
if (verboseLogging) {
output.appendLine(`liblldb: ${liblldb}`);
output.appendLine(`environment: ${inspect(adapterEnv)}`);
output.appendLine(`settings: ${inspect(adapterSettings)}`);
}
let adapterProcess = await adapter.start(liblldb, {
extensionRoot: this.context.extensionPath,
extraEnv: adapterEnv,
workDir: workspace.rootPath,
port: connectPort,
connect: true,
authToken: authToken,
adapterSettings: adapterSettings,
verboseLogging: verboseLogging
});
util.logProcessOutput(adapterProcess, output);
adapterProcess.on('exit', async (code, signal) => {
output.appendLine(`Debug adapter exit code=${code} (0x${code.toString(16)}), signal=${signal}.`);
if (code != 0) {
let result = await window.showErrorMessage('Oops! The debug adapter has terminated abnormally.', 'Open log');
if (result != undefined) {
output.show();
}
}
});
return adapterProcess;
}
// Resolve paths of the native adapter libraries and cache them.
async getAdapterDylibs(config: WorkspaceConfiguration): Promise<[string]> {
if (!this.adapterDylibsCache) {
let liblldb = config.get<string>('library');
if (liblldb) {
liblldb = await adapter.findLibLLDB(liblldb)
} else {
liblldb = await adapter.findLibLLDB(path.join(this.context.extensionPath, 'lldb'));
}
this.adapterDylibsCache = [liblldb];
}
return this.adapterDylibsCache;
}
adapterDylibsCache: [string] = null;
async checkPrerequisites(folder?: WorkspaceFolder): Promise<boolean> {
if (!await install.ensurePlatformPackage(this.context, output, true))
return false;
return true;
}
async runDiagnostics(folder?: WorkspaceFolder) {
let succeeded;
try {
let authToken = crypto.randomBytes(16).toString('base64');
let connector = new ReverseAdapterConnector(authToken);
let port = await connector.listen();
let adapter = await this.startDebugAdapter(folder, {}, port, authToken);
let adapterExitAsync = new Promise((resolve, reject) => {
adapter.on('exit', resolve);
adapter.on('error', reject);
});
await connector.accept();
connector.handleMessage({ seq: 1, type: 'request', command: 'disconnect' });
connector.dispose();
await adapterExitAsync;
succeeded = true;
} catch (err) {
succeeded = false;
}
if (succeeded) {
window.showInformationMessage('LLDB self-test completed successfuly.');
} else {
window.showErrorMessage('LLDB self-test has failed. Please check log output.');
output.show();
}
}
async attach() {
let debugConfig: DebugConfiguration = {
type: 'lldb',
request: 'attach',
name: 'Attach',
pid: '${command:pickMyProcess}',
};
await debug.startDebugging(undefined, debugConfig);
}
async alternateBackend() {
let box = window.createInputBox();
box.prompt = 'Enter file name of the LLDB instance you\'d like to use. ';
box.onDidAccept(async () => {
try {
let dirs = await util.getLLDBDirectories(box.value);
if (dirs) {
let libraryPath = await adapter.findLibLLDB(dirs.shlibDir);
if (libraryPath) {
let choice = await window.showInformationMessage(
`Located liblldb at: ${libraryPath}\r\nUse it to configure the current workspace?`,
{ modal: true }, 'Yes'
);
if (choice == 'Yes') {
box.hide();
let lldbConfig = getExtensionConfig();
lldbConfig.update('library', libraryPath, ConfigurationTarget.Workspace);
} else {
box.show();
}
}
}
} catch (err) {
let message = (err.code == 'ENOENT') ? `could not find "${err.path}".` : err.message;
await window.showErrorMessage(`Failed to query LLDB for library location: ${message}`, { modal: true });
box.show();
}
});
box.show();
}
commandPrompt() {
let lldb = os.platform() != 'win32' ? 'lldb' : 'lldb.exe';
let lldbPath = path.join(this.context.extensionPath, 'lldb', 'bin', lldb);
let consolePath = path.join(this.context.extensionPath, 'adapter', 'scripts', 'console.py');
let folder = workspace.workspaceFolders?.[0];
let config = getExtensionConfig(folder);
let env = adapter.getAdapterEnv(config.get('adapterEnv', {}));
let terminal = window.createTerminal({
name: 'LLDB Command Prompt',
shellPath: lldbPath,
shellArgs: ['--no-lldbinit', '--one-line-before-file', 'command script import ' + consolePath],
cwd: folder.uri.fsPath,
env: env,
strictEnv: true
});
terminal.show()
}
async viewMemory(address?: bigint) {
if (address == undefined) {
let addressStr = await window.showInputBox({
title: 'Enter memory address',
prompt: 'Hex, octal or decimal '
});
try {
address = BigInt(addressStr);
} catch (err) {
window.showErrorMessage('Could not parse address', { modal: true });
return;
}
}
commands.executeCommand('workbench.debug.viewlet.action.viewMemory', {
sessionId: debug.activeDebugSession.id,
variable: {
memoryReference: `0x${address.toString(16)}`
}
});
}
}