-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathGDBDebugSession.ts
2292 lines (2141 loc) · 83.3 KB
/
GDBDebugSession.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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************************
* Copyright (c) 2018 QNX Software Systems and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*********************************************************************/
import * as os from 'os';
import * as path from 'path';
import * as fs from 'fs';
import {
DebugSession,
Handles,
InitializedEvent,
Logger,
logger,
LoggingDebugSession,
OutputEvent,
Response,
Scope,
Source,
StackFrame,
TerminatedEvent,
} from '@vscode/debugadapter';
import { DebugProtocol } from '@vscode/debugprotocol';
import { GDBBackend } from './GDBBackend';
import * as mi from './mi';
import {
sendDataReadMemoryBytes,
sendDataDisassemble,
sendDataWriteMemoryBytes,
} from './mi/data';
import { StoppedEvent } from './stoppedEvent';
import { VarObjType } from './varManager';
import { createEnvValues, getGdbCwd } from './util';
export interface RequestArguments extends DebugProtocol.LaunchRequestArguments {
gdb?: string;
gdbArguments?: string[];
gdbAsync?: boolean;
gdbNonStop?: boolean;
// defaults to the environment of the process of the adapter
environment?: Record<string, string | null>;
program: string;
// defaults to dirname of the program, if present or the cwd of the process of the adapter
cwd?: string;
verbose?: boolean;
logFile?: string;
openGdbConsole?: boolean;
initCommands?: string[];
hardwareBreakpoint?: boolean;
}
export interface LaunchRequestArguments extends RequestArguments {
arguments?: string;
}
export interface AttachRequestArguments extends RequestArguments {
processId: string;
}
export interface FrameReference {
threadId: number;
frameId: number;
}
export interface FrameVariableReference {
type: 'frame';
frameHandle: number;
}
export interface ObjectVariableReference {
type: 'object';
frameHandle: number;
varobjName: string;
}
export interface RegisterVariableReference {
type: 'registers';
frameHandle: number;
regname?: string;
}
export type VariableReference =
| FrameVariableReference
| ObjectVariableReference
| RegisterVariableReference;
export interface MemoryRequestArguments {
address: string;
length: number;
offset?: number;
}
/**
* Response for our custom 'cdt-gdb-adapter/Memory' request.
*/
export interface MemoryContents {
/* Hex-encoded string of bytes. */
data: string;
address: string;
}
export interface MemoryResponse extends Response {
body: MemoryContents;
}
export interface CDTDisassembleArguments
extends DebugProtocol.DisassembleArguments {
/**
* Memory reference to the end location containing the instructions to disassemble. When this
* optional setting is provided, the minimum number of lines needed to get to the endMemoryReference
* is used.
*/
endMemoryReference: string;
}
class ThreadWithStatus implements DebugProtocol.Thread {
id: number;
name: string;
running: boolean;
constructor(id: number, name: string, running: boolean) {
this.id = id;
this.name = name;
this.running = running;
}
}
// Allow a single number for ignore count or the form '> [number]'
const ignoreCountRegex = /\s|>/g;
const arrayRegex = /.*\[[\d]+\].*/;
const arrayChildRegex = /[\d]+/;
const numberRegex = /^-?\d+(?:\.\d*)?$/; // match only numbers (integers and floats)
const cNumberTypeRegex = /\b(?:char|short|int|long|float|double)$/; // match C number types
const cBoolRegex = /\bbool$/; // match boolean
export function hexToBase64(hex: string): string {
// The buffer will ignore incomplete bytes (unpaired digits), so we need to catch that early
if (hex.length % 2 !== 0) {
throw new Error('Received memory with incomplete bytes.');
}
const base64 = Buffer.from(hex, 'hex').toString('base64');
// If the hex input includes characters that are not hex digits, Buffer.from() will return an empty buffer, and the base64 string will be empty.
if (base64.length === 0 && hex.length !== 0) {
throw new Error('Received ill-formed hex input: ' + hex);
}
return base64;
}
export function base64ToHex(base64: string): string {
const buffer = Buffer.from(base64, 'base64');
// The caller likely passed in a value that left dangling bits that couldn't be assigned to a full byte and so
// were ignored by Buffer. We can't be sure what the client thought they wanted to do with those extra bits, so fail here.
if (buffer.length === 0 || !buffer.toString('base64').startsWith(base64)) {
throw new Error('Received ill-formed base64 input: ' + base64);
}
return buffer.toString('hex');
}
export class GDBDebugSession extends LoggingDebugSession {
/**
* Initial (aka default) configuration for launch/attach request
* typically supplied with the --config command line argument.
*/
protected static defaultRequestArguments?: any;
/**
* Frozen configuration for launch/attach request
* typically supplied with the --config-frozen command line argument.
*/
protected static frozenRequestArguments?: { request?: string };
protected gdb: GDBBackend = this.createBackend();
protected isAttach = false;
// isRunning === true means there are no threads stopped.
protected isRunning = false;
protected supportsRunInTerminalRequest = false;
protected supportsGdbConsole = false;
/* A reference to the logger to be used by subclasses */
protected logger: Logger.Logger;
protected frameHandles = new Handles<FrameReference>();
protected variableHandles = new Handles<VariableReference>();
protected functionBreakpoints: string[] = [];
protected logPointMessages: { [key: string]: string } = {};
protected threads: ThreadWithStatus[] = [];
// promise that resolves once the target stops so breakpoints can be inserted
protected waitPaused?: (value?: void | PromiseLike<void>) => void;
// the thread id that we were waiting for
protected waitPausedThreadId = 0;
// set to true if the target was interrupted where inteneded, and should
// therefore be resumed after breakpoints are inserted.
protected waitPausedNeeded = false;
protected isInitialized = false;
constructor() {
super();
this.logger = logger;
}
/**
* Main entry point
*/
public static run(debugSession: typeof GDBDebugSession) {
GDBDebugSession.processArgv(process.argv.slice(2));
DebugSession.run(debugSession);
}
/**
* Parse an optional config file which is a JSON string of launch/attach request arguments.
* The config can be a response file by starting with an @.
*/
public static processArgv(args: string[]) {
args.forEach(function (val, _index, _array) {
const configMatch = /^--config(-frozen)?=(.*)$/.exec(val);
if (configMatch) {
let configJson;
const configStr = configMatch[2];
if (configStr.startsWith('@')) {
const configFile = configStr.slice(1);
configJson = JSON.parse(
fs.readFileSync(configFile).toString('utf8')
);
} else {
configJson = JSON.parse(configStr);
}
if (configMatch[1]) {
GDBDebugSession.frozenRequestArguments = configJson;
} else {
GDBDebugSession.defaultRequestArguments = configJson;
}
}
});
}
/**
* Apply the initial and frozen launch/attach request arguments.
* @param request the default request type to return if request type is not frozen
* @param args the arguments from the user to apply initial and frozen arguments to.
* @returns resolved request type and the resolved arguments
*/
protected applyRequestArguments(
request: 'launch' | 'attach',
args: LaunchRequestArguments | AttachRequestArguments
): ['launch' | 'attach', LaunchRequestArguments | AttachRequestArguments] {
const frozenRequest = GDBDebugSession.frozenRequestArguments?.request;
if (frozenRequest === 'launch' || frozenRequest === 'attach') {
request = frozenRequest;
}
return [
request,
{
...GDBDebugSession.defaultRequestArguments,
...args,
...GDBDebugSession.frozenRequestArguments,
},
];
}
protected createBackend(): GDBBackend {
return new GDBBackend();
}
/**
* Handle requests not defined in the debug adapter protocol.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected customRequest(
command: string,
response: DebugProtocol.Response,
args: any
): void {
if (command === 'cdt-gdb-adapter/Memory') {
this.memoryRequest(response as MemoryResponse, args);
// This custom request exists to allow tests in this repository to run arbitrary commands
// Use at your own risk!
} else if (command === 'cdt-gdb-tests/executeCommand') {
const consoleOutput: string[] = [];
const consoleOutputListener = (line: string) =>
consoleOutput.push(line);
// Listens the console output for test and controls purpose during the
// test command execution. Boundry of the console output not guaranteed.
this.gdb.addListener('consoleStreamOutput', consoleOutputListener);
this.gdb
.sendCommand(args.command)
.then((result) => {
response.body = {
status: 'Ok',
result,
console: consoleOutput,
};
this.sendResponse(response);
})
.catch((e) => {
const message =
e instanceof Error
? e.message
: `Encountered a problem executing ${args.command}`;
this.sendErrorResponse(response, 1, message);
})
.finally(() => {
this.gdb.removeListener(
'consoleStreamOutput',
consoleOutputListener
);
});
} else {
return super.customRequest(command, response, args);
}
}
protected initializeRequest(
response: DebugProtocol.InitializeResponse,
args: DebugProtocol.InitializeRequestArguments
): void {
this.supportsRunInTerminalRequest =
args.supportsRunInTerminalRequest === true;
this.supportsGdbConsole =
os.platform() === 'linux' && this.supportsRunInTerminalRequest;
response.body = response.body || {};
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsSetVariable = true;
response.body.supportsConditionalBreakpoints = true;
response.body.supportsHitConditionalBreakpoints = true;
response.body.supportsLogPoints = true;
response.body.supportsFunctionBreakpoints = true;
// response.body.supportsSetExpression = true;
response.body.supportsDisassembleRequest = true;
response.body.supportsReadMemoryRequest = true;
response.body.supportsWriteMemoryRequest = true;
response.body.supportsSteppingGranularity = true;
this.sendResponse(response);
}
protected async attachOrLaunchRequest(
response: DebugProtocol.Response,
request: 'launch' | 'attach',
args: LaunchRequestArguments | AttachRequestArguments
) {
logger.setup(
args.verbose ? Logger.LogLevel.Verbose : Logger.LogLevel.Warn,
args.logFile || false
);
this.gdb.on('consoleStreamOutput', (output, category) => {
this.sendEvent(new OutputEvent(output, category));
});
this.gdb.on('execAsync', (resultClass, resultData) =>
this.handleGDBAsync(resultClass, resultData)
);
this.gdb.on('notifyAsync', (resultClass, resultData) =>
this.handleGDBNotify(resultClass, resultData)
);
await this.spawn(args);
if (!args.program) {
this.sendErrorResponse(
response,
1,
'The program must be specified in the request arguments'
);
return;
}
await this.gdb.sendFileExecAndSymbols(args.program);
await this.gdb.sendEnablePrettyPrint();
if (request === 'attach') {
this.isAttach = true;
const attachArgs = args as AttachRequestArguments;
await mi.sendTargetAttachRequest(this.gdb, {
pid: attachArgs.processId,
});
this.sendEvent(
new OutputEvent(`attached to process ${attachArgs.processId}`)
);
}
await this.gdb.sendCommands(args.initCommands);
if (request === 'launch') {
const launchArgs = args as LaunchRequestArguments;
if (launchArgs.arguments) {
await mi.sendExecArguments(this.gdb, {
arguments: launchArgs.arguments,
});
}
}
this.sendEvent(new InitializedEvent());
this.sendResponse(response);
this.isInitialized = true;
}
protected async attachRequest(
response: DebugProtocol.AttachResponse,
args: AttachRequestArguments
): Promise<void> {
try {
const [request, resolvedArgs] = this.applyRequestArguments(
'attach',
args
);
await this.attachOrLaunchRequest(response, request, resolvedArgs);
} catch (err) {
this.sendErrorResponse(
response,
1,
err instanceof Error ? err.message : String(err)
);
}
}
protected async launchRequest(
response: DebugProtocol.LaunchResponse,
args: LaunchRequestArguments
): Promise<void> {
try {
const [request, resolvedArgs] = this.applyRequestArguments(
'launch',
args
);
await this.attachOrLaunchRequest(response, request, resolvedArgs);
} catch (err) {
this.sendErrorResponse(
response,
1,
err instanceof Error ? err.message : String(err)
);
}
}
protected async spawn(
args: LaunchRequestArguments | AttachRequestArguments
) {
if (args.openGdbConsole) {
if (!this.supportsGdbConsole) {
logger.warn(
'cdt-gdb-adapter: openGdbConsole is not supported on this platform'
);
} else if (
!(await this.gdb.supportsNewUi(
args.gdb,
getGdbCwd(args),
args.environment
))
) {
logger.warn(
`cdt-gdb-adapter: new-ui command not detected (${
args.gdb || 'gdb'
})`
);
} else {
logger.verbose(
'cdt-gdb-adapter: spawning gdb console in client terminal'
);
return this.spawnInClientTerminal(args);
}
}
return this.gdb.spawn(args);
}
protected async spawnInClientTerminal(
args:
| DebugProtocol.LaunchRequestArguments
| DebugProtocol.AttachRequestArguments
) {
const requestArgs = args as
| LaunchRequestArguments
| AttachRequestArguments;
const gdbEnvironment = requestArgs.environment
? createEnvValues(process.env, requestArgs.environment)
: process.env;
return this.gdb.spawnInClientTerminal(requestArgs, async (command) => {
const response = await new Promise<DebugProtocol.Response>(
(resolve) =>
this.sendRequest(
'runInTerminal',
{
kind: 'integrated',
cwd: getGdbCwd(requestArgs),
env: gdbEnvironment,
args: command,
} as DebugProtocol.RunInTerminalRequestArguments,
5000,
resolve
)
);
if (!response.success) {
const message = `could not start the terminal on the client: ${response.message}`;
logger.error(message);
throw new Error(message);
}
});
}
protected async setBreakPointsRequest(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments
): Promise<void> {
this.waitPausedNeeded = this.isRunning;
if (this.waitPausedNeeded) {
// Need to pause first
const waitPromise = new Promise<void>((resolve) => {
this.waitPaused = resolve;
});
if (this.gdb.isNonStopMode()) {
const threadInfo = await mi.sendThreadInfoRequest(this.gdb, {});
this.waitPausedThreadId = parseInt(
threadInfo['current-thread-id'],
10
);
this.gdb.pause(this.waitPausedThreadId);
} else {
this.gdb.pause();
}
await waitPromise;
}
try {
// Need to get the list of current breakpoints in the file and then make sure
// that we end up with the requested set of breakpoints for that file
// deleting ones not requested and inserting new ones.
const result = await mi.sendBreakList(this.gdb);
const file = args.source.path as string;
const gdbOriginalLocationPrefix = await mi.sourceBreakpointLocation(
this.gdb,
file
);
const gdbbps = result.BreakpointTable.body.filter((gdbbp) => {
// Ignore "children" breakpoint of <MULTIPLE> entries
if (gdbbp.number.includes('.')) {
return false;
}
// Ignore other files
if (!gdbbp['original-location']) {
return false;
}
if (
!gdbbp['original-location'].startsWith(
gdbOriginalLocationPrefix
)
) {
return false;
}
// Ignore function breakpoints
return this.functionBreakpoints.indexOf(gdbbp.number) === -1;
});
const { resolved, deletes } = this.resolveBreakpoints(
args.breakpoints || [],
gdbbps,
(vsbp, gdbbp) => {
// Always invalidate hit conditions as they have a one-way mapping to gdb ignore and temporary
if (vsbp.hitCondition) {
return false;
}
// Ensure we can compare undefined and empty strings
const vsbpCond = vsbp.condition || undefined;
const gdbbpCond = gdbbp.cond || undefined;
// Check with original-location so that relocated breakpoints are properly matched
const gdbOriginalLocation = `${gdbOriginalLocationPrefix}${vsbp.line}`;
return !!(
gdbbp['original-location'] === gdbOriginalLocation &&
vsbpCond === gdbbpCond
);
}
);
// Delete before insert to avoid breakpoint clashes in gdb
if (deletes.length > 0) {
await mi.sendBreakDelete(this.gdb, { breakpoints: deletes });
deletes.forEach(
(breakpoint) => delete this.logPointMessages[breakpoint]
);
}
// Reset logPoints
this.logPointMessages = {};
// Set up logpoint messages and return a formatted breakpoint for the response body
const createState = (
vsbp: DebugProtocol.SourceBreakpoint,
gdbbp: mi.MIBreakpointInfo
): DebugProtocol.Breakpoint => {
if (vsbp.logMessage) {
this.logPointMessages[gdbbp.number] = vsbp.logMessage;
}
let line = 0;
if (gdbbp.line) {
line = parseInt(gdbbp.line, 10);
} else if (vsbp.line) {
line = vsbp.line;
}
return {
id: parseInt(gdbbp.number, 10),
line,
verified: true,
};
};
const actual: DebugProtocol.Breakpoint[] = [];
for (const bp of resolved) {
if (bp.gdbbp) {
actual.push(createState(bp.vsbp, bp.gdbbp));
continue;
}
let temporary = false;
let ignoreCount: number | undefined;
const vsbp = bp.vsbp;
if (vsbp.hitCondition !== undefined) {
ignoreCount = parseInt(
vsbp.hitCondition.replace(ignoreCountRegex, ''),
10
);
if (isNaN(ignoreCount)) {
this.sendEvent(
new OutputEvent(
`Unable to decode expression: ${vsbp.hitCondition}`
)
);
continue;
}
// Allow hit condition continuously above the count
temporary = !vsbp.hitCondition.startsWith('>');
if (temporary) {
// The expression is not 'greater than', decrease ignoreCount to match
ignoreCount--;
}
}
try {
const line = vsbp.line.toString();
const options = await this.gdb.getBreakpointOptions(
{
locationType: 'source',
source: file,
line,
},
{
condition: vsbp.condition,
temporary,
ignoreCount,
hardware: this.gdb.isUseHWBreakpoint(),
}
);
const gdbbp = await mi.sendSourceBreakpointInsert(
this.gdb,
file,
line,
options
);
actual.push(createState(vsbp, gdbbp.bkpt));
} catch (err) {
actual.push({
verified: false,
message:
err instanceof Error ? err.message : String(err),
} as DebugProtocol.Breakpoint);
}
}
response.body = {
breakpoints: actual,
};
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(
response,
1,
err instanceof Error ? err.message : String(err)
);
}
if (this.waitPausedNeeded) {
if (this.gdb.isNonStopMode()) {
mi.sendExecContinue(this.gdb, this.waitPausedThreadId);
} else {
mi.sendExecContinue(this.gdb);
}
}
}
protected async setFunctionBreakPointsRequest(
response: DebugProtocol.SetFunctionBreakpointsResponse,
args: DebugProtocol.SetFunctionBreakpointsArguments
) {
this.waitPausedNeeded = this.isRunning;
if (this.waitPausedNeeded) {
// Need to pause first
const waitPromise = new Promise<void>((resolve) => {
this.waitPaused = resolve;
});
if (this.gdb.isNonStopMode()) {
const threadInfo = await mi.sendThreadInfoRequest(this.gdb, {});
this.waitPausedThreadId = parseInt(
threadInfo['current-thread-id'],
10
);
this.gdb.pause(this.waitPausedThreadId);
} else {
this.gdb.pause();
}
await waitPromise;
}
try {
const result = await mi.sendBreakList(this.gdb);
const gdbbps = result.BreakpointTable.body.filter((gdbbp) => {
// Only function breakpoints
return this.functionBreakpoints.indexOf(gdbbp.number) > -1;
});
const { resolved, deletes } = this.resolveBreakpoints(
args.breakpoints,
gdbbps,
(vsbp, gdbbp) => {
// Always invalidate hit conditions as they have a one-way mapping to gdb ignore and temporary
if (vsbp.hitCondition) {
return false;
}
// Ensure we can compare undefined and empty strings
const vsbpCond = vsbp.condition || undefined;
const gdbbpCond = gdbbp.cond || undefined;
const originalLocation = mi.functionBreakpointLocation(
this.gdb,
vsbp.name
);
return !!(
gdbbp['original-location'] === originalLocation &&
vsbpCond === gdbbpCond
);
}
);
// Delete before insert to avoid breakpoint clashes in gdb
if (deletes.length > 0) {
await mi.sendBreakDelete(this.gdb, { breakpoints: deletes });
this.functionBreakpoints = this.functionBreakpoints.filter(
(fnbp) => deletes.indexOf(fnbp) === -1
);
}
const createActual = (
breakpoint: mi.MIBreakpointInfo
): DebugProtocol.Breakpoint => ({
id: parseInt(breakpoint.number, 10),
verified: true,
});
const actual: DebugProtocol.Breakpoint[] = [];
// const actual = existing.map((bp) => createActual(bp.gdbbp));
for (const bp of resolved) {
if (bp.gdbbp) {
actual.push(createActual(bp.gdbbp));
continue;
}
try {
const options = await this.gdb.getBreakpointOptions(
{
locationType: 'function',
fn: bp.vsbp.name,
},
{
hardware: this.gdb.isUseHWBreakpoint(),
}
);
const gdbbp = await mi.sendFunctionBreakpointInsert(
this.gdb,
bp.vsbp.name,
options
);
this.functionBreakpoints.push(gdbbp.bkpt.number);
actual.push(createActual(gdbbp.bkpt));
} catch (err) {
actual.push({
verified: false,
message:
err instanceof Error ? err.message : String(err),
} as DebugProtocol.Breakpoint);
}
}
response.body = {
breakpoints: actual,
};
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(
response,
1,
err instanceof Error ? err.message : String(err)
);
}
if (this.waitPausedNeeded) {
if (this.gdb.isNonStopMode()) {
mi.sendExecContinue(this.gdb, this.waitPausedThreadId);
} else {
mi.sendExecContinue(this.gdb);
}
}
}
/**
* Resolved which VS breakpoints needs to be installed, which
* GDB breakpoints need to be deleted and which VS breakpoints
* are already installed with which matching GDB breakpoint.
* @param vsbps VS DAP breakpoints
* @param gdbbps GDB breakpoints
* @param matchFn matcher to compare VS and GDB breakpoints
* @returns resolved -> array maintaining order of vsbps that identifies whether
* VS breakpoint has a cooresponding GDB breakpoint (gdbbp field set) or needs to be
* inserted (gdbbp field empty)
* deletes -> GDB bps ids that should be deleted because they don't match vsbps
*/
protected resolveBreakpoints<T>(
vsbps: T[],
gdbbps: mi.MIBreakpointInfo[],
matchFn: (vsbp: T, gdbbp: mi.MIBreakpointInfo) => boolean
): {
resolved: Array<{ vsbp: T; gdbbp?: mi.MIBreakpointInfo }>;
deletes: string[];
} {
const resolved: Array<{ vsbp: T; gdbbp?: mi.MIBreakpointInfo }> =
vsbps.map((vsbp) => {
return {
vsbp,
gdbbp: gdbbps.find((gdbbp) => matchFn(vsbp, gdbbp)),
};
});
const deletes = gdbbps
.filter((gdbbp) => {
return !vsbps.find((vsbp) => matchFn(vsbp, gdbbp));
})
.map((gdbbp) => gdbbp.number);
return { resolved, deletes };
}
protected async configurationDoneRequest(
response: DebugProtocol.ConfigurationDoneResponse,
_args: DebugProtocol.ConfigurationDoneArguments
): Promise<void> {
try {
this.sendEvent(
new OutputEvent(
'\n' +
'In the Debug Console view you can interact directly with GDB.\n' +
'To display the value of an expression, type that expression which can reference\n' +
"variables that are in scope. For example type '2 + 3' or the name of a variable.\n" +
"Arbitrary commands can be sent to GDB by prefixing the input with a '>',\n" +
"for example type '>show version' or '>help'.\n" +
'\n',
'console'
)
);
if (this.isAttach) {
await mi.sendExecContinue(this.gdb);
} else {
await mi.sendExecRun(this.gdb);
}
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(
response,
100,
err instanceof Error ? err.message : String(err)
);
}
}
protected convertThread(thread: mi.MIThreadInfo) {
let name = thread.name || thread.id;
if (thread.details) {
name += ` (${thread.details})`;
}
const running = thread.state === 'running';
return new ThreadWithStatus(parseInt(thread.id, 10), name, running);
}
protected async threadsRequest(
response: DebugProtocol.ThreadsResponse
): Promise<void> {
try {
if (!this.isRunning) {
const result = await mi.sendThreadInfoRequest(this.gdb, {});
this.threads = result.threads
.map((thread) => this.convertThread(thread))
.sort((a, b) => a.id - b.id);
}
response.body = {
threads: this.threads,
};
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(
response,
1,
err instanceof Error ? err.message : String(err)
);
}
}
protected async stackTraceRequest(
response: DebugProtocol.StackTraceResponse,
args: DebugProtocol.StackTraceArguments
): Promise<void> {
try {
const threadId = args.threadId;
const depthResult = await mi.sendStackInfoDepth(this.gdb, {
maxDepth: 100,
threadId,
});
const depth = parseInt(depthResult.depth, 10);
const levels = args.levels
? args.levels > depth
? depth
: args.levels
: depth;
const lowFrame = args.startFrame || 0;
const highFrame = lowFrame + levels - 1;
const listResult = await mi.sendStackListFramesRequest(this.gdb, {
lowFrame,
highFrame,
threadId,
});
const stack = listResult.stack.map((frame) => {
let source;
if (frame.fullname) {
source = new Source(
path.basename(frame.file || frame.fullname),
frame.fullname
);
}
let line;
if (frame.line) {
line = parseInt(frame.line, 10);
}
const frameHandle = this.frameHandles.create({
threadId: args.threadId,
frameId: parseInt(frame.level, 10),
});
const name = frame.func || frame.fullname || '';
const sf = new StackFrame(
frameHandle,
name,
source,
line
) as DebugProtocol.StackFrame;
sf.instructionPointerReference = frame.addr;
return sf;
});
response.body = {
stackFrames: stack,
totalFrames: depth,
};
this.sendResponse(response);
} catch (err) {
this.sendErrorResponse(
response,
1,
err instanceof Error ? err.message : String(err)
);
}
}