-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdebugAdapter.ts
More file actions
351 lines (291 loc) · 12.4 KB
/
debugAdapter.ts
File metadata and controls
351 lines (291 loc) · 12.4 KB
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
/**
* debugAdapter.ts implements the Debug Adapter protocol and integrates it with the log2src
* "debugger".
*/
import {
Logger, logger,
LoggingDebugSession,
Thread, StackFrame, Scope, Source,
InitializedEvent, StoppedEvent,
Handles,
} from '@vscode/debugadapter';
import { DebugProtocol } from '@vscode/debugprotocol';
import * as vscode from 'vscode';
import * as path from 'path';
import { outputChannel } from './extension';
import { LogDebugger } from './logDebugger';
interface CallSite {
name: string,
sourcePath: string,
lineNumber: number
}
interface LogMapping {
srcRef: SourceRef,
exceptionTrace: Array<CallSite>,
variables: Array<VariablePair>
}
interface VariablePair {
expr: string,
value: string,
}
interface SourceRef {
sourcePath: string,
lineNumber: number,
column: number,
name: string,
}
export interface ILaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
// the source to debug, currently a single file
source: string;
// the log files to use for "debugging"
log: string;
// the format of the log to parse the file name and line number
log_format: string;
// enable logging
trace?: boolean;
// If true, the launch request should launch the program without enabling debugging.
noDebug?: boolean;
}
interface IAttachRequestArguments extends ILaunchRequestArguments { }
const PLATFORM_TO_BINARY = new Map<string, string>([
["darwin-arm64", "../bin/darwin-arm64/log2src"],
["darwin-x64", "../bin/darwin-x64/log2src"],
["linux-x64", "../bin/linux-x64/log2src"],
["win32-x64", "../bin/win-x64/log2src.exe"],
]);
export class BinaryNotFoundError extends Error {
constructor(message: string) {
super(message);
this.name = "BinaryNotFoundError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, BinaryNotFoundError);
}
}
}
export class DebugSession extends LoggingDebugSession {
private static _threadID = 1;
private _binaryPath: string;
private readonly _variableHandles = new Handles<'locals'>();
private _launchArgs: ILaunchRequestArguments = { source: "", log: "", log_format: "" };
private readonly _highlightDecoration: vscode.TextEditorDecorationType;
private _mapping?: LogMapping = undefined;
private readonly _logDebugger: LogDebugger;
/**
* Create a new debug adapter to use with a debug session.
*/
public constructor(logDebugger: LogDebugger) {
super("log2src-dap.txt");
this._binaryPath = PLATFORM_TO_BINARY.get(`${process.platform}-${process.arch}`)!;
if (!this._binaryPath) {
throw new BinaryNotFoundError(
`No binary available for platform: ${process.platform} and architecture: ${process.arch}`
);
}
this._logDebugger = logDebugger;
this.setDebuggerLinesStartAt1(true);
this.setDebuggerColumnsStartAt1(true);
const focusColor = new vscode.ThemeColor('editor.focusedStackFrameHighlightBackground');
this._highlightDecoration = vscode.window.createTextEditorDecorationType({ "backgroundColor": focusColor });
outputChannel.appendLine("Starting up...");
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): void {
console.log(`disconnectRequest suspend: ${args.suspendDebuggee}, terminate: ${args.terminateDebuggee}`);
vscode.window.visibleTextEditors.forEach((editor) => editor.setDecorations(this._highlightDecoration, []));
this.sendResponse(response);
}
/**
* The 'initialize' request is the first request called by the frontend
* to interrogate the features the debug adapter provides.
*/
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
console.log(`initializeRequest: ${JSON.stringify(args)}`);
response.body = response.body || {};
response.body.supportsStepBack = true;
// response.body.supportsBreakpointLocationsRequest = true;
response.body.supportTerminateDebuggee = true;
this.sendResponse(response);
this.sendEvent(new InitializedEvent());
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments) {
console.log(`setBreakPointsRequest ${JSON.stringify(args)}`);
const source = args.source.path as string;
const bps = args.breakpoints || [];
const breakpoints = this._logDebugger.setBreakPoint(source, bps);
response.body = {
breakpoints: breakpoints
};
if (breakpoints.length > 0) {
this.sendEvent(new StoppedEvent('breakpoint', DebugSession._threadID));
}
return this.sendResponse(response);
}
protected attachRequest(response: DebugProtocol.AttachResponse, args: IAttachRequestArguments) {
console.log(`attachRequest`);
return this.launchRequest(response, args);
}
protected launchRequest(response: DebugProtocol.LaunchResponse, args: ILaunchRequestArguments) {
outputChannel.appendLine(`launchRequest ${JSON.stringify(args)}`);
// make sure to 'Stop' the buffered logging if 'trace' is not set
logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Error, false);
this._launchArgs = args;
this.openLogAndFocus();
const execFile = require('child_process').execFileSync;
let stdout = execFile('wc', ['-l', this._launchArgs.log]);
const logLines = +stdout.toString().trim().split(" ")[0] || Number.MAX_VALUE
this._logDebugger.setToLog(this._launchArgs.log, logLines);
if (!this._logDebugger.hasBreakpoints()) {
this.sendEvent(new StoppedEvent('entry', DebugSession._threadID));
}
this.sendResponse(response);
}
private openLogAndFocus() {
const editors = this.findEditors();
if (editors.length >= 1) {
this.focusEditor(editors[0]);
} else {
Promise.resolve(vscode.workspace.openTextDocument(this._launchArgs.log))
.then(doc => {
return vscode.window.showTextDocument(doc, {
viewColumn: vscode.ViewColumn.Beside,
preserveFocus: false
});
})
.then(editor => {
this.focusEditor(editor);
return editor;
})
.catch(error => {
const message = `Failed to open log file: ${error.message}`;
outputChannel.appendLine(message);
console.error(message);
});
}
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
console.log(`threadsRequest`);
// just sending back junk for now
response.body = {
threads: [
new Thread(DebugSession._threadID, "thread 1"),
]
};
this.sendResponse(response);
}
protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void {
console.log(`continueRequest ${JSON.stringify(args)}`);
this._logDebugger.gotoNextBreakpoint();
this.sendEvent(new StoppedEvent('breakpoint', DebugSession._threadID));
this.sendResponse(response);
}
protected reverseContinueRequest(response: DebugProtocol.ReverseContinueResponse, args: DebugProtocol.ReverseContinueArguments): void {
console.log(`reverseContinueRequest ${JSON.stringify(args)}`);
this._logDebugger.gotoNextBreakpoint(true);
this.sendEvent(new StoppedEvent('breakpoint', DebugSession._threadID));
this.sendResponse(response);
}
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void {
console.log(`nextRequest ${JSON.stringify(args)} line=${this._logDebugger.linenum()}`);
this._logDebugger.stepForward()
this.sendEvent(new StoppedEvent('step', DebugSession._threadID));
this.sendResponse(response);
}
protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void {
console.log(`stepBackRequest ${JSON.stringify(args)} line=${this._logDebugger.linenum()}`);
this._logDebugger.stepBackward();
this.sendEvent(new StoppedEvent('step', DebugSession._threadID));
this.sendResponse(response);
}
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
console.log(`stackTraceRequest ${JSON.stringify(args)}`);
const log2srcPath = path.resolve(__dirname, this._binaryPath);
const execFile = require('child_process').execFileSync;
const start = this._logDebugger.linenum() - 1;
const editors = this.findEditors();
if (editors.length > 0) {
this.focusEditor(editors[0]);
}
let l2sArgs = ['-d', this._launchArgs.source,
'--log', this._launchArgs.log,
'--start', start,
'--count', 1]
if (this._launchArgs.log_format !== undefined && this._launchArgs.log_format !== "") {
l2sArgs.push("-f");
l2sArgs.push(this._launchArgs.log_format);
}
outputChannel.appendLine(`args ${l2sArgs.join(" ")}`);
let stdout = execFile(log2srcPath, l2sArgs);
this._mapping = JSON.parse(stdout.toString('utf8'));
outputChannel.appendLine(`mapped ${JSON.stringify(this._mapping)}`);
let index = 0;
const currentFrame = this.buildStackFrame(index++, this._mapping?.srcRef);
const stack: StackFrame[] = [];
stack.push(currentFrame);
response.body = {
stackFrames: stack,
totalFrames: stack.length
};
this.sendResponse(response);
}
private findEditors(): vscode.TextEditor[] {
const target = path.resolve(this._launchArgs.log);
return vscode.window.visibleTextEditors.filter((editor) => editor.document.fileName === target);
}
private focusEditor(editor: vscode.TextEditor) {
const start = this._logDebugger.linenum() - 1;
let range = new vscode.Range(
new vscode.Position(start, 0),
new vscode.Position(start, Number.MAX_VALUE)
);
editor.setDecorations(this._highlightDecoration, [range]);
editor.revealRange(
range,
vscode.TextEditorRevealType.InCenter
);
}
private buildStackFrame(index: number, srcRef?: SourceRef): StackFrame {
let name = "???";
let lineNumber = -1;
let sourceName = "???";
let sourcePath = "???";
if (srcRef !== null && srcRef !== undefined) {
name = srcRef.name;
lineNumber = srcRef.lineNumber;
const codeSrcPath = path.parse(srcRef.sourcePath);
sourceName = codeSrcPath.base;
sourcePath = srcRef.sourcePath;
}
return new StackFrame(
index,
name,
new Source(sourceName, sourcePath),
this.convertDebuggerLineToClient(lineNumber)
);
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
console.log(`scopesRequest ${JSON.stringify(args)}`);
response.body = {
scopes: [
new Scope("Locals", this._variableHandles.create('locals'), false),
]
};
this.sendResponse(response);
}
protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments, request?: DebugProtocol.Request): void {
console.log(`variablesRequest ${JSON.stringify(args)}`);
let vs: DebugProtocol.Variable[] = [];
const v = this._variableHandles.get(args.variablesReference);
if (v === 'locals' && this._mapping !== undefined) {
for (let pair of this._mapping.variables) {
vs.push({
name: pair.expr,
value: pair.value,
variablesReference: 0
});
}
}
response.body = {
variables: vs
};
this.sendResponse(response);
}
}