forked from OpenModelica/metamodelica-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgdbAdapter.ts
More file actions
456 lines (406 loc) · 15.7 KB
/
gdbAdapter.ts
File metadata and controls
456 lines (406 loc) · 15.7 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2024, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF AGPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.8.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GNU AGPL
* VERSION 3, ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the OSMC (Open Source Modelica Consortium)
* Public License (OSMC-PL) are obtained from OSMC, either from the above
* address, from the URLs:
* http://www.openmodelica.org or
* https://github.com/OpenModelica/ or
* http://www.ida.liu.se/projects/OpenModelica,
* and in the OpenModelica distribution.
*
* GNU AGPL version 3 is obtained from:
* https://www.gnu.org/licenses/licenses.html#GPL
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
import { ChildProcess, spawn } from 'child_process';
import { EventEmitter } from 'events';
import { existsSync } from 'fs';
import * as vscode from 'vscode';
import * as CommandFactory from './commandFactory';
import { logger } from '../../util/logger';
import { GDBMIParser, GDBMIOutput,
GDBMIResult, GDBMIOutOfBandRecord, GDBMIAsyncOutput, GDBMIStreamRecordType
} from '../parser/gdbParser';
export enum GDBCommandFlag {
noFlags = 0,
consoleCommand = 1 << 0, // This is a command that needs to be wrapped into -interpreter-exec console
nonCriticalResponse = 1 << 1,
silentCommand = 1 << 2, // Ignore the error of this command
blockUntilResponse = 1 << 3 // Blocks until the command has received the answer
}
class GDBMICommand {
mFlags: GDBCommandFlag;
mCommand: string;
mCompleted: boolean = false;
constructor(flags: GDBCommandFlag, command: string) {
this.mFlags = flags;
this.mCommand = command;
if ( (flags & GDBCommandFlag.consoleCommand) === GDBCommandFlag.consoleCommand ) {
this.mCommand = `-interpreter-exec console "${this.mCommand}"`;
}
}
}
export class GDBAdapter extends EventEmitter {
private gdbProcess: ChildProcess | null = null;
private gdbProgram: string = '';
private gdbArguments: string[] = [];
private inferiorArguments: string[] = [];
// TODO: Make this a state machine thingy instead of bazillion booleans.
private gdbKilled: boolean = true;
private gdbStarted: boolean = false;
private isRunning: boolean = false;
private token: number = 0;
private standardOutputBuffer: string = ""; /* Buffer GDB machine interface output from STDOUT */
private gdbmiOutput: GDBMIOutput = { miOutOfBandRecordList: [] };
private gdbmiCommandOutput?: (data: GDBMIOutput) => void;
private programOutput: string = '';
private parser: GDBMIParser;
/**
* Event handler on GDB response completed
*/
public onComplete?: () => void;
public exited?: () => void;
constructor() {
super();
this.parser = new GDBMIParser();
// Initialize GDB/MI tree-sitter parser
this.parser.initialize();
}
/**
* Launch GDB child process with default arguments.
*
* @param program The program to debug with GDB.
* @param workingDirectory Working directory for GDB.
* @param programArgs Program arguments
* @param gdbPath Path to GDB executable.
*/
public async launch(
program: string,
workingDirectory: string,
programArgs: string[],
gdbPath: string): Promise<void>
{
return new Promise<void>((resolve, reject) => {
// Check if the program to debug exists
if (!existsSync(program)) {
return reject(new Error(`GDB: The executable to debug does not exist: ${program}`));
}
// Check if GDB/MI tree-sitter parser initialized
if (!this.parser) {
return reject(new Error(`GDB: GDB/MI parser not initialized`));
}
/* launch gdb with the default arguments
* -q quiet mode. Don't print welcome messages
* -nw don't use window interface
* -i select interface
* mi machine interface
*/
this.gdbProgram = gdbPath;
this.gdbArguments = ['-q', '-nw', '-i', 'mi', '--args', program];
logger.info(`GDB: Launching GDB ${this.gdbProgram} ${this.gdbArguments.join(" ")} with working directory ${workingDirectory}`);
if (workingDirectory && !existsSync(workingDirectory)) {
return reject(new Error(`GDB: The working directory (cwd) does not exist: ${workingDirectory}`));
}
this.gdbProcess = spawn(this.gdbProgram, this.gdbArguments, {
cwd: workingDirectory
});
if (!this.gdbProcess) {
return reject(new Error("GDB: Failed to spawn gdb process."));
}
this.inferiorArguments = programArgs;
this.gdbKilled = false;
this.gdbProcess.stdout!.once('data', (data: Buffer) => {
logger.info('GDB: Process started.');
this.gdbStarted = true;
this.isRunning = true;
resolve();
});
this.gdbProcess.stdout!.on('data', (data) => {
let scan = this.standardOutputBuffer.length;
this.standardOutputBuffer += data.toString();
let newstart = 0;
while (newstart < this.standardOutputBuffer.length) {
const start = newstart;
let end = this.standardOutputBuffer.indexOf('\n', scan);
if (end < 0) {
this.standardOutputBuffer = this.standardOutputBuffer.slice(start);
return;
}
newstart = end + 1;
scan = newstart;
if (end === start) {
continue;
}
if (process.platform === 'win32' && this.standardOutputBuffer[end - 1] === '\r') {
--end;
if (end === start) {
continue;
}
}
const response = this.standardOutputBuffer.slice(start, end);
if (response.trim() === "" || response.trim() === "(gdb)") {
continue;
}
// parser requires string to end with newline
this.gdbmiOutput = this.parser.parse(response + "\n");
// console.log(response);
// console.log(this.gdbmiOutput.type);
if (this.gdbmiOutput.miResultRecord) {
// console.log(this.gdbmiOutput.miResultRecord?.cls);
if (this.gdbmiOutput.miResultRecord?.cls === "done") {
this.emit('completed');
} else if (this.gdbmiOutput.miResultRecord?.cls === "running") {
// do not send completed for running as it will break gdbAdapter.test
// this.emit('completed');
} else {
// console.log(this.gdbmiOutput.miResultRecord?.cls);
}
} else if (this.gdbmiOutput.miOutOfBandRecordList.length > 0) {
for (const miOutOfBandRecord of this.gdbmiOutput.miOutOfBandRecordList) {
this.processGDBMIOutOfBandRecord(miOutOfBandRecord);
}
} else {
this.writeToDebugConsole(response);
}
if (this.gdbmiCommandOutput) {
this.gdbmiCommandOutput(this.gdbmiOutput);
this.gdbmiCommandOutput = undefined;
}
}
this.standardOutputBuffer = "";
});
this.gdbProcess.on('error', (err) => {
logger.error('GDB: Error occurred in process:', err);
reject(err);
});
this.gdbProcess.once('exit', (code, signal) => {
const err = `GDB: Process exited with code ${code} and signal ${signal}`;
logger.info(err);
this.gdbKilled = true;
this.isRunning = false;
this.gdbStarted = false;
reject(err);
});
});
}
private writeToDebugConsole(output: string) {
this.programOutput += output;
const debugConsole = vscode.debug.activeDebugConsole;
// Use the appendLine method
debugConsole.appendLine(output);
}
/**
* Processes GDB/MI out-of-band records.
*
* @param outOfBandRecord The out-of-band record to process.
*/
private processGDBMIOutOfBandRecord(outOfBandRecord: GDBMIOutOfBandRecord): void {
if (outOfBandRecord.miAsyncRecord) {
const asyncRecord = outOfBandRecord.miAsyncRecord;
if (asyncRecord.miExecAsyncOutput) {
if (asyncRecord.miExecAsyncOutput?.miAsyncOutput) {
this.processGDBMIAsyncOutput(asyncRecord.miExecAsyncOutput.miAsyncOutput);
} else if (asyncRecord.miStatusAsyncOutput?.miAsyncOutput) {
this.processGDBMIAsyncOutput(asyncRecord.miStatusAsyncOutput.miAsyncOutput);
} else if (asyncRecord.miNotifyAsyncOutput?.miAsyncOutput) {
this.processGDBMIAsyncOutput(asyncRecord.miNotifyAsyncOutput.miAsyncOutput);
} else {
logger.error("GDB: Unknown async record type.");
}
}
} else if (outOfBandRecord.miStreamRecord) {
// Handle stream records (e.g., console, target, or log output)
const streamOutput = outOfBandRecord.miStreamRecord?.value;
switch (outOfBandRecord.miStreamRecord?.type) {
case GDBMIStreamRecordType.consoleStream:
// todo. Add configuration to show/hide console output
break;
case GDBMIStreamRecordType.targetStream:
this.writeToDebugConsole(streamOutput);
break;
case GDBMIStreamRecordType.logStream:
// todo. Add configuration to show/hide log output
break;
default:
logger.error(`GDB: Unknown stream record type: ${outOfBandRecord.miStreamRecord?.type}`);
break;
}
}
}
/**
* Processes GDB/MI async output.
*
* @param asyncOutput The async output to process.
*/
private processGDBMIAsyncOutput(asyncOutput: GDBMIAsyncOutput): void {
const asyncClass = asyncOutput.asyncClass;
if (asyncClass === "stopped") {
const reasonResult = this.getGDBMIResult("reason", asyncOutput.miResult);
const reason = reasonResult ? this.getGDBMIConstantValue(reasonResult) : "";
if (reason === "exited-normally" || reason === "exited") {
this.emit("completed");
this.emit("exit");
} else if (reason === "breakpoint-hit") {
this.emit("completed");
this.emit("stopOnBreakpoint");
}
}
}
/**
* Quit GDB process.
*
* If quit failed kill process.
*/
async quit(): Promise<void> {
if (!this.gdbProcess || this.gdbKilled) {
return;
}
// Stop GDB
// TODO: Add some timeout
await this.sendCommand(CommandFactory.gdbExit(), GDBCommandFlag.nonCriticalResponse);
// Kill the process
if (!this.gdbKilled) {
logger.info("GDB: Killed process.");
this.gdbProcess.kill();
this.gdbKilled = true;
this.isRunning = false;
this.gdbStarted = false;
}
}
public isGDBRunning(): boolean {
return this.gdbStarted && this.isRunning;
}
public getProgramOutput(): string {
return this.programOutput;
}
/**
* Send command to GDB.
*
* Resolves when response completed.
*
* @param command GDB command.
* @param flags Command flags.
* @returns Promise response data as string.
*/
public sendCommand(
command: string,
flags: GDBCommandFlag = GDBCommandFlag.noFlags): Promise<GDBMIOutput>
{
return new Promise<GDBMIOutput>((resolve, reject) => {
if ( !this.isGDBRunning() || !this.gdbProcess ) {
return reject(new Error(`GDB: Not running.`));
}
this.token += 1;
const cmd = new GDBMICommand(flags, `${this.token}${command}`);
// Resolve when GDB command completed.
this.once('completed', () => {
logger.info(`GDB: Finished command "${cmd.mCommand}"`);
this.gdbmiCommandOutput = resolve;
});
// Log command
logger.info(`GDB: Run command "${cmd.mCommand}"`);
// Pass command to GDB
this.gdbProcess.stdin!.write(`${cmd.mCommand}\r\n`);
if (command === '-gdb-exit') {
resolve({ miOutOfBandRecordList: [] });
}
});
}
/**
* Sets up the GDB (GNU Debugger) environment with various configurations before starting the actual debugging process.
*/
async setupGDB(): Promise<void> {
// Set the GDB environment before starting the actual debugging
// Sets the confirm on/off. Off disables confirmation requests. On enables confirmation requests.
await this.sendCommand(CommandFactory.gdbSet("confirm off"), GDBCommandFlag.nonCriticalResponse);
// When displaying a pointer to an object, identify the actual (derived) type of the object rather than the declared type,
// using the virtual function table.
await this.sendCommand(CommandFactory.gdbSet("print object on"), GDBCommandFlag.nonCriticalResponse);
// This indicates that an unrecognized breakpoint location should automatically result in a pending breakpoint being created.
await this.sendCommand(CommandFactory.gdbSet("breakpoint pending on"), GDBCommandFlag.nonCriticalResponse);
// This command sets the width of the screen to num characters wide.
await this.sendCommand(CommandFactory.gdbSet("width 0"), GDBCommandFlag.nonCriticalResponse);
// This command sets the height of the screen to num lines high.
await this.sendCommand(CommandFactory.gdbSet("height 0"), GDBCommandFlag.nonCriticalResponse);
/* Set a limit on how many elements of an array GDB will print.
* If GDB is printing a large array, it stops printing after it has printed
* the number of elements set by the set print elements command. This limit
* also applies to the display of strings. When GDB starts, this limit is
* set to 200. Setting number-of-elements to zero means that the printing
* is unlimited.
*/
// TODO: Make this an option in the final extension
const numberOfElements: number = 0;
await this.sendCommand(CommandFactory.gdbSet(`print elements ${numberOfElements}`), GDBCommandFlag.nonCriticalResponse);
// Set the inferior arguments.
// GDB changes the program arguments if we pass them through --args e.g -override=variableFilter=.*
await this.sendCommand(CommandFactory.gdbSet(`args ${this.inferiorArguments.join(" ")}`), GDBCommandFlag.nonCriticalResponse);
// Insert breakpoints
await this.insertCatchOMCBreakpoint();
}
/**
* Inserts a breakpoint at Catch.omc:1 to handle MMC_THROW()
*/
async insertCatchOMCBreakpoint(): Promise<void> {
await this.sendCommand(CommandFactory.breakInsert("Catch.omc", 1, true), GDBCommandFlag.silentCommand);
}
/**
* Get the result record from the GDBMIOutput.
*
* @param gdbmiOutput GDBMIOutput object.
* @returns The result record if available, otherwise undefined.
*/
public getGDBMIResultRecord(gdbmiOutput: GDBMIOutput) {
if (gdbmiOutput.miResultRecord) {
return gdbmiOutput.miResultRecord;
}
return undefined;
}
/**
* Get the result from the GDBMIResult array.
*
* @param variable The variable to search for.
* @param gdbmiResults Array of GDBMIResult.
* @returns The result if found, otherwise undefined.
*/
public getGDBMIResult(variable: string, gdbmiResults: GDBMIResult[]) {
for (const result of gdbmiResults) {
if (result.variable === variable) {
return result;
}
}
return undefined;
}
/**
* Get the constant value from the GDBMIResult.
*
* @param results Array of GDBMIResult.
* @returns The constant value if found, otherwise undefined.
*/
public getGDBMIConstantValue(gdbmiResult: GDBMIResult): string {
if (gdbmiResult) {
return gdbmiResult.miValue.value;
}
return "";
}
}