-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDebugAdapter.ts
More file actions
1168 lines (946 loc) · 40.6 KB
/
Copy pathDebugAdapter.ts
File metadata and controls
1168 lines (946 loc) · 40.6 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
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
import {
DebugSession, OutputEvent, TerminatedEvent, Source, Scope, Handles,
StoppedEvent, InitializedEvent, BreakpointEvent, Breakpoint, ContinuedEvent
} from 'vscode-debugadapter';
import * as vsDebugAdapter from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import { GDB } from './gdb/gdb';
import * as IGDB from './gdb/IGDB';
import { ResourceManager } from './ResourceManager';
import { File } from '../lib/node-utility/File';
import { EventEmitter } from 'events';
import * as NodePath from 'path';
import * as vscode from 'vscode';
import { GlobalEvent } from './GlobalEvent';
import * as util from 'util';
import { getAdapter } from './gdb/GdbAdapters';
class Subject {
private _event: EventEmitter;
constructor() {
this._event = new EventEmitter();
}
notify() {
this._event.emit('done');
}
async wait(): Promise<void> {
return new Promise((resolve) => {
this._event.once('done', () => {
resolve();
});
});
}
}
export interface LaunchArguments extends DebugProtocol.LaunchRequestArguments, IGDB.ConnectOption {
svdFile?: string;
runToMain?: boolean;
}
interface RegisterField {
name: string;
bitsOffset: number;
bitsWidth: number;
}
interface PeriphRegister {
name: string;
baseAddress?: string;
bytes: number;
fields?: RegisterField[];
}
interface Peripheral {
name: string;
baseAddress: string;
registers: PeriphRegister[];
}
interface SvdFilter {
file: File;
regexp: RegExp;
}
enum ScopeType {
SCOPE_GLOBAL = 1, // ID must > 0
SCOPE_LOCAL,
SCOPE_FUNC_PARAMS,
SCOPE_REGISTER,
SCOPE_OPTION_BYTES,
SCOPE_PERIPHERAL
}
// override Variable
class Variable extends vsDebugAdapter.Variable {
vPath?: string;
}
export class DebugAdapter extends DebugSession implements vscode.TextDocumentContentProvider {
// must bigger than Scope ID
private static readonly HANLER_START: number = 10;
private static readonly HANLER_NULL: number = -1;
private readonly ThreadID = 1;
private gdb: GDB;
private cwd: File;
private configDoneEmitter: Subject = new Subject();
private isConnected: boolean = false;
private stringAsArray: boolean;
private useSyncMode: boolean = false;
private globalVars: string[] = [];
private vHandles: Handles<Variable[]>;
private rootVariables: Map<ScopeType, Variable[]> = new Map();
private periphReferanceMap: Map<number, string> = new Map();
private peripherals: Peripheral[] = [];
private periphRegValueMap: Map<string, number> = new Map();
// current frame information
private frameChanged = false;
private funcArguments: IGDB.Variable[] = [];
private bpMap: Map<string, IGDB.Breakpoint[]> = new Map();
private preLoadBPMap: Map<string, IGDB.Breakpoint[]> = new Map();
private timeUsed: number | undefined;
// disassembly document
disassemblyScheme: string;
assemblyMatcher = {
'normal': /^(0x[0-9a-f]+)\s+(<[^>]+>:)\s+(?:0x[0-9a-f]+)\s+(.*?)\s*$/i,
'simple': /^(0x[0-9a-f]+):\s+(?:0x[0-9a-f]+)\s+(.*?)\s*$/i
};
disassemblyBuf: Map<string, string[]>;
assemblyTextEvent: vscode.EventEmitter<vscode.Uri>;
onDidChange: vscode.Event<vscode.Uri>;
constructor() {
super();
this.vHandles = new Handles(DebugAdapter.HANLER_START);
this.cwd = <File>ResourceManager.getInstance().getWorkspaceDir();
this.gdb = new GDB(ResourceManager.getInstance().isVerboseMode());
this.stringAsArray = ResourceManager.getInstance().isParseString2Array();
this.disassemblyScheme = ResourceManager.getInstance().getAppName();
this.assemblyTextEvent = new vscode.EventEmitter();
this.onDidChange = this.assemblyTextEvent.event;
this.disassemblyBuf = new Map();
this.setDebuggerColumnsStartAt1(false);
this.setDebuggerLinesStartAt1(false);
this.gdb.on('log', (logData) => {
switch (logData.type) {
case 'warning':
this.warn(logData.msg);
break;
case 'error':
this.error(logData.msg);
break;
default:
this.log(logData.msg);
break;
}
});
}
private log(line: string) {
this.sendEvent(new OutputEvent(`${line}\r\n`, 'stdout'));
}
private warn(line: string) {
this.sendEvent(new OutputEvent(`${line}\r\n`));
}
private error(line: string) {
this.sendEvent(new OutputEvent(`${line}\r\n`, 'stderr'));
}
//----- variables
private cacheChild(children: IGDB.VariableChildren): number {
return this.vHandles.create(children.map((item) => {
const vTemp = new Variable(item.name, '', DebugAdapter.HANLER_NULL);
switch (item.type) {
case 'array':
vTemp.value = `array [${(<any[]>item.value).length}]`;
vTemp.variablesReference = this.cacheChild(<IGDB.VariableChildren>item.value);
break;
case 'obj':
vTemp.value = 'struct {...}';
vTemp.variablesReference = this.cacheChild(<IGDB.VariableChildren>item.value);
break;
default:
vTemp.value = <string>item.value;
break;
}
return vTemp;
}));
}
private vClearAll() {
this.vHandles.reset();
}
private vToVariable(_var: IGDB.Variable): Variable {
const result: DebugProtocol.Variable = new Variable(_var.name, '', DebugAdapter.HANLER_NULL);
switch (_var.type) {
case 'array':
result.value = `array [${(<any[]>_var.value).length}]`;
result.variablesReference = this.cacheChild(<IGDB.VariableChildren>_var.value);
break;
case 'obj':
result.value = 'struct {...}';
result.variablesReference = this.cacheChild(<IGDB.VariableChildren>_var.value);
break;
case 'string':
{
const value: string = <string>_var.value;
result.value = `"${value}"`;
result.type = _var.type;
// conver a string to an array
if (this.stringAsArray) {
const cArr = Array.from(value).map((_char, index) => {
return <IGDB.Variable>{
name: index.toString(),
type: 'integer',
value: _char.charCodeAt(0).toString()
};
});
// add '\0' suffix
cArr.push({
name: cArr.length.toString(),
type: 'integer',
value: '0'
});
result.variablesReference = this.cacheChild(cArr);
}
}
break;
default:
result.value = <string>_var.value;
result.type = _var.type;
break;
}
return result;
}
private vGetChildren(ref: number): Variable[] {
return this.vHandles.get(ref, []);
}
private vGetRoot(name: string): Variable | undefined {
for (const rootList of this.rootVariables.values()) {
const index = rootList.findIndex((v) => { return v.name === name; });
if (index !== -1) {
return rootList[index];
}
}
return undefined;
}
//------ source
private createSource(_path: string): Source {
if (NodePath.isAbsolute(_path)) {
return new Source(NodePath.basename(_path), _path);
} else {
const absPath = NodePath.join(this.cwd.path, _path);
return new Source(NodePath.basename(absPath), absPath);
}
}
private toRelative(_path: string): string {
return _path;
}
private async loadBreakPoints() {
for (const keyValue of this.preLoadBPMap) {
const fPath = keyValue[0];
const bpList = keyValue[1];
const validList: IGDB.Breakpoint[] = [];
for (const bp of bpList) {
const bkpt = await this.gdb.addBreakPoint(bp);
if (bkpt) {
validList.push(bkpt);
/* this.sendEvent(new BreakpointEvent('changed',
new Breakpoint(true, bp.line, 0, this.createSource(fPath)))); */
}
}
this.bpMap.set(fPath, validList);
}
this.preLoadBPMap.clear();
}
//------ svd
private loadSvd(fPath: string) {
const svdFile = new File(fPath);
if (!svdFile.IsFile()) {
throw new Error(`not found file: ${svdFile.path}`);
}
try {
this.peripherals = <Peripheral[]>JSON.parse(svdFile.Read());
} catch (e) {
throw new Error(`incorrect json file format: ${(<Error>e).message}`);
}
try {
// check data format
this.peripherals.forEach((periph, index) => {
if (typeof periph.name !== 'string') {
throw new Error(`'name' must be a string, peripheral index: ${index}`);
}
if (typeof periph.baseAddress !== 'string') {
throw new Error(`'baseAddress' must be a string, at peripheral: ${periph.name}`);
}
if (!Array.isArray(periph.registers)) {
throw new Error(`'registers' must be a array, at peripheral: ${periph.name}`);
}
let baseAddress = parseInt(periph.baseAddress);
let offset = 0;
periph.registers.forEach((reg, rIndex) => {
if (typeof reg.name !== 'string') {
throw new Error(`'name' must be a string, at peripheral: ${periph.name}, register index: ${rIndex}`);
}
if (typeof reg.bytes !== 'number') {
throw new Error(`'bytes' must be a number, at peripheral: ${periph.name}, register: ${reg.name}`);
}
if (typeof reg.baseAddress !== 'string' && typeof reg.baseAddress !== 'undefined') {
throw new Error(`'baseAddress' must be string or undefined, at peripheral: ${periph.name}, register: ${reg.name}`);
}
if (!Array.isArray(reg.fields) && typeof reg.fields !== 'undefined') {
throw new Error(`'fields' must be array or undefined, at peripheral: ${periph.name}, register: ${reg.name}`);
}
if (reg.fields) {
reg.fields.forEach((field) => {
if (typeof field.name !== 'string') {
throw new Error(`'fields' format error, at peripheral: ${periph.name}, register: ${reg.name}`);
}
if (typeof field.bitsOffset !== 'number') {
throw new Error(`'fields' format error, at peripheral: ${periph.name}, register: ${reg.name}`);
}
if (typeof field.bitsWidth !== 'number') {
throw new Error(`'fields' format error, at peripheral: ${periph.name}, register: ${reg.name}`);
}
});
}
// fill register address
if (reg.baseAddress) {
baseAddress = parseInt(reg.baseAddress);
offset = 1;
} else {
reg.baseAddress = `0x${(baseAddress + offset).toString(16)}`;
offset++;
}
});
});
} catch (error) {
this.peripherals = [];
throw error;
}
}
private getSVDFilter(): SvdFilter[] {
return ResourceManager.getInstance()
.getSvdDir().GetList([/\.svd\.json$/], File.EMPTY_FILTER)
.map((file) => {
const cpuName = file.name.split('.')[0];
return {
file: file,
regexp: new RegExp(`^${cpuName}`, 'i')
};
});
}
private periphToVariables(): Variable[] {
// clear ptr map, value cache
this.periphReferanceMap.clear();
this.periphRegValueMap.clear();
return this.peripherals.map((periph) => {
const vPeriph = new Variable(`${periph.name}`,
`address ${periph.baseAddress}`, DebugAdapter.HANLER_NULL);
vPeriph.vPath = periph.name;
vPeriph.variablesReference = this.vHandles.create(periph.registers.map((register) => {
const vReg = new Variable(register.name, 'null', DebugAdapter.HANLER_NULL);
vReg.vPath = `${vPeriph.vPath}.${register.name}`;
const children = register.fields?.map((field) => {
const vField = new Variable(field.name, 'null', DebugAdapter.HANLER_NULL);
vField.vPath = `${vReg.vPath}.${field.name}`;
return vField;
});
if (children) {
vReg.variablesReference = this.vHandles.create(children);
// add ptr to mapper
this.periphReferanceMap.set(vReg.variablesReference, vReg.vPath);
}
return vReg;
}));
// add ptr to mapper
this.periphReferanceMap.set(vPeriph.variablesReference, vPeriph.vPath);
return vPeriph;
});
}
private isPeriphRef(ref: number): boolean {
return this.periphReferanceMap.has(ref);
}
private getPeriphByPath(vPath: string): Peripheral | PeriphRegister | RegisterField | undefined {
const nameList = vPath.split('.');
// search peripheral
if (nameList.length > 0) {
const pIndex = this.peripherals.findIndex((periph) => { return periph.name === nameList[0]; });
if (pIndex !== -1) {
const periph = this.peripherals[pIndex];
// search register
if (nameList.length > 1) {
const regIndex = periph.registers.findIndex((reg) => { return reg.name === nameList[1]; });
if (regIndex !== -1) {
const register = periph.registers[regIndex];
// search fields
if (nameList.length > 2) {
if (register.fields) {
const fIndex = register.fields.findIndex((field) => { return field.name === nameList[2]; });
if (fIndex !== -1) {
return register.fields[fIndex];
}
}
} else {
return register;
}
}
} else {
return periph;
}
}
}
}
private async readPeriphRegisters(ref: number): Promise<Variable[]> {
const resultList: Variable[] = [];
const reqList: Variable[] = this.vHandles.get(ref, []);
for (const reqVar of reqList) {
if (reqVar.vPath) {
const nameList = reqVar.vPath.split('.');
// is registers
if (nameList.length === 2) {
const register = <PeriphRegister>this.getPeriphByPath(reqVar.vPath);
if (register) {
const baseAddress = parseInt(<string>register.baseAddress);
const mem = await this.gdb.readMemory(baseAddress, register.bytes);
// check address, length
if (mem.addr === baseAddress &&
mem.buf.length === register.bytes) {
// set value
if (mem.buf.length === 1) {
reqVar.value = `0x${mem.buf[0].toString(16)}`;
// cache
this.periphRegValueMap.set(reqVar.vPath, mem.buf[0]);
} else {
const hexList = mem.buf.map((num) => { return `0x${num.toString(16)}`; });
reqVar.value = `[${hexList.join(',')}]`;
}
} else {
// clear cache
this.periphRegValueMap.delete(reqVar.vPath);
}
}
resultList.push(reqVar);
}
// is fields
else if (nameList.length === 3) {
const regValue = this.periphRegValueMap.get(`${nameList[0]}.${nameList[1]}`);
const field = <RegisterField>this.getPeriphByPath(reqVar.vPath);
if (field && typeof regValue !== 'undefined') {
let mask = 0; // bit mask
for (let i = 0; i < field.bitsWidth; i++) {
mask = (mask << 1) | 1;
}
const fieldValue = (regValue >> field.bitsOffset) & mask;
reqVar.value = `0x${fieldValue.toString(16)}`;
resultList.push(reqVar);
}
}
}
}
return resultList;
}
//----- disassembly
private async disassembleRange(start: string, length: string): Promise<string[] | undefined> {
const lines = await this.gdb.readDisassembly({
start: start,
length: length
});
if (lines) {
return lines;
}
}
private splitInstructionLine(line: string): { instruction: string, comment: string } | undefined {
const wsIndex = line.search(/\s/);
if (wsIndex !== -1) {
const instName = line.substring(0, wsIndex);
const nInstIndex = line.indexOf(instName, wsIndex);
if (nInstIndex !== -1) {
return {
instruction: line.substring(0, nInstIndex).trim(),
comment: line.substring(nInstIndex).trim()
};
}
}
}
provideTextDocumentContent(uri: vscode.Uri, token: vscode.CancellationToken): vscode.ProviderResult<string> {
const lines = this.disassemblyBuf.get(uri.toString());
if (lines) {
const resList: { addr: string, txt: string, inst: string, com: string }[] = [];
let maxTextLen: number = 0;
let maxInstLen: number = 0;
lines.forEach((line) => {
/**
* 0x0080aef <Main+4>: 0x20DF PUSH A PUSH A
*/
let mList = this.assemblyMatcher['normal'].exec(line);
if (mList && mList.length > 3) {
const pair = this.splitInstructionLine(mList[3]);
if (pair) {
// add line
maxInstLen = pair.instruction.length > maxInstLen ? pair.instruction.length : maxInstLen;
maxTextLen = mList[2].length > maxTextLen ? mList[2].length : maxTextLen;
resList.push({ addr: mList[1], txt: mList[2], inst: pair.instruction, com: pair.comment });
return;
}
// add line
maxTextLen = mList[2].length > maxTextLen ? mList[2].length : maxTextLen;
resList.push({ addr: mList[1], txt: mList[2], inst: mList[3], com: '' });
return;
}
/**
* 0x0080aef: 0x20DF PUSH A PUSH A
*/
mList = this.assemblyMatcher['simple'].exec(line);
if (mList && mList.length > 2) {
const pair = this.splitInstructionLine(mList[2]);
if (pair) {
maxInstLen = pair.instruction.length > maxInstLen ? pair.instruction.length : maxInstLen;
resList.push({ addr: mList[1], txt: '', inst: pair.instruction, com: pair.comment });
return;
}
// add line
resList.push({ addr: mList[1], txt: '', inst: mList[2], com: '' });
return;
}
// add line
resList.push({ addr: line, txt: '', inst: '', com: '' });
return;
});
// convert line
return resList.map((info) => {
return `${info.addr}\t${info.txt.padEnd(maxTextLen)}\t${info.inst.padEnd(maxInstLen)}\t; ${info.com}`;
}).join('\r\n');
}
}
//------ option bytes
//command gdi mcuoption -show
private async readOptionBytes(): Promise<IGDB.Variable[] | undefined> {
// sdcc not support read option bytes
if (this.gdb.getAdapter().type === 'stm8-sdcc') {
return undefined;
}
const result = await this.gdb.sendCustomCommand('gdi mcuoption -show');
if (result.resultType === 'done') {
const vList: IGDB.Variable[] = [];
result.lines.forEach((line) => {
const index = line.indexOf(':');
if (index !== -1) {
vList.push({
name: line.substr(0, index),
type: 'orignal',
value: line.substr(index + 1)
});
}
});
return vList;
}
}
//=================================================
/**
* The 'initialize' request is the first request called by the frontend
* to interrogate the features the debug adapter provides.
*/
protected async initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments) {
// build and return the capabilities of this debug adapter:
response.body = response.body || {};
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsEvaluateForHovers = true;
response.body.supportsConditionalBreakpoints = true;
response.body.supportsRestartRequest = true;
//response.body.supportsTerminateRequest = true;
this.sendResponse(response);
this.sendEvent(new InitializedEvent());
}
protected async terminateRequest(response: DebugProtocol.TerminateResponse, args: DebugProtocol.TerminateArguments, request?: DebugProtocol.Request) {
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments) {
this.log('[SEND]: kill gdb.exe');
this.gdb.kill().then(() => {
this.log('\tdone');
this.log('[END]');
this.isConnected = false;
GlobalEvent.emit('debug.terminal');
this.sendResponse(response);
});
}
/**
* Called at the end of the configuration sequence.
* Indicates that all breakpoints etc. have been sent to the DA and that the 'launch' can start.
*/
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
super.configurationDoneRequest(response, args);
// notify the launchRequest that configuration has finished
setTimeout(() => {
this.configDoneEmitter.notify();
}, 100);
}
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchArguments) {
// wait until configuration has finished (and configurationDoneRequest has been called)
await this.configDoneEmitter.wait();
// init
this.log(`==================== Initialize ====================\r\n`);
const adpTag: IGDB.GdbServerType = args.serverType || 'st7';
// st7 not support async mode
this.useSyncMode = adpTag === 'st7';
// get gdb adapter by tag
const adapter = getAdapter(adpTag);
if (adapter === undefined) {
this.error(`Not found gdb adapter: '${adpTag}'`);
this.sendEvent(new TerminatedEvent()); // launch failed, exit
return;
}
this.gdb.initAdapter(adapter);
// launch gdb.exe process
const errMsg = await this.gdb.launch([
`--quiet`,
`--cd=${this.cwd.path}`,
`--directory=${this.cwd.path}`
]);
if (errMsg) {
this.error(errMsg);
this.sendEvent(new TerminatedEvent()); // launch failed, exit
return;
}
// load svd
try {
if (args.svdFile) {
const absPath: string = NodePath.isAbsolute(args.svdFile)
? args.svdFile : NodePath.normalize(`${this.cwd.path}${File.sep}${args.svdFile}`);
this.log(`Load SVD: ${args.svdFile}`);
this.loadSvd(absPath);
} else {
const filters = this.getSVDFilter();
const index = filters.findIndex((item) => { return item.regexp.test(args.cpu); });
if (index !== -1) {
this.log(`Load SVD: ${filters[index].file.name}`);
this.loadSvd(filters[index].file.path);
}
}
} catch (e) {
this.error(`Load SVD failed !, msg: ${(<Error>e).message}`);
}
// connect to gdb
this.log(`\r\n==================== Connect ====================\r\n`);
this.isConnected = await this.gdb.connect(args);
if (!this.isConnected) {
this.sendEvent(new TerminatedEvent()); // launch failed, exit
return;
}
// other custom commands
const extraCommands: string[] = [];
if (args.runToMain !== false) {
extraCommands.push('break main');
}
this.log(`\r\n==================== Launch ====================\r\n`);
const launched = await this.gdb.startDebug(args.executable, extraCommands);
if (!launched) {
this.sendEvent(new TerminatedEvent()); // launch failed, exit
return;
}
this.sendResponse(response); // launch done !
await this.loadBreakPoints();
const bkpt = await this.gdb.continue(this.useSyncMode);
if (bkpt) {
this.sendEvent(new StoppedEvent(args.runToMain !== false ? 'entry' : 'breakpoint', this.ThreadID));
}
}
protected async restartRequest(response: DebugProtocol.RestartResponse, args: DebugProtocol.RestartArguments) {
if (this.gdb.isStopped()) {
this.gdb.sendCommand('reset', 'null').then((result) => {
if (result.resultType === 'done') {
this.sendEvent(new ContinuedEvent(this.ThreadID, true));
this.gdb.continue(this.useSyncMode).then(() => {
this.sendEvent(new StoppedEvent('breakpoint', this.ThreadID));
});
this.sendResponse(response);
}
});
}
}
protected async setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments) {
const bpList: DebugProtocol.SourceBreakpoint[] = args.breakpoints || [];
response.body = {
breakpoints: []
};
const file: string | undefined = args.source.path || args.source.name;
if (file === undefined) {
this.sendResponse(response);
this.warn(`set breakpoint on 'undefine' path`);
return;
}
// connected device
if (this.isConnected) {
// clear all
if (this.bpMap.has(file)) {
const cList = (<IGDB.Breakpoint[]>this.bpMap.get(file)).map((bkpt) => {
return <number>bkpt.number;
});
await this.gdb.removeBreakpoints(cList);
}
const validList: IGDB.Breakpoint[] = [];
for (const bp of bpList) {
const bkpt = await this.gdb.addBreakPoint({
file: this.toRelative(file),
line: bp.line,
condition: bp.condition
});
if (bkpt) {
response.body.breakpoints.push({
line: bkpt.line,
id: bkpt.number,
source: this.createSource(file),
verified: true
});
validList.push(bkpt);
}
}
// update
this.bpMap.set(file, validList);
} else {
this.preLoadBPMap.set(file, bpList.map((bpItem) => {
response.body.breakpoints.push({
line: bpItem.line,
source: this.createSource(file),
verified: true
});
return <IGDB.Breakpoint>{
line: bpItem.line,
condition: bpItem.condition,
file: this.toRelative(file)
};
}));
}
this.sendResponse(response);
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
response.body = {
threads: [{
id: this.ThreadID,
name: 'MainThread'
}]
};
this.sendResponse(response);
}
protected async stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments) {
const startFrame = typeof args.startFrame === 'number' ? args.startFrame : 0;
const maxLevels = typeof args.levels === 'number' ? args.levels : 100;
const endFrame = startFrame + maxLevels;
// clear frame data
this.frameChanged = true;
this.funcArguments = [];
// clear all variables
this.vClearAll();
const stack = await this.gdb.getStack(startFrame, endFrame);
// init current frame function arguments
if (stack.length > 0) {
this.funcArguments = stack[0].paramsList || [];
}
// send Elapsed time event
if (this.timeUsed !== undefined && stack.length > 0) {
if (stack[0].line !== null && stack[0].file) {
GlobalEvent.emit('debug.onStopped', {
file: this.createSource(stack[0].file).path,
line: stack[0].line - 1, // to zero base
useTimeMs: this.timeUsed
});
}
this.timeUsed = undefined;
}
const stackFrames: DebugProtocol.StackFrame[] = [];
for (let index = 0; index < stack.length; index++) {
const frame = stack[index];
if (util.isNullOrUndefined(frame.file) && frame.address) {
const prevInstructionOffset = 10;
const instructionLen = 30;
let line: number | undefined;
let fileName: string | undefined;
let asmFileUri: string | undefined;
let cAddress: number = parseInt(frame.address);
const realStartAddr = cAddress >= prevInstructionOffset ? (cAddress - prevInstructionOffset) : 0;
const addrStart: string = `0x${realStartAddr.toString(16)}`;
const asmLines = await this.disassembleRange(addrStart, instructionLen.toString());
if (asmLines) {
const fileName = `${frame.address}.stm8asm`;
asmFileUri = `${this.disassemblyScheme}:${encodeURIComponent(fileName)}`;
const bkptReg = new RegExp(`${frame.address}`);
line = asmLines.findIndex((line) => { return bkptReg.test(line); }) + 1;
this.disassemblyBuf.set(asmFileUri, asmLines);
this.assemblyTextEvent.fire(vscode.Uri.parse(asmFileUri));
}
stackFrames.push(<DebugProtocol.StackFrame>{
id: frame.level,
name: `${frame.address} ${frame.function}`,
line: line || 0,
source: asmFileUri ? new Source(<string>fileName, asmFileUri) : undefined,
column: 0,
});
} else {
const frameName: string = frame.address ?
(`${frame.address} ${frame.function}`) : frame.function;
stackFrames.push(<DebugProtocol.StackFrame>{
id: frame.level,
name: frameName,
line: frame.line || 0,
source: frame.file ? this.createSource(frame.file) : undefined,
column: 0,
});
}
}
response.body = {
stackFrames: stackFrames,
totalFrames: stack.length
};
this.sendResponse(response);
}
protected async scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments) {
// storage global variables
const vDefines = await this.gdb.getGlobalVariables();
if (vDefines) {
this.globalVars = vDefines.map((item) => { return item.name; });
}
response.body = {
scopes: [
new Scope("Globals", ScopeType.SCOPE_GLOBAL, true),
new Scope("Locals", ScopeType.SCOPE_LOCAL, false),
new Scope("Arguments", ScopeType.SCOPE_FUNC_PARAMS, false),
new Scope("Registers", ScopeType.SCOPE_REGISTER, true),
new Scope('Option Bytes', ScopeType.SCOPE_OPTION_BYTES, true),
new Scope('Peripherals', ScopeType.SCOPE_PERIPHERAL, true)
]
};
this.sendResponse(response);
}
protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments) {