Skip to content
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

Add Debug Context Selector #133

Open
wants to merge 4 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
17 changes: 12 additions & 5 deletions src/common/messaging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export type StoreMemoryResult = void;
export type ApplyMemoryArguments = URI | undefined;
export type ApplyMemoryResult = MemoryOptions;

export interface ConnectionContext {
name: string;
id: number;
}

export interface SessionContext {
sessionId?: string;
canRead: boolean;
Expand All @@ -51,15 +56,17 @@ export const setMemoryViewSettingsType: NotificationType<Partial<MemoryViewSetti
export const setTitleType: NotificationType<string> = { method: 'setTitle' };
export const memoryWrittenType: NotificationType<WrittenMemory> = { method: 'memoryWritten' };
export const sessionContextChangedType: NotificationType<SessionContext> = { method: 'sessionContextChanged' };
export const connectionContextChangedType: NotificationType<[ConnectionContext?,
ConnectionContext[]?]> = { method: 'connectionContextChanged' };

// Requests
export const setOptionsType: RequestType<MemoryOptions, void> = { method: 'setOptions' };
export const logMessageType: RequestType<string, void> = { method: 'logMessage' };
export const readMemoryType: RequestType<ReadMemoryArguments, ReadMemoryResult> = { method: 'readMemory' };
export const writeMemoryType: RequestType<WriteMemoryArguments, WriteMemoryResult> = { method: 'writeMemory' };
export const getVariablesType: RequestType<ReadMemoryArguments, VariableRange[]> = { method: 'getVariables' };
export const storeMemoryType: RequestType<StoreMemoryArguments, void> = { method: 'storeMemory' };
export const applyMemoryType: RequestType<ApplyMemoryArguments, ApplyMemoryResult> = { method: 'applyMemory' };
export const readMemoryType: RequestType<[ReadMemoryArguments, ConnectionContext?], ReadMemoryResult> = { method: 'readMemory' };
export const writeMemoryType: RequestType<[WriteMemoryArguments, ConnectionContext?], WriteMemoryResult> = { method: 'writeMemory' };
export const getVariablesType: RequestType<[ReadMemoryArguments, ConnectionContext?], VariableRange[]> = { method: 'getVariables' };
export const storeMemoryType: RequestType<[StoreMemoryArguments, ConnectionContext?], void> = { method: 'storeMemory' };
export const applyMemoryType: RequestType<[ApplyMemoryArguments, ConnectionContext?], ApplyMemoryResult> = { method: 'applyMemory' };

export const showAdvancedOptionsType: NotificationType<void> = { method: 'showAdvancedOptions' };
export const getWebviewSelectionType: RequestType<void, WebviewSelection> = { method: 'getWebviewSelection' };
Expand Down
5 changes: 5 additions & 0 deletions src/entry-points/desktop/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@

import * as vscode from 'vscode';
import { AdapterRegistry } from '../../plugin/adapter-registry/adapter-registry';
import { AmalgamatorGdbVariableTransformer, AmalgamatorSessionManager } from '../../plugin/adapter-registry/amalgamator-gdb-tracker';
import { CAdapter } from '../../plugin/adapter-registry/c-adapter';
import { ContextTracker } from '../../plugin/context-tracker';
import { outputChannelLogger } from '../../plugin/logger';
import { MemoryProvider } from '../../plugin/memory-provider';
import { MemoryStorage } from '../../plugin/memory-storage';
import { MemoryWebview } from '../../plugin/memory-webview-main';
Expand All @@ -32,6 +34,9 @@ export const activate = async (context: vscode.ExtensionContext): Promise<Adapte
const memoryStorage = new MemoryStorage(memoryProvider);
const cAdapter = new CAdapter(registry);

const debugTypes = ['amalgamator'];
registry.registerAdapter(new AmalgamatorSessionManager(AmalgamatorGdbVariableTransformer, outputChannelLogger, ...debugTypes), ...debugTypes);

registry.activate(context);
sessionTracker.activate(context);
memoryProvider.activate(context);
Expand Down
44 changes: 29 additions & 15 deletions src/plugin/adapter-registry/adapter-capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,29 @@ import { DebugProtocol } from '@vscode/debugprotocol';
import * as vscode from 'vscode';
import { isDebugRequest, isDebugResponse } from '../../common/debug-requests';
import { VariableRange } from '../../common/memory-range';
import { ConnectionContext, ReadMemoryArguments, ReadMemoryResult,
WriteMemoryArguments, WriteMemoryResult } from '../../common/messaging';
import { MemoryDisplaySettingsContribution } from '../../common/webview-configuration';
import { Logger } from '../logger';

/** Represents capabilities that may be achieved with particular debug adapters but are not part of the DAP */
export interface AdapterCapabilities {
/** Resolve variables known to the adapter to their locations. Fallback if {@link getResidents} is not present */
getVariables?(session: vscode.DebugSession): Promise<VariableRange[]>;
getVariables?(session: vscode.DebugSession, context?: ConnectionContext): Promise<VariableRange[]>;
/** Resolve symbols resident in the memory at the specified range. Will be preferred to {@link getVariables} if present. */
getResidents?(session: vscode.DebugSession, params: DebugProtocol.ReadMemoryArguments): Promise<VariableRange[]>;
getResidents?(session: vscode.DebugSession, params: DebugProtocol.ReadMemoryArguments, context?: ConnectionContext): Promise<VariableRange[]>;
/** Resolves the address of a given variable in bytes with the current context. */
getAddressOfVariable?(session: vscode.DebugSession, variableName: string): Promise<string | undefined>;
getAddressOfVariable?(session: vscode.DebugSession, variableName: string, context?: ConnectionContext): Promise<string | undefined>;
/** Resolves the size of a given variable in bytes within the current context. */
getSizeOfVariable?(session: vscode.DebugSession, variableName: string): Promise<bigint | undefined>;
getSizeOfVariable?(session: vscode.DebugSession, variableName: string, context?: ConnectionContext): Promise<bigint | undefined>;
/** Retrieve the suggested default display settings for the memory view. */
getMemoryDisplaySettings?(session: vscode.DebugSession): Promise<Partial<MemoryDisplaySettingsContribution>>;
/** Initialize the trackers of this adapter's for the debug session. */
initializeAdapterTracker?(session: vscode.DebugSession): vscode.DebugAdapterTracker | undefined;
readMemory?(session: vscode.DebugSession, params: ReadMemoryArguments, context?: ConnectionContext): Promise<ReadMemoryResult>;
writeMemory?(session: vscode.DebugSession, params: WriteMemoryArguments, context?: ConnectionContext): Promise<WriteMemoryResult>;
getConnectionContexts?(session: vscode.DebugSession): Promise<ConnectionContext[]>;
getCurrentConnectionContext?(session: vscode.DebugSession): Promise<ConnectionContext | undefined>;
}

export type WithChildren<Original> = Original & { children?: Array<WithChildren<DebugProtocol.Variable>> };
Expand Down Expand Up @@ -105,14 +111,14 @@ export class AdapterVariableTracker implements vscode.DebugAdapterTracker {
this.pendingMessages.clear();
}

async getLocals(session: vscode.DebugSession): Promise<VariableRange[]> {
async getLocals(session: vscode.DebugSession, context?: ConnectionContext): Promise<VariableRange[]> {
this.logger.debug('Retrieving local variables in', session.name + ' Current variables:\n', this.variablesTree);
if (this.currentFrame === undefined) { return []; }
const maybeRanges = await Promise.all(Object.values(this.variablesTree).reduce<Array<Promise<VariableRange | undefined>>>((previous, parent) => {
if (this.isDesiredVariable(parent) && parent.children?.length) {
this.logger.debug('Resolving children of', parent.name);
parent.children.forEach(child => {
previous.push(this.variableToVariableRange(child, session));
previous.push(this.variableToVariableRange(child, session, context));
});
} else {
this.logger.debug('Ignoring', parent.name);
Expand All @@ -126,15 +132,23 @@ export class AdapterVariableTracker implements vscode.DebugAdapterTracker {
return candidate.presentationHint !== 'registers' && candidate.name !== 'Registers';
}

protected variableToVariableRange(_variable: DebugProtocol.Variable, _session: vscode.DebugSession): Promise<VariableRange | undefined> {
protected variableToVariableRange(_variable: DebugProtocol.Variable, _session: vscode.DebugSession,
_context?: ConnectionContext): Promise<VariableRange | undefined> {
throw new Error('To be implemented by derived classes!');
}

/** Resolves the address of a given variable in bytes within the current context. */
getAddressOfVariable?(variableName: string, session: vscode.DebugSession): Promise<string | undefined>;
getAddressOfVariable?(variableName: string, session: vscode.DebugSession, context?: ConnectionContext): Promise<string | undefined>;

/** Resolves the size of a given variable in bytes within the current context. */
getSizeOfVariable?(variableName: string, session: vscode.DebugSession): Promise<bigint | undefined>;
getSizeOfVariable?(variableName: string, session: vscode.DebugSession, context?: ConnectionContext): Promise<bigint | undefined>;

readMemory?(session: vscode.DebugSession, params: ReadMemoryArguments, context?: ConnectionContext): Promise<ReadMemoryResult>;

writeMemory?(session: vscode.DebugSession, params: WriteMemoryArguments, context?: ConnectionContext): Promise<WriteMemoryResult>;

getConnectionContexts?(session: vscode.DebugSession): Promise<ConnectionContext[]>;
getCurrentConnectionContext?(session: vscode.DebugSession): Promise<ConnectionContext | undefined>;
}

export class VariableTracker implements AdapterCapabilities {
Expand All @@ -156,15 +170,15 @@ export class VariableTracker implements AdapterCapabilities {
}
}

async getVariables(session: vscode.DebugSession): Promise<VariableRange[]> {
return this.sessions.get(session.id)?.getLocals(session) ?? [];
async getVariables(session: vscode.DebugSession, context?: ConnectionContext): Promise<VariableRange[]> {
return this.sessions.get(session.id)?.getLocals(session, context) ?? [];
}

async getAddressOfVariable(session: vscode.DebugSession, variableName: string): Promise<string | undefined> {
return this.sessions.get(session.id)?.getAddressOfVariable?.(variableName, session);
async getAddressOfVariable(session: vscode.DebugSession, variableName: string, context?: ConnectionContext): Promise<string | undefined> {
return this.sessions.get(session.id)?.getAddressOfVariable?.(variableName, session, context);
}

async getSizeOfVariable(session: vscode.DebugSession, variableName: string): Promise<bigint | undefined> {
return this.sessions.get(session.id)?.getSizeOfVariable?.(variableName, session);
async getSizeOfVariable(session: vscode.DebugSession, variableName: string, context?: ConnectionContext): Promise<bigint | undefined> {
return this.sessions.get(session.id)?.getSizeOfVariable?.(variableName, session, context);
}
}
114 changes: 114 additions & 0 deletions src/plugin/adapter-registry/amalgamator-gdb-tracker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/********************************************************************************
* Copyright (C) 2024 Ericsson, Arm and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/

import { DebugProtocol } from '@vscode/debugprotocol';
import * as vscode from 'vscode';
import { ConnectionContext, ReadMemoryArguments, ReadMemoryResult, WriteMemoryArguments, WriteMemoryResult } from '../../common/messaging';
import { AdapterCapabilities, AdapterVariableTracker, VariableTracker } from './adapter-capabilities';

// Copied from cdt-amalgamator [AmalgamatorSession.d.ts] file
/**
* Response for our custom 'cdt-amalgamator/getChildDaps' request.
*/
export interface ConnectionContexts {
children?: ConnectionContext[];
}
export interface GetContextsResponse extends DebugProtocol.Response {
body: ConnectionContexts;
}
export type GetContextsResult = GetContextsResponse['body'];

export interface AmalgamatorReadArgs extends ReadMemoryArguments {
child: ConnectionContext;
}

export class AmalgamatorSessionManager extends VariableTracker implements AdapterCapabilities {
Copy link
Contributor

Choose a reason for hiding this comment

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

It sounds like we likely want to move this over to the Amalgamator repository and make it dependent on this plugin (or at least propose it).

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree with @colin-grant-work . I think this is a great example of how a custom adapter implementation could look like.
But ideally it would be contributed by the debug adapter. Or was the intention to use it in a downstream version of the Memory Inspector, @WyoTwT ?

Maybe we can build some "how to implement your own adapter contribution" docs around it in https://github.com/eclipse-cdt-cloud/vscode-memory-inspector?tab=readme-ov-file#the-memory-provider ? It could be a nice story to demonstrate this with two Eclipse CDT Cloud components.

Another thing this PR shows me is that we may want to consider to somehow provide access to the default adapter implementation for reuse in custom implementations. Beyond asking developers to include the according sources from this repo.

Copy link
Author

Choose a reason for hiding this comment

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

It doesn't appear there is an easy way to get access to the AdapterCapabilities, AdapterVariableTracker, and VariableTracker if this code is moved to the Amalgamator repository.

I could duplicate the interfaces in Amalgamator which is what I did with the Context because that wasn't shared from the Amalgamator. Would restructuring the code differently facilitate future movement of some parts into a form that could be reused for custom implementations?

I'm rather new to this so all suggestions to better structure the code are welcome but I may need additional clarification.

async getConnectionContexts(session: vscode.DebugSession): Promise<ConnectionContext[]> {
return this.sessions.get(session.id)?.getConnectionContexts?.(session) || [];
}

async readMemory(session: vscode.DebugSession, args: ReadMemoryArguments, context: ConnectionContext): Promise<ReadMemoryResult> {
if (!context) {
vscode.window.showErrorMessage('Invalid context for Amalgamator. Select Context in Dropdown');
return {
address: args.memoryReference
};
}
return this.sessions.get(session.id)?.readMemory?.(session, args, context);
}

async writeMemory(session: vscode.DebugSession, args: WriteMemoryArguments, context: ConnectionContext): Promise<WriteMemoryResult> {
return this.sessions.get(session.id)?.writeMemory?.(session, args, context);
}

async getCurrentConnectionContext(session: vscode.DebugSession): Promise<ConnectionContext | undefined> {
return this.sessions.get(session.id)?.getCurrentConnectionContext?.(session);
}
}

export class AmalgamatorGdbVariableTransformer extends AdapterVariableTracker {
protected connectionContexts?: ConnectionContext[];
protected currentConnectionContext?: ConnectionContext;

onWillReceiveMessage(message: unknown): void {
if (isStacktraceRequest(message)) {
if (typeof (message.arguments.threadId) !== 'undefined') {
this.currentConnectionContext = {
id: message.arguments.threadId,
name: message.arguments.threadId.toString()
};
} else {
this.logger.warn('Invalid ThreadID in stackTrace');
this.currentConnectionContext = undefined;
}
} else {
super.onWillReceiveMessage(message);
}
}

get frame(): number | undefined { return this.currentFrame; }

async getConnectionContexts(session: vscode.DebugSession): Promise<ConnectionContext[]> {
if (!this.connectionContexts) {
const contexts: GetContextsResult = (await session.customRequest('cdt-amalgamator/getChildDaps'));
this.connectionContexts = contexts.children?.map(({ name, id }) => ({ name, id })) ?? [];
}
return Promise.resolve(this.connectionContexts);
}

async getCurrentConnectionContext(_session: vscode.DebugSession): Promise<ConnectionContext | undefined> {
const curConnectionContext = this.connectionContexts?.length ?
(this.connectionContexts?.filter(context => context.id === this.currentConnectionContext?.id).shift() ??
this.currentConnectionContext) :
this.currentConnectionContext;
return Promise.resolve(curConnectionContext);
}

readMemory(session: vscode.DebugSession, args: ReadMemoryArguments, context: ConnectionContext): Promise<ReadMemoryResult> {
const amalReadArgs: AmalgamatorReadArgs = { ...args, child: context };
return Promise.resolve(session.customRequest('cdt-amalgamator/readMemory', amalReadArgs));
}
}

export function isStacktraceRequest(message: unknown): message is DebugProtocol.StackTraceRequest {
const candidate = message as DebugProtocol.StackTraceRequest;
return !!candidate && candidate.command === 'stackTrace';
}

export function isStacktraceResponse(message: unknown): message is DebugProtocol.StackTraceResponse {
const candidate = message as DebugProtocol.StackTraceResponse;
return !!candidate && candidate.command === 'stackTrace' && Array.isArray(candidate.body.stackFrames);
}
Loading
Loading