Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
b9083ea
add a process picker for attaching by PID
matthewbastien Feb 26, 2025
b423842
convert pid to a number so that lldb-dap can properly consume it
matthewbastien Feb 26, 2025
ee7b00e
update extension README
matthewbastien Feb 26, 2025
82ef750
allow matching on the full command line arguments in the process picker
matthewbastien Feb 26, 2025
f4407b2
use execFile() instead of spawn() to simplify logic
matthewbastien Feb 28, 2025
daf2618
use camel case for ${command:pickProcess}
matthewbastien Mar 6, 2025
b2c0382
allow filtering processes by program
matthewbastien Mar 6, 2025
18cba4b
fix Linux process tree to include the full executable path
matthewbastien Mar 6, 2025
85a19e4
minor fixes to Darwin process tree
matthewbastien Mar 6, 2025
f84f5cc
remove program property from attach to process ID example
matthewbastien Mar 6, 2025
0a615f2
add `lldb-dap.attachToProcess` command
matthewbastien Mar 6, 2025
6f40eb3
use Get-CimInstance on Windows because WMIC is deprecated
matthewbastien Mar 6, 2025
d4c81e1
update README with more info about the 'program' property
matthewbastien Mar 6, 2025
6deb671
add code comment to LinuxProcessTree's parser
matthewbastien Mar 6, 2025
582cd9b
use the pickProcess command in attach requests by default
matthewbastien Mar 7, 2025
548ac79
filter out zombie, trace, and debug state processes on macOS and Linux
matthewbastien Mar 7, 2025
f967f6d
allow searching by pid in the process picker
matthewbastien Mar 7, 2025
2492e1e
match program by basename like the docs say
matthewbastien Mar 7, 2025
e9b4e6a
use the process picker even if `program` is set
matthewbastien Mar 7, 2025
a18e5cc
update documentation for attaching to a process
matthewbastien Mar 7, 2025
55e0c95
update attach parameter table in the README
matthewbastien Mar 7, 2025
6d01d9a
show an error message if no program is provided for waitFor
matthewbastien Mar 7, 2025
e4155ec
update description of waitFor in the package.json to indicate that th…
matthewbastien Mar 7, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion lldb/tools/lldb-dap/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ This will attach to a process `a.out` whose process ID is 123:
}
```

You can also use the variable substituion `${command:PickProcess}` to select a
process at the start of the debug session instead of setting the pid manually:

```javascript
{
"type": "lldb-dap",
"request": "attach",
"name": "Attach to PID",
"program": "/tmp/a.out",
"pid": "${command:PickProcess}"
}
```

#### Attach by Name

This will attach to an existing process whose base
Expand Down Expand Up @@ -224,7 +237,7 @@ the following `lldb-dap` specific key/value pairs:
| Parameter | Type | Req | |
|-----------------------------------|-------------|:---:|---------|
| **program** | string | | Path to the executable to attach to. This value is optional but can help to resolve breakpoints prior the attaching to the program.
| **pid** | number | | The process id of the process you wish to attach to. If **pid** is omitted, the debugger will attempt to attach to the program by finding a process whose file name matches the file name from **porgram**. Setting this value to `${command:pickMyProcess}` will allow interactive process selection in the IDE.
| **pid** | number | | The process id of the process you wish to attach to. If **pid** is omitted, the debugger will attempt to attach to the program by finding a process whose file name matches the file name from **program**. Setting this value to `${command:PickProcess}` will allow interactive process selection in the IDE.
| **waitFor** | boolean | | Wait for the process to launch.
| **attachCommands** | [string] | | LLDB commands that will be executed after **preRunCommands** which take place of the code that normally does the attach. The commands can create a new target and attach or launch it however desired. This allows custom launch and attach configurations. Core files can use `target create --core /path/to/core` to attach to core files.

Expand Down
30 changes: 29 additions & 1 deletion lldb/tools/lldb-dap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@
"windows": {
"program": "./bin/lldb-dap.exe"
},
"variables": {
"PickProcess": "lldb-dap.pickProcess"
},
"configurationAttributes": {
"launch": {
"required": [
Expand Down Expand Up @@ -517,6 +520,16 @@
"cwd": "^\"\\${workspaceRoot}\""
}
},
{
"label": "LLDB: Attach to Process",
"description": "",
"body": {
"type": "lldb-dap",
"request": "attach",
"name": "${1:Attach}",
"pid": "^\"\\${command:PickProcess}\""
}
},
{
"label": "LLDB: Attach",
"description": "",
Expand All @@ -541,6 +554,21 @@
}
]
}
]
],
"commands": [
{
"command": "lldb-dap.pickProcess",
"title": "Pick Process",
"category": "LLDB DAP"
}
],
"menus": {
"commandPalette": [
{
"command": "lldb-dap.pickProcess",
"when": "false"
}
]
}
}
}
42 changes: 42 additions & 0 deletions lldb/tools/lldb-dap/src-ts/commands/pick-process.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import * as path from "path";
import * as vscode from "vscode";
import { createProcessTree } from "../process-tree";

interface ProcessQuickPick extends vscode.QuickPickItem {
processId: number;
}

/**
* Prompts the user to select a running process.
*
* The return value must be a string so that it is compatible with VS Code's
* string substitution infrastructure. The value will eventually be converted
* to a number by the debug configuration provider.
*
* @returns The pid of the process as a string or undefined if cancelled.
*/
export async function pickProcess(): Promise<string | undefined> {
const processTree = createProcessTree();
const selectedProcess = await vscode.window.showQuickPick<ProcessQuickPick>(
processTree.listAllProcesses().then((processes): ProcessQuickPick[] => {
return processes
.sort((a, b) => b.start - a.start) // Sort by start date in descending order
.map((proc) => {
return {
processId: proc.id,
label: path.basename(proc.command),
description: proc.id.toString(),
detail: proc.arguments,
} satisfies ProcessQuickPick;
});
}),
{
placeHolder: "Select a process to attach the debugger to",
matchOnDetail: true,
},
);
if (!selectedProcess) {
return;
}
return selectedProcess.processId.toString();
}
54 changes: 54 additions & 0 deletions lldb/tools/lldb-dap/src-ts/debug-configuration-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import * as vscode from "vscode";

/**
* Converts the given value to an integer if it isn't already.
*
* If the value cannot be converted then this function will return undefined.
*
* @param value the value to to be converted
* @returns the integer value or undefined if unable to convert
*/
function convertToInteger(value: any): number | undefined {
let result: number | undefined;
switch (typeof value) {
case "number":
result = value;
break;
case "string":
result = Number(value);
break;
default:
return undefined;
}
if (!Number.isInteger(result)) {
return undefined;
}
return result;
}

/**
* A {@link vscode.DebugConfigurationProvider} used to resolve LLDB DAP debug configurations.
*
* Performs checks on the debug configuration before launching a debug session.
*/
export class LLDBDapConfigurationProvider
implements vscode.DebugConfigurationProvider
{
resolveDebugConfigurationWithSubstitutedVariables(
_folder: vscode.WorkspaceFolder | undefined,
debugConfiguration: vscode.DebugConfiguration,
): vscode.ProviderResult<vscode.DebugConfiguration> {
// Convert the "pid" option to a number if it is a string
if ("pid" in debugConfiguration) {
const pid = convertToInteger(debugConfiguration.pid);
if (pid === undefined) {
vscode.window.showErrorMessage(
"Invalid debug configuration: property 'pid' must either be an integer or a string containing an integer value.",
);
return null;
}
debugConfiguration.pid = pid;
}
return debugConfiguration;
}
}
14 changes: 12 additions & 2 deletions lldb/tools/lldb-dap/src-ts/extension.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as path from "path";
import * as util from "util";
import * as vscode from "vscode";

import { pickProcess } from "./commands/pick-process";
import {
LLDBDapDescriptorFactory,
isExecutable,
} from "./debug-adapter-factory";
import { DisposableContext } from "./disposable-context";
import { LLDBDapConfigurationProvider } from "./debug-configuration-provider";

/**
* This class represents the extension and manages its life cycle. Other extensions
Expand All @@ -15,6 +15,12 @@ import { DisposableContext } from "./disposable-context";
export class LLDBDapExtension extends DisposableContext {
constructor() {
super();
this.pushSubscription(
vscode.debug.registerDebugConfigurationProvider(
"lldb-dap",
new LLDBDapConfigurationProvider(),
),
);
this.pushSubscription(
vscode.debug.registerDebugAdapterDescriptorFactory(
"lldb-dap",
Expand All @@ -38,6 +44,10 @@ export class LLDBDapExtension extends DisposableContext {
}
}),
);

this.pushSubscription(
vscode.commands.registerCommand("lldb-dap.pickProcess", pickProcess),
);
}
}

Expand Down
102 changes: 102 additions & 0 deletions lldb/tools/lldb-dap/src-ts/process-tree/base-process-tree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { ChildProcessWithoutNullStreams } from "child_process";
import { Process, ProcessTree } from ".";
import { Transform } from "stream";

/** Parses process information from a given line of process output. */
export type ProcessTreeParser = (line: string) => Process | undefined;

/**
* Implements common behavior between the different {@link ProcessTree} implementations.
*/
export abstract class BaseProcessTree implements ProcessTree {
/**
* Spawn the process responsible for collecting all processes on the system.
*/
protected abstract spawnProcess(): ChildProcessWithoutNullStreams;

/**
* Create a new parser that can read the process information from stdout of the process
* spawned by {@link spawnProcess spawnProcess()}.
*/
protected abstract createParser(): ProcessTreeParser;

listAllProcesses(): Promise<Process[]> {
return new Promise<Process[]>((resolve, reject) => {
const proc = this.spawnProcess();
const parser = this.createParser();

// Capture processes from stdout
const processes: Process[] = [];
proc.stdout.pipe(new LineBasedStream()).on("data", (line) => {
const process = parser(line.toString());
if (process && process.id !== proc.pid) {
processes.push(process);
}
});

// Resolve or reject the promise based on exit code/signal/error
proc.on("error", reject);
proc.on("exit", (code, signal) => {
if (code === 0) {
resolve(processes);
} else if (signal) {
reject(
new Error(
`Unable to list processes: process exited due to signal ${signal}`,
),
);
} else {
reject(
new Error(
`Unable to list processes: process exited with code ${code}`,
),
);
}
});
});
}
}

/**
* A stream that emits each line as a single chunk of data. The end of a line is denoted
* by the newline character '\n'.
*/
export class LineBasedStream extends Transform {
private readonly newline: number = "\n".charCodeAt(0);
private buffer: Buffer = Buffer.alloc(0);

override _transform(
chunk: Buffer,
_encoding: string,
callback: () => void,
): void {
let currentIndex = 0;
while (currentIndex < chunk.length) {
const newlineIndex = chunk.indexOf(this.newline, currentIndex);
if (newlineIndex === -1) {
this.buffer = Buffer.concat([
this.buffer,
chunk.subarray(currentIndex),
]);
break;
}

const newlineChunk = chunk.subarray(currentIndex, newlineIndex);
const line = Buffer.concat([this.buffer, newlineChunk]);
this.push(line);
this.buffer = Buffer.alloc(0);

currentIndex = newlineIndex + 1;
}

callback();
}

override _flush(callback: () => void): void {
if (this.buffer.length) {
this.push(this.buffer);
}

callback();
}
}
36 changes: 36 additions & 0 deletions lldb/tools/lldb-dap/src-ts/process-tree/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { DarwinProcessTree } from "./platforms/darwin-process-tree";
import { LinuxProcessTree } from "./platforms/linux-process-tree";
import { WindowsProcessTree } from "./platforms/windows-process-tree";

/**
* Represents a single process running on the system.
*/
export interface Process {
/** Process ID */
id: number;

/** Command that was used to start the process */
command: string;

/** The full command including arguments that was used to start the process */
arguments: string;

/** The date when the process was started */
start: number;
}

export interface ProcessTree {
listAllProcesses(): Promise<Process[]>;
}

/** Returns a {@link ProcessTree} based on the current platform. */
export function createProcessTree(): ProcessTree {
switch (process.platform) {
case "darwin":
return new DarwinProcessTree();
case "win32":
return new WindowsProcessTree();
default:
return new LinuxProcessTree();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { LinuxProcessTree } from "./linux-process-tree";

function fill(prefix: string, suffix: string, length: number): string {
return prefix + suffix.repeat(length - prefix.length);
}

export class DarwinProcessTree extends LinuxProcessTree {
protected override spawnProcess(): ChildProcessWithoutNullStreams {
return spawn("ps", [
"-xo",
// The length of comm must be large enough or data will be truncated.
`pid=PID,lstart=START,comm=${fill("COMMAND", "-", 256)},command=ARGUMENTS`,
]);
}
}
Loading