Skip to content

Feat: naive waitFor preattach/attach support #13464

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
28 changes: 28 additions & 0 deletions Extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4663,6 +4663,33 @@
}
]
},
"waitFor": {
"description": "%c_cpp.debuggers.waitFor.description%",
"type": "object",
"default": {},
"properties": {
"enabled": {
"type": "boolean",
"description": "%c_cpp.debuggers.waitFor.enabled.description%",
"default": false
},
"pattern": {
"type": "string",
"description": "%c_cpp.debuggers.waitFor.pattern.description%",
"default": ""
},
"timeout": {
"type": "number",
"description": "%c_cpp.debuggers.waitFor.timeout.description%",
"default": 30000
},
"interval": {
"type": "number",
"description": "%c_cpp.debuggers.waitFor.interval.description%",
"default": 150
}
}
},
"filterStdout": {
"type": "boolean",
"description": "%c_cpp.debuggers.filterStdout.description%",
Expand Down Expand Up @@ -6566,6 +6593,7 @@
"@types/shell-quote": "^1.7.5",
"@types/sinon": "^17.0.3",
"@types/tmp": "^0.2.6",
"@types/vscode": "^1.99.1",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this needed? It seems like it might be the cause of the CI failures: C:/a/vscode-cpptools/vscode-cpptools/Extension/node_modules/@types/vscode/index.d.ts(4497,3): error TS2374: Duplicate index signature for type 'string'.

Our current VS Code dependency is 1.67.0, so including a type dependency on VS Code version 1.99.1 seems incorrect.

"@types/which": "^2.0.2",
"@types/yauzl": "^2.10.3",
"@typescript-eslint/eslint-plugin": "^6.1.0",
Expand Down
4 changes: 4 additions & 0 deletions Extension/package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -1007,6 +1007,10 @@
"c_cpp.debuggers.VSSymbolOptionsModuleFilter.excludedModules.description": "Array of modules that the debugger should NOT load symbols for. Wildcards (example: MyCompany.*.dll) are supported.\n\nThis property is ignored unless 'mode' is set to 'loadAllButExcluded'.",
"c_cpp.debuggers.VSSymbolOptionsModuleFilter.includedModules.description": "Array of modules that the debugger should load symbols for. Wildcards (example: MyCompany.*.dll) are supported.\n\nThis property is ignored unless 'mode' is set to 'loadOnlyIncluded'.",
"c_cpp.debuggers.VSSymbolOptionsModuleFilter.includeSymbolsNextToModules.description": "If true, for any module NOT in the 'includedModules' array, the debugger will still check next to the module itself and the launching executable, but it will not check paths on the symbol search list. This option defaults to 'true'.\n\nThis property is ignored unless 'mode' is set to 'loadOnlyIncluded'.",
"c_cpp.debuggers.waitFor.enabled.description": "If true, the debugger will wait till timeout to match a process cmd pattern and attach to it. If matched, sends a SIGSTOP to the process before attaching.",
"c_cpp.debuggers.waitFor.pattern.description": "The process cmd pattern to match against. The pattern is a regular expression that will be matched against the process name.",
"c_cpp.debuggers.waitFor.timeout.description": "The time, in milliseconds, to wait for a process to match. The default is 10000ms.",
"c_cpp.debuggers.waitFor.interval.description": "The interval, in milliseconds, to wait between checks for the process to match. The default is 200ms.",
"c_cpp.semanticTokenTypes.referenceType.description": "Style for C++/CLI reference types.",
"c_cpp.semanticTokenTypes.cliProperty.description": "Style for C++/CLI properties.",
"c_cpp.semanticTokenTypes.genericType.description": "Style for C++/CLI generic types.",
Expand Down
134 changes: 134 additions & 0 deletions Extension/src/Debugger/attachWaitFor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@

import * as os from 'os';
import * as vscode from 'vscode';
import { localize } from 'vscode-nls';
import * as util from '../common';
import { sleep } from '../Utility/Async/sleep';
import { CimAttachItemsProvider, PsAttachItemsProvider, WmicAttachItemsProvider } from './nativeAttach';

export interface WaitForProcessProvider {
poll(program: string, timeout: number, interval: number, token?: vscode.CancellationToken): Promise<string | undefined>
}

export class PollProcessProviderFactory {
static Get(): WaitForProcessProvider {
if (os.platform() === 'win32') {
const pwsh: string | undefined = util.findPowerShell();
let itemsProvider = pwsh ? new CimAttachItemsProvider(pwsh) : new WmicAttachItemsProvider();
return new PollWindowsProvider(itemsProvider);
} else {
// Linux and MacOS
return new PollProcProvider(new PsAttachItemsProvider());
}
}
}

export class PollProcProvider implements WaitForProcessProvider {

constructor(itemsProvider: PsAttachItemsProvider) {
this.itemsProvider = itemsProvider;
}

private itemsProvider: PsAttachItemsProvider;

async poll(program: string, timeout: number, interval: number, token?: vscode.CancellationToken): Promise<string | undefined> {
return new Promise<string | undefined>(async (resolve, reject) => {
const startTime = Date.now(); // Get the current time in milliseconds
let process: string | undefined;
while (true) {
let elapsedTime = Date.now() - startTime;
if (elapsedTime >= timeout) {
reject(new Error(localize("waitfor.timeout", "Timeout reached. No process matched the pattern.")));
}

if (token?.isCancellationRequested) {
reject(new Error(localize("waitfor.cancelled", "Operation cancelled.")));
}

let procs = await this.itemsProvider.getAttachItems(token)
for (const proc of procs) {
if (proc.detail?.includes(program)) {
process = proc.id
break
}
}

if (process) {
await util.execChildProcess(`kill -STOP ${process}`, undefined, undefined);
break
}

sleep(interval)
}

resolve(process)
})
}
}

export class PollWindowsProvider implements WaitForProcessProvider {
constructor(itemsProvider: CimAttachItemsProvider | WmicAttachItemsProvider) {
this.itemsProvider = itemsProvider;
}

private itemsProvider: CimAttachItemsProvider | WmicAttachItemsProvider;

public async poll(program: string, timeout: number, interval: number, token?: vscode.CancellationToken): Promise<string | undefined> {
return new Promise<string | undefined>(async (resolve, reject) => {
const startTime = Date.now(); // Get the current time in milliseconds
let process: string | undefined;
while (true) {
const elapsedTime = Date.now() - startTime;
if (elapsedTime >= timeout) {
reject(new Error(localize("waitfor.timeout", "Timeout reached. No process matched the pattern.")));
}

// Check for cancellation
if (token?.isCancellationRequested) {
reject(new Error(localize("waitfor.cancelled", "Operation cancelled.")));
}

let procs = await this.itemsProvider.getAttachItems(token)
for (const proc of procs) {
if (proc.detail?.includes(program)) {
process = proc.id
break
}
}

if (process) {
// Use pssupend to send SIGSTOP analogous in Windows
await util.execChildProcess(`pssuspend.exe /accepteula -nobanner ${process}`, undefined, undefined)
break
}

sleep(interval)
}
resolve(process)
})
}
}


export class AttachWaitFor {
constructor(poller: WaitForProcessProvider) {
//this._channel = vscode.window.createOutputChannel('waitfor-attach');
this.poller = poller;

}

// Defaults: ms
private timeout: number = 10000;
private interval: number = 150;
private poller: WaitForProcessProvider;

public async WaitForProcess(program: string, timeout: number, interval: number, token?: vscode.CancellationToken): Promise<string | undefined> {
if (timeout) {
this.timeout = timeout;
}
if (interval) {
this.interval = interval;
}
return await this.poller.poll(program, this.timeout, this.interval, token);
}
}
32 changes: 25 additions & 7 deletions Extension/src/Debugger/configurationProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { PlatformInformation } from '../platform';
import { rsync, scp, ssh } from '../SSH/commands';
import * as Telemetry from '../telemetry';
import { AttachItemsProvider, AttachPicker, RemoteAttachPicker } from './attachToProcess';
import { AttachWaitFor, PollProcessProviderFactory, WaitForProcessProvider } from './attachWaitFor';
import { ConfigMenu, ConfigMode, ConfigSource, CppDebugConfiguration, DebuggerEvent, DebuggerType, DebugType, IConfiguration, IConfigurationSnippet, isDebugLaunchStr, MIConfigurations, PipeTransportConfigurations, TaskStatus, WindowsConfigurations, WSLConfigurations } from './configurations';
import { NativeAttachItemsProviderFactory } from './nativeAttach';
import { Environment, ParsedEnvironmentFile } from './ParsedEnvironmentFile';
Expand Down Expand Up @@ -347,16 +348,33 @@ export class DebugConfigurationProvider implements vscode.DebugConfigurationProv
}
}

// Pick process if process id is empty
if (config.request === "attach" && !config.processId) {
let processId: string | undefined;
if (config.pipeTransport || config.useExtendedRemote) {
const remoteAttachPicker: RemoteAttachPicker = new RemoteAttachPicker();
processId = await remoteAttachPicker.ShowAttachEntries(config);
if (config.waitFor.enabled) {
const pollProvider: WaitForProcessProvider = PollProcessProviderFactory.Get();
const waitForAttach: AttachWaitFor = new AttachWaitFor(pollProvider);
if (config.waitFor.process === "") {
void logger.getOutputChannelLogger().showErrorMessage(localize("waitfor.process.empty", "Wait for Process name is empty."));
return undefined;
}
if (config.waitFor.timeout < 0) {
void logger.getOutputChannelLogger().showErrorMessage(localize("waitfor.timeout.value", "Wait for Timeout value should be non zero."));
return undefined;
}
if (config.waitFor.interval < 0) {
void logger.getOutputChannelLogger().showErrorMessage(localize("waitfor.interval.value", "Wait for Interval value should be non zero."));
return undefined;
}
processId = await waitForAttach.WaitForProcess(config.waitFor.process, config.waitFor.timeout, config.waitFor.interval, token);
} else {
const attachItemsProvider: AttachItemsProvider = NativeAttachItemsProviderFactory.Get();
const attacher: AttachPicker = new AttachPicker(attachItemsProvider);
processId = await attacher.ShowAttachEntries(token);
if (config.pipeTransport || config.useExtendedRemote) {
const remoteAttachPicker: RemoteAttachPicker = new RemoteAttachPicker();
processId = await remoteAttachPicker.ShowAttachEntries(config);
} else {
const attachItemsProvider: AttachItemsProvider = NativeAttachItemsProviderFactory.Get();
const attacher: AttachPicker = new AttachPicker(attachItemsProvider);
processId = await attacher.ShowAttachEntries(token);
}
}

if (processId) {
Expand Down
7 changes: 4 additions & 3 deletions Extension/src/Debugger/configurations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ function createLaunchString(name: string, type: string, executable: string): str
"stopAtEntry": false,
"cwd": "$\{fileDirname\}",
"environment": [],
${ type === "cppdbg" ? `"externalConsole": false` : `"console": "externalTerminal"` }
${type === "cppdbg" ? `"externalConsole": false` : `"console": "externalTerminal"`}
`;
}

Expand All @@ -119,6 +119,7 @@ function createRemoteAttachString(name: string, type: string, executable: string
`;
}


function createPipeTransportString(pipeProgram: string, debuggerProgram: string, pipeArgs: string[] = []): string {
return `
"pipeTransport": {
Expand Down Expand Up @@ -164,7 +165,7 @@ export class MIConfigurations extends Configuration {
\t${indentJsonString(createLaunchString(name, this.miDebugger, this.executable))},
\t"MIMode": "${this.MIMode}"{0}{1}
}`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "",
this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]);
this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]);

return {
"label": configPrefix + name,
Expand All @@ -182,7 +183,7 @@ export class MIConfigurations extends Configuration {
\t${indentJsonString(createAttachString(name, this.miDebugger, this.executable))}
\t"MIMode": "${this.MIMode}"{0}{1}
}`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "",
this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]);
this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]);

return {
"label": configPrefix + name,
Expand Down
4 changes: 4 additions & 0 deletions Extension/src/Debugger/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ export async function initialize(context: vscode.ExtensionContext): Promise<void
}
}
}));




}

export function dispose(): void {
Expand Down
15 changes: 10 additions & 5 deletions Extension/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -734,13 +734,18 @@ export function execChildProcess(process: string, workingDirectory?: string, cha
}
}

if (error) {
reject(error);
return;
if (stderr && stderr.length > 0) {
if (stderr.indexOf('screen size is bogus') >= 0) {
// ignore this error silently; see https://github.com/microsoft/vscode/issues/75932
// see similar fix for the Node - Debug (Legacy) Extension at https://github.com/microsoft/vscode-node-debug/commit/5298920
} else {
reject(error);
return;
}
}

if (stderr && stderr.length > 0) {
reject(new Error(stderr));
if (error) {
reject(error);
return;
}

Expand Down
26 changes: 26 additions & 0 deletions Extension/tools/OptionsSchema.json
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,28 @@
},
"default": []
},
"WaitFor": {
"type": "object",
"description": "%c_cpp.debuggers.waitFor.description%",
"default": {},
"properties": {
"timeout": {
"type": "integer",
"description": "%c_cpp.debuggers.waitFor.timeout.description%",
"default": 10000
},
"interval": {
"type": "integer",
"description": "%c_cpp.debuggers.waitFor.interval.description%",
"default": 150
},
"pattern": {
"type": "string",
"description": "%c_cpp.debuggers.waitFor.pattern.description%",
"default": ""
}
}
},
"CppdbgLaunchOptions": {
"type": "object",
"required": [
Expand Down Expand Up @@ -923,6 +945,10 @@
}
]
},
"waitFor": {
"$ref": "#/definitions/WaitFor",
"description": "%c_cpp.debuggers.waitFor.description%"
},
"logging": {
"$ref": "#/definitions/Logging",
"description": "%c_cpp.debuggers.logging.description%"
Expand Down
Loading