-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathdebug-session-connection.ts
357 lines (319 loc) · 15.6 KB
/
debug-session-connection.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
// *****************************************************************************
// Copyright (C) 2018 Red Hat, Inc. 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-only WITH Classpath-exception-2.0
// *****************************************************************************
/* eslint-disable @typescript-eslint/no-explicit-any */
import { DebugProtocol } from '@vscode/debugprotocol';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { Event, Emitter, DisposableCollection, Disposable, MaybePromise } from '@theia/core';
import { OutputChannel } from '@theia/output/lib/browser/output-channel';
import { DebugChannel } from '../common/debug-service';
export type DebugRequestHandler = (request: DebugProtocol.Request) => MaybePromise<any>;
export interface DebugRequestTypes {
'attach': [DebugProtocol.AttachRequestArguments, DebugProtocol.AttachResponse]
'breakpointLocations': [DebugProtocol.BreakpointLocationsArguments, DebugProtocol.BreakpointLocationsResponse]
'cancel': [DebugProtocol.CancelArguments, DebugProtocol.CancelResponse]
'completions': [DebugProtocol.CompletionsArguments, DebugProtocol.CompletionsResponse]
'configurationDone': [DebugProtocol.ConfigurationDoneArguments, DebugProtocol.ConfigurationDoneResponse]
'continue': [DebugProtocol.ContinueArguments, DebugProtocol.ContinueResponse]
'dataBreakpointInfo': [DebugProtocol.DataBreakpointInfoArguments, DebugProtocol.DataBreakpointInfoResponse]
'disassemble': [DebugProtocol.DisassembleArguments, DebugProtocol.DisassembleResponse]
'disconnect': [DebugProtocol.DisconnectArguments, DebugProtocol.DisconnectResponse]
'evaluate': [DebugProtocol.EvaluateArguments, DebugProtocol.EvaluateResponse]
'exceptionInfo': [DebugProtocol.ExceptionInfoArguments, DebugProtocol.ExceptionInfoResponse]
'goto': [DebugProtocol.GotoArguments, DebugProtocol.GotoResponse]
'gotoTargets': [DebugProtocol.GotoTargetsArguments, DebugProtocol.GotoTargetsResponse]
'initialize': [DebugProtocol.InitializeRequestArguments, DebugProtocol.InitializeResponse]
'launch': [DebugProtocol.LaunchRequestArguments, DebugProtocol.LaunchResponse]
'loadedSources': [DebugProtocol.LoadedSourcesArguments, DebugProtocol.LoadedSourcesResponse]
'modules': [DebugProtocol.ModulesArguments, DebugProtocol.ModulesResponse]
'next': [DebugProtocol.NextArguments, DebugProtocol.NextResponse]
'pause': [DebugProtocol.PauseArguments, DebugProtocol.PauseResponse]
'readMemory': [DebugProtocol.ReadMemoryArguments, DebugProtocol.ReadMemoryResponse]
'restart': [DebugProtocol.RestartArguments, DebugProtocol.RestartResponse]
'restartFrame': [DebugProtocol.RestartFrameArguments, DebugProtocol.RestartFrameResponse]
'reverseContinue': [DebugProtocol.ReverseContinueArguments, DebugProtocol.ReverseContinueResponse]
'scopes': [DebugProtocol.ScopesArguments, DebugProtocol.ScopesResponse]
'setBreakpoints': [DebugProtocol.SetBreakpointsArguments, DebugProtocol.SetBreakpointsResponse]
'setDataBreakpoints': [DebugProtocol.SetDataBreakpointsArguments, DebugProtocol.SetDataBreakpointsResponse]
'setExceptionBreakpoints': [DebugProtocol.SetExceptionBreakpointsArguments, DebugProtocol.SetExceptionBreakpointsResponse]
'setExpression': [DebugProtocol.SetExpressionArguments, DebugProtocol.SetExpressionResponse]
'setFunctionBreakpoints': [DebugProtocol.SetFunctionBreakpointsArguments, DebugProtocol.SetFunctionBreakpointsResponse]
'setInstructionBreakpoints': [DebugProtocol.SetInstructionBreakpointsArguments, DebugProtocol.SetInstructionBreakpointsResponse]
'setVariable': [DebugProtocol.SetVariableArguments, DebugProtocol.SetVariableResponse]
'source': [DebugProtocol.SourceArguments, DebugProtocol.SourceResponse]
'stackTrace': [DebugProtocol.StackTraceArguments, DebugProtocol.StackTraceResponse]
'stepBack': [DebugProtocol.StepBackArguments, DebugProtocol.StepBackResponse]
'stepIn': [DebugProtocol.StepInArguments, DebugProtocol.StepInResponse]
'stepInTargets': [DebugProtocol.StepInTargetsArguments, DebugProtocol.StepInTargetsResponse]
'stepOut': [DebugProtocol.StepOutArguments, DebugProtocol.StepOutResponse]
'terminate': [DebugProtocol.TerminateArguments, DebugProtocol.TerminateResponse]
'terminateThreads': [DebugProtocol.TerminateThreadsArguments, DebugProtocol.TerminateThreadsResponse]
'threads': [{}, DebugProtocol.ThreadsResponse]
'variables': [DebugProtocol.VariablesArguments, DebugProtocol.VariablesResponse]
'writeMemory': [DebugProtocol.WriteMemoryArguments, DebugProtocol.WriteMemoryResponse]
}
export interface DebugEventTypes {
'breakpoint': DebugProtocol.BreakpointEvent
'capabilities': DebugProtocol.CapabilitiesEvent
'continued': DebugProtocol.ContinuedEvent
'exited': DebugProtocol.ExitedEvent,
'initialized': DebugProtocol.InitializedEvent
'invalidated': DebugProtocol.InvalidatedEvent
'loadedSource': DebugProtocol.LoadedSourceEvent
'module': DebugProtocol.ModuleEvent
'output': DebugProtocol.OutputEvent
'process': DebugProtocol.ProcessEvent
'progressEnd': DebugProtocol.ProgressEndEvent
'progressStart': DebugProtocol.ProgressStartEvent
'progressUpdate': DebugProtocol.ProgressUpdateEvent
'stopped': DebugProtocol.StoppedEvent
'terminated': DebugProtocol.TerminatedEvent
'thread': DebugProtocol.ThreadEvent
}
export type DebugEventNames = keyof DebugEventTypes;
export namespace DebugEventTypes {
export function isStandardEvent(event: string): event is DebugEventNames {
return standardDebugEvents.has(event);
};
}
const standardDebugEvents = new Set<string>([
'breakpoint',
'capabilities',
'continued',
'exited',
'initialized',
'invalidated',
'loadedSource',
'module',
'output',
'process',
'progressEnd',
'progressStart',
'progressUpdate',
'stopped',
'terminated',
'thread'
]);
export class DebugSessionConnection implements Disposable {
private sequence = 1;
protected readonly pendingRequests = new Map<number, Deferred<DebugProtocol.Response>>();
protected readonly connectionPromise: Promise<DebugChannel>;
protected readonly requestHandlers = new Map<string, DebugRequestHandler>();
protected readonly onDidCustomEventEmitter = new Emitter<DebugProtocol.Event>();
readonly onDidCustomEvent: Event<DebugProtocol.Event> = this.onDidCustomEventEmitter.event;
protected readonly onDidCloseEmitter = new Emitter<void>();
readonly onDidClose: Event<void> = this.onDidCloseEmitter.event;
protected isClosed = false;
protected readonly toDispose = new DisposableCollection(
this.onDidCustomEventEmitter,
Disposable.create(() => this.pendingRequests.clear()),
Disposable.create(() => this.emitters.clear())
);
constructor(
readonly sessionId: string,
connectionFactory: (sessionId: string) => Promise<DebugChannel>,
protected readonly traceOutputChannel: OutputChannel | undefined
) {
this.connectionPromise = this.createConnection(connectionFactory);
}
get disposed(): boolean {
return this.toDispose.disposed;
}
protected checkDisposed(): void {
if (this.disposed) {
throw new Error('the debug session connection is disposed, id: ' + this.sessionId);
}
}
dispose(): void {
this.toDispose.dispose();
}
protected async createConnection(connectionFactory: (sessionId: string) => Promise<DebugChannel>): Promise<DebugChannel> {
const connection = await connectionFactory(this.sessionId);
connection.onClose(() => {
this.isClosed = true;
this.cancelPendingRequests();
this.onDidCloseEmitter.fire();
});
connection.onMessage(data => this.handleMessage(data));
return connection;
}
protected allThreadsContinued = true;
async sendRequest<K extends keyof DebugRequestTypes>(command: K, args: DebugRequestTypes[K][0], timeout?: number): Promise<DebugRequestTypes[K][1]> {
const result = await this.doSendRequest(command, args, timeout);
if (command === 'next' || command === 'stepIn' ||
command === 'stepOut' || command === 'stepBack' ||
command === 'reverseContinue' || command === 'restartFrame') {
this.fireContinuedEvent((args as any).threadId);
}
if (command === 'continue') {
const response = result as DebugProtocol.ContinueResponse;
const allThreadsContinued = response && response.body && response.body.allThreadsContinued;
if (allThreadsContinued !== undefined) {
this.allThreadsContinued = result.body.allThreadsContinued;
}
this.fireContinuedEvent((args as any).threadId, this.allThreadsContinued);
return result;
}
return result;
}
sendCustomRequest<T extends DebugProtocol.Response>(command: string, args?: any): Promise<T> {
return this.doSendRequest<T>(command, args);
}
protected cancelPendingRequests(): void {
this.pendingRequests.forEach((deferred, requestId) => {
deferred.reject(new Error(`Request ${requestId} cancelled on connection close`));
});
}
protected doSendRequest<K extends DebugProtocol.Response>(command: string, args?: any, timeout?: number): Promise<K> {
const result = new Deferred<K>();
if (this.isClosed) {
result.reject(new Error('Connection is closed'));
} else {
const request: DebugProtocol.Request = {
seq: this.sequence++,
type: 'request',
command: command,
arguments: args
};
this.pendingRequests.set(request.seq, result);
if (timeout) {
const handle = setTimeout(() => {
const pendingRequest = this.pendingRequests.get(request.seq);
if (pendingRequest) {
// request has not been handled
this.pendingRequests.delete(request.seq);
const error: DebugProtocol.Response = {
type: 'response',
seq: 0,
request_seq: request.seq,
success: false,
command,
message: `Request #${request.seq}: ${request.command} timed out`
};
pendingRequest.reject(error);
}
}, timeout);
result.promise.finally(() => clearTimeout(handle));
}
this.send(request);
}
return result.promise;
}
protected async send(message: DebugProtocol.ProtocolMessage): Promise<void> {
const connection = await this.connectionPromise;
const messageStr = JSON.stringify(message);
if (this.traceOutputChannel) {
const now = new Date();
const dateStr = `${now.toLocaleString(undefined, { hour12: false })}.${now.getMilliseconds()}`;
this.traceOutputChannel.appendLine(`${this.sessionId.substring(0, 8)} ${dateStr} theia -> adapter: ${JSON.stringify(message, undefined, 4)}`);
}
connection.send(messageStr);
}
protected handleMessage(data: string): void {
const message: DebugProtocol.ProtocolMessage = JSON.parse(data);
if (this.traceOutputChannel) {
const now = new Date();
const dateStr = `${now.toLocaleString(undefined, { hour12: false })}.${now.getMilliseconds()}`;
this.traceOutputChannel.appendLine(`${this.sessionId.substring(0, 8)} ${dateStr} theia <- adapter: ${JSON.stringify(message, undefined, 4)}`);
}
if (message.type === 'request') {
this.handleRequest(message as DebugProtocol.Request);
} else if (message.type === 'response') {
this.handleResponse(message as DebugProtocol.Response);
} else if (message.type === 'event') {
this.handleEvent(message as DebugProtocol.Event);
}
}
protected handleResponse(response: DebugProtocol.Response): void {
const pendingRequest = this.pendingRequests.get(response.request_seq);
if (pendingRequest) {
this.pendingRequests.delete(response.request_seq);
if (!response.success) {
pendingRequest.reject(response);
} else {
pendingRequest.resolve(response);
}
}
}
onRequest(command: string, handler: DebugRequestHandler): void {
this.requestHandlers.set(command, handler);
}
protected async handleRequest(request: DebugProtocol.Request): Promise<void> {
const response: DebugProtocol.Response = {
type: 'response',
seq: 0,
command: request.command,
request_seq: request.seq,
success: true,
};
const handler = this.requestHandlers.get(request.command);
if (handler) {
try {
response.body = await handler(request);
} catch (error) {
response.success = false;
response.message = error.message;
}
} else {
console.error('Unhandled request', request);
}
await this.send(response);
}
protected handleEvent(event: DebugProtocol.Event): void {
if (event.event === 'continued') {
this.allThreadsContinued = (<DebugProtocol.ContinuedEvent>event).body.allThreadsContinued === false ? false : true;
}
if (DebugEventTypes.isStandardEvent(event.event)) {
this.doFire(event.event, event);
} else {
this.onDidCustomEventEmitter.fire(event);
}
}
protected readonly emitters = new Map<string, Emitter<DebugProtocol.Event>>();
on<K extends keyof DebugEventTypes>(kind: K, listener: (e: DebugEventTypes[K]) => any): Disposable {
return this.getEmitter(kind).event(listener);
}
onEvent<K extends keyof DebugEventTypes>(kind: K): Event<DebugEventTypes[K]> {
return this.getEmitter(kind).event;
}
protected fire<K extends keyof DebugEventTypes>(kind: K, e: DebugEventTypes[K]): void {
this.doFire(kind, e);
}
protected doFire<K extends keyof DebugEventTypes>(kind: K, e: DebugEventTypes[K]): void {
this.getEmitter(kind).fire(e);
}
protected getEmitter<K extends keyof DebugEventTypes>(kind: K): Emitter<DebugEventTypes[K]> {
const emitter = this.emitters.get(kind) || this.newEmitter();
this.emitters.set(kind, emitter);
return <Emitter<DebugEventTypes[K]>>emitter;
}
protected newEmitter(): Emitter<DebugProtocol.Event> {
const emitter = new Emitter();
this.checkDisposed();
this.toDispose.push(emitter);
return emitter;
}
protected fireContinuedEvent(threadId: number, allThreadsContinued = false): void {
this.fire('continued', {
type: 'event',
event: 'continued',
body: {
threadId,
allThreadsContinued
},
seq: -1
});
}
}