This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 646
/
goDebug.ts
1406 lines (1294 loc) · 46.4 KB
/
goDebug.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) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------*/
import * as path from 'path';
import * as os from 'os';
import { DebugProtocol } from 'vscode-debugprotocol';
import { DebugSession, InitializedEvent, TerminatedEvent, ThreadEvent, StoppedEvent, OutputEvent, Thread, StackFrame, Scope, Source, Handles, LoggingDebugSession, Logger, logger } from 'vscode-debugadapter';
import { existsSync, lstatSync } from 'fs';
import { basename, dirname, extname } from 'path';
import { spawn, ChildProcess, execSync, spawnSync, execFile } from 'child_process';
import { Client, RPCConnection } from 'json-rpc2';
import { parseEnvFile, getBinPathWithPreferredGopath, resolveHomeDir, getInferredGopath, getCurrentGoWorkspaceFromGOPATH, envPath, fixDriveCasingInWindows } from '../goPath';
// This enum should stay in sync with https://golang.org/pkg/reflect/#Kind
enum GoReflectKind {
Invalid = 0,
Bool,
Int,
Int8,
Int16,
Int32,
Int64,
Uint,
Uint8,
Uint16,
Uint32,
Uint64,
Uintptr,
Float32,
Float64,
Complex64,
Complex128,
Array,
Chan,
Func,
Interface,
Map,
Ptr,
Slice,
String,
Struct,
UnsafePointer
}
// These types should stay in sync with:
// https://github.com/derekparker/delve/blob/master/service/api/types.go
interface CommandOut {
State: DebuggerState;
}
interface DebuggerState {
exited: boolean;
exitStatus: number;
breakPoint: DebugBreakpoint;
breakPointInfo: {};
currentThread: DebugThread;
currentGoroutine: DebugGoroutine;
}
interface ClearBreakpointOut {
breakpoint: DebugBreakpoint;
}
interface CreateBreakpointOut {
breakpoint: DebugBreakpoint;
}
interface GetVersionOut {
DelveVersion: string;
APIVersion: number;
}
interface DebugBreakpoint {
addr: number;
continue: boolean;
file: string;
functionName?: string;
goroutine: boolean;
id: number;
name: string;
line: number;
stacktrace: number;
variables?: DebugVariable[];
loadArgs?: LoadConfig;
loadLocals?: LoadConfig;
cond?: string;
}
interface LoadConfig {
// FollowPointers requests pointers to be automatically dereferenced.
followPointers: boolean;
// MaxVariableRecurse is how far to recurse when evaluating nested types.
maxVariableRecurse: number;
// MaxStringLen is the maximum number of bytes read from a string
maxStringLen: number;
// MaxArrayValues is the maximum number of elements read from an array, a slice or a map.
maxArrayValues: number;
// MaxStructFields is the maximum number of fields read from a struct, -1 will read all fields.
maxStructFields: number;
}
interface DebugThread {
file: string;
id: number;
line: number;
pc: number;
function?: DebugFunction;
}
interface StacktraceOut {
Locations: DebugLocation[];
}
interface DebugLocation {
pc: number;
file: string;
line: number;
function: DebugFunction;
}
interface DebugFunction {
name: string;
value: number;
type: number;
goType: number;
args: DebugVariable[];
locals: DebugVariable[];
}
interface ListVarsOut {
Variables: DebugVariable[];
}
interface ListFunctionArgsOut {
Args: DebugVariable[];
}
interface EvalOut {
Variable: DebugVariable;
}
enum GoVariableFlags {
VariableEscaped = 1,
VariableShadowed = 2,
VariableConstant = 4,
VariableArgument = 8,
VariableReturnArgument = 16
}
interface DebugVariable {
name: string;
addr: number;
type: string;
realType: string;
kind: GoReflectKind;
flags: GoVariableFlags;
onlyAddr: boolean;
DeclLine: number;
value: string;
len: number;
cap: number;
children: DebugVariable[];
unreadable: string;
fullyQualifiedName: string;
}
interface ListGoroutinesOut {
Goroutines: DebugGoroutine[];
}
interface DebugGoroutine {
id: number;
currentLoc: DebugLocation;
userCurrentLoc: DebugLocation;
goStatementLoc: DebugLocation;
}
interface DebuggerCommand {
name: string;
threadID?: number;
goroutineID?: number;
}
interface RestartOut {
DiscardedBreakpoints: DiscardedBreakpoint[];
}
interface DiscardedBreakpoint {
breakpoint: DebugBreakpoint;
reason: string;
}
// This interface should always match the schema found in `package.json`.
interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
program: string;
stopOnEntry?: boolean;
args?: string[];
showLog?: boolean;
logOutput?: string;
cwd?: string;
env?: { [key: string]: string; };
mode?: string;
remotePath?: string;
port?: number;
host?: string;
buildFlags?: string;
init?: string;
trace?: 'verbose' | 'log' | 'error';
/** Optional path to .env file. */
envFile?: string;
backend?: string;
output?: string;
/** Delve LoadConfig parameters **/
dlvLoadConfig?: LoadConfig;
dlvToolPath: string;
/** Delve Version */
apiVersion: number;
/** Delve maximum stack trace depth */
stackTraceDepth: number;
showGlobalVariables?: boolean;
currentFile: string;
}
process.on('uncaughtException', (err: any) => {
const errMessage = err && (err.stack || err.message);
logger.error(`Unhandled error in debug adapter: ${errMessage}`);
throw err;
});
function logArgsToString(args: any[]): string {
return args.map(arg => {
return typeof arg === 'string' ?
arg :
JSON.stringify(arg);
}).join(' ');
}
function log(...args: any[]) {
logger.warn(logArgsToString(args));
}
function logError(...args: any[]) {
logger.error(logArgsToString(args));
}
function normalizePath(filePath: string) {
if (process.platform === 'win32') {
filePath = path.normalize(filePath);
return fixDriveCasingInWindows(filePath);
}
return filePath;
}
class Delve {
program: string;
remotePath: string;
debugProcess: ChildProcess;
loadConfig: LoadConfig;
connection: Promise<RPCConnection>;
onstdout: (str: string) => void;
onstderr: (str: string) => void;
onclose: (code: number) => void;
noDebug: boolean;
isApiV1: boolean;
dlvEnv: any;
stackTraceDepth: number;
constructor(remotePath: string, port: number, host: string, program: string, launchArgs: LaunchRequestArguments) {
this.program = normalizePath(program);
this.remotePath = remotePath;
this.isApiV1 = false;
if (typeof launchArgs.apiVersion === 'number') {
this.isApiV1 = launchArgs.apiVersion === 1;
} else if (typeof launchArgs['useApiV1'] === 'boolean') {
this.isApiV1 = launchArgs['useApiV1'];
}
this.stackTraceDepth = typeof launchArgs.stackTraceDepth === 'number' ? launchArgs.stackTraceDepth : 50;
let mode = launchArgs.mode;
let dlvCwd = dirname(program);
let isProgramDirectory = false;
let launchArgsEnv = launchArgs.env || {};
this.connection = new Promise((resolve, reject) => {
// Validations on the program
if (!program) {
return reject('The program attribute is missing in the debug configuration in launch.json');
}
try {
let pstats = lstatSync(program);
if (pstats.isDirectory()) {
if (mode === 'exec') {
logError(`The program "${program}" must not be a directory in exec mode`);
return reject('The program attribute must be an executable in exec mode');
}
dlvCwd = program;
isProgramDirectory = true;
} else if (mode !== 'exec' && extname(program) !== '.go') {
logError(`The program "${program}" must be a valid go file in debug mode`);
return reject('The program attribute must be a directory or .go file in debug mode');
}
} catch (e) {
logError(`The program "${program}" does not exist: ${e}`);
return reject('The program attribute must point to valid directory, .go file or executable.');
}
// read env from disk and merge into env variables
let fileEnv = {};
try {
fileEnv = parseEnvFile(launchArgs.envFile);
} catch (e) {
return reject(e);
}
let env = Object.assign({}, process.env, fileEnv, launchArgsEnv);
let dirname = isProgramDirectory ? program : path.dirname(program);
if (!env['GOPATH'] && (mode === 'debug' || mode === 'test')) {
// If no GOPATH is set, then infer it from the file/package path
// Not applicable to exec mode in which case `program` need not point to source code under GOPATH
env['GOPATH'] = getInferredGopath(dirname) || env['GOPATH'];
}
this.dlvEnv = env;
log(`Using GOPATH: ${env['GOPATH']}`);
if (!!launchArgs.noDebug) {
if (mode === 'debug') {
if (isProgramDirectory && launchArgs.currentFile) {
program = launchArgs.currentFile;
isProgramDirectory = false;
}
if (!isProgramDirectory) {
this.noDebug = true;
let runArgs = ['run'];
if (launchArgs.buildFlags) {
runArgs.push(launchArgs.buildFlags);
}
runArgs.push(program);
if (launchArgs.args) {
runArgs.push(...launchArgs.args);
}
this.debugProcess = spawn(getBinPathWithPreferredGopath('go', []), runArgs, { env });
this.debugProcess.stderr.on('data', chunk => {
let str = chunk.toString();
if (this.onstderr) { this.onstderr(str); }
});
this.debugProcess.stdout.on('data', chunk => {
let str = chunk.toString();
if (this.onstdout) { this.onstdout(str); }
});
this.debugProcess.on('close', (code) => {
logError('Process exiting with code: ' + code);
if (this.onclose) { this.onclose(code); }
});
this.debugProcess.on('error', function (err) {
reject(err);
});
resolve();
return;
}
}
}
this.noDebug = false;
let serverRunning = false;
// Get default LoadConfig values according to delve API:
// https://github.com/derekparker/delve/blob/c5c41f635244a22d93771def1c31cf1e0e9a2e63/service/rpc1/server.go#L13
// https://github.com/derekparker/delve/blob/c5c41f635244a22d93771def1c31cf1e0e9a2e63/service/rpc2/server.go#L423
this.loadConfig = launchArgs.dlvLoadConfig || {
followPointers: true,
maxVariableRecurse: 1,
maxStringLen: 64,
maxArrayValues: 64,
maxStructFields: -1
};
if (mode === 'remote') {
this.debugProcess = null;
serverRunning = true; // assume server is running when in remote mode
connectClient(port, host);
return;
}
if (!existsSync(launchArgs.dlvToolPath)) {
log(`Couldn't find dlv at the Go tools path, ${process.env['GOPATH']}${env['GOPATH'] ? ', ' + env['GOPATH'] : ''} or ${envPath}`);
return reject(`Cannot find Delve debugger. Install from https://github.com/derekparker/delve & ensure it is in your Go tools path, "GOPATH/bin" or "PATH".`);
}
let currentGOWorkspace = getCurrentGoWorkspaceFromGOPATH(env['GOPATH'], dirname);
let dlvArgs = [mode || 'debug'];
if (mode === 'exec') {
dlvArgs = dlvArgs.concat([program]);
} else if (currentGOWorkspace) {
dlvArgs = dlvArgs.concat([dirname.substr(currentGOWorkspace.length + 1)]);
}
dlvArgs = dlvArgs.concat(['--headless=true', '--listen=' + host + ':' + port.toString()]);
if (!this.isApiV1) {
dlvArgs.push('--api-version=2');
}
if (launchArgs.showLog) {
dlvArgs = dlvArgs.concat(['--log=' + launchArgs.showLog.toString()]);
}
if (launchArgs.logOutput) {
dlvArgs = dlvArgs.concat(['--log-output=' + launchArgs.logOutput]);
}
if (launchArgs.cwd) {
dlvArgs = dlvArgs.concat(['--wd=' + launchArgs.cwd]);
}
if (launchArgs.buildFlags) {
dlvArgs = dlvArgs.concat(['--build-flags=' + launchArgs.buildFlags]);
}
if (launchArgs.init) {
dlvArgs = dlvArgs.concat(['--init=' + launchArgs.init]);
}
if (launchArgs.backend) {
dlvArgs = dlvArgs.concat(['--backend=' + launchArgs.backend]);
}
if (launchArgs.output && mode === 'debug') {
dlvArgs = dlvArgs.concat(['--output=' + launchArgs.output]);
}
if (launchArgs.args) {
dlvArgs = dlvArgs.concat(['--', ...launchArgs.args]);
}
log(`Current working directory: ${dlvCwd}`);
log(`Running: ${launchArgs.dlvToolPath} ${dlvArgs.join(' ')}`);
this.debugProcess = spawn(launchArgs.dlvToolPath, dlvArgs, {
cwd: dlvCwd,
env,
});
function connectClient(port: number, host: string) {
// Add a slight delay to avoid issues on Linux with
// Delve failing calls made shortly after connection.
setTimeout(() => {
let client = Client.$create(port, host);
client.connectSocket((err, conn) => {
if (err) return reject(err);
return resolve(conn);
});
}, 200);
}
this.debugProcess.stderr.on('data', chunk => {
let str = chunk.toString();
if (this.onstderr) { this.onstderr(str); }
});
this.debugProcess.stdout.on('data', chunk => {
let str = chunk.toString();
if (this.onstdout) { this.onstdout(str); }
if (!serverRunning) {
serverRunning = true;
connectClient(port, host);
}
});
this.debugProcess.on('close', (code) => {
// TODO: Report `dlv` crash to user.
logError('Process exiting with code: ' + code);
if (this.onclose) { this.onclose(code); }
});
this.debugProcess.on('error', function (err) {
reject(err);
});
});
}
call<T>(command: string, args: any[], callback: (err: Error, results: T) => void) {
this.connection.then(conn => {
conn.call('RPCServer.' + command, args, callback);
}, err => {
callback(err, null);
});
}
callPromise<T>(command: string, args: any[]): Thenable<T> {
return new Promise<T>((resolve, reject) => {
this.connection.then(conn => {
conn.call<T>('RPCServer.' + command, args, (err, res) => {
if (err) return reject(err);
resolve(res);
});
}, err => {
reject(err);
});
});
}
close(): Thenable<void> {
log('HaltRequest');
return new Promise(resolve => {
let timeoutToken: NodeJS.Timer;
if (this.debugProcess) {
timeoutToken = setTimeout(() => {
log('Killing debug process manually as we could not halt and detach delve in time');
killTree(this.debugProcess.pid);
resolve();
}, 1000);
}
this.callPromise('Command', [{ name: 'halt' }]).then(() => {
if (timeoutToken) {
clearTimeout(timeoutToken);
}
log('HaltResponse');
if (!this.debugProcess) {
log('RestartRequest');
return this.callPromise('Restart', this.isApiV1 ? [] : [{ position: '', resetArgs: false, newArgs: [] }])
.then(null, err => {
log('RestartResponse');
logError(`Failed to restart - ${(err || '').toString()}`);
})
.then(() => resolve());
} else {
log('DetachRequest');
return this.callPromise('Detach', [this.isApiV1 ? true : { Kill: true }])
.then(null, err => {
log('DetachResponse');
logError(`Killing debug process manually as we failed to detach - ${(err || '').toString()}`);
killTree(this.debugProcess.pid);
})
.then(() => resolve());
}
}, err => {
const errMsg = err ? err.toString() : '';
logError('Failed to halt - ' + errMsg.toString());
if (errMsg.endsWith('has exited with status 0')) {
if (timeoutToken) {
clearTimeout(timeoutToken);
}
return resolve();
}
});
});
}
}
class GoDebugSession extends LoggingDebugSession {
private _variableHandles: Handles<DebugVariable>;
private breakpoints: Map<string, DebugBreakpoint[]>;
private skipStopEventOnce: boolean; // Editing breakpoints requires halting delve, skip sending Stop Event to VS Code in such cases
private goroutines: Set<number>;
private debugState: DebuggerState;
private delve: Delve;
private localPathSeparator: string;
private remotePathSeparator: string;
private stackFrameHandles: Handles<[number, number]>;
private packageInfo = new Map<string, string>();
private launchArgs: LaunchRequestArguments;
private logLevel: Logger.LogLevel = Logger.LogLevel.Error;
private readonly initdone = 'initdone·';
private showGlobalVariables: boolean = true;
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false) {
super('', debuggerLinesStartAt1, isServer);
this._variableHandles = new Handles<DebugVariable>();
this.skipStopEventOnce = false;
this.goroutines = new Set<number>();
this.debugState = null;
this.delve = null;
this.breakpoints = new Map<string, DebugBreakpoint[]>();
this.stackFrameHandles = new Handles<[number, number]>();
}
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
log('InitializeRequest');
// This debug adapter implements the configurationDoneRequest.
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsSetVariable = true;
this.sendResponse(response);
log('InitializeResponse');
}
protected findPathSeperator(path) {
if (/^(\w:[\\/]|\\\\)/.test(path)) return '\\';
return path.includes('/') ? '/' : '\\';
}
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
this.launchArgs = args;
this.logLevel = args.trace === 'verbose' ?
Logger.LogLevel.Verbose :
args.trace === 'log' ? Logger.LogLevel.Log :
Logger.LogLevel.Error;
const logPath = this.logLevel !== Logger.LogLevel.Error ? path.join(os.tmpdir(), 'vscode-go-debug.txt') : undefined;
logger.setup(this.logLevel, logPath);
if (typeof (args.showGlobalVariables) === 'boolean') {
this.showGlobalVariables = args.showGlobalVariables;
}
if (!args.program) {
this.sendErrorResponse(response, 3000, 'Failed to continue: The program attribute is missing in the debug configuration in launch.json');
return;
}
// Launch the Delve debugger on the program
let localPath = args.program;
let remotePath = args.remotePath || '';
let port = args.port || random(2000, 50000);
let host = args.host || '127.0.0.1';
if (remotePath.length > 0) {
this.localPathSeparator = this.findPathSeperator(localPath);
this.remotePathSeparator = this.findPathSeperator(remotePath);
let llist = localPath.split(/\/|\\/).reverse();
let rlist = remotePath.split(/\/|\\/).reverse();
let i = 0;
for (; i < llist.length; i++) if (llist[i] !== rlist[i] || llist[i] === 'src') break;
if (i) {
localPath = llist.reverse().slice(0, -i).join(this.localPathSeparator) + this.localPathSeparator;
remotePath = rlist.reverse().slice(0, -i).join(this.remotePathSeparator) + this.remotePathSeparator;
} else if ((remotePath.endsWith('\\')) || (remotePath.endsWith('/'))) {
remotePath = remotePath.substring(0, remotePath.length - 1);
}
}
this.delve = new Delve(remotePath, port, host, localPath, args);
this.delve.onstdout = (str: string) => {
this.sendEvent(new OutputEvent(str, 'stdout'));
};
this.delve.onstderr = (str: string) => {
this.sendEvent(new OutputEvent(str, 'stderr'));
};
this.delve.onclose = (code) => {
if (code !== 0) {
this.sendErrorResponse(response, 3000, 'Failed to continue: Check the debug console for details.');
}
log('Sending TerminatedEvent as delve is closed');
this.sendEvent(new TerminatedEvent());
};
this.delve.connection.then(() => {
if (!this.delve.noDebug) {
this.delve.call<GetVersionOut>('GetVersion', [], (err, out) => {
if (err) {
logError(err);
return this.sendErrorResponse(response, 2001, 'Failed to get remote server version: "{e}"', { e: err.toString() });
}
let clientVersion = this.delve.isApiV1 ? 1 : 2;
if (out.APIVersion !== clientVersion) {
const errorMessage = `The remote server is running on delve v${out.APIVersion} API and the client is running v${clientVersion} API. Change the version used on the client by using the setting "apiVersion" to true or false as appropriate.`;
logError(errorMessage);
return this.sendErrorResponse(response,
3000,
errorMessage);
}
});
this.sendEvent(new InitializedEvent());
log('InitializeEvent');
}
this.sendResponse(response);
}, err => {
this.sendErrorResponse(response, 3000, 'Failed to continue: "{e}"', { e: err.toString() });
log('ContinueResponse');
});
}
protected disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): void {
log('DisconnectRequest');
this.delve.close().then(() => {
log('DisconnectRequest to parent');
super.disconnectRequest(response, args);
log('DisconnectResponse');
});
}
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
log('ConfigurationDoneRequest');
if (this.launchArgs.stopOnEntry) {
this.sendEvent(new StoppedEvent('breakpoint', 0));
log('StoppedEvent("breakpoint")');
this.sendResponse(response);
} else {
this.continueRequest(<DebugProtocol.ContinueResponse>response);
}
}
protected toDebuggerPath(path: string): string {
if (this.delve.remotePath.length === 0) {
return this.convertClientPathToDebugger(path);
}
return path.replace(this.delve.program, this.delve.remotePath).split(this.localPathSeparator).join(this.remotePathSeparator);
}
protected toLocalPath(pathToConvert: string): string {
if (this.delve.remotePath.length === 0) {
return this.convertDebuggerPathToClient(pathToConvert);
}
// Fix for https://github.com/Microsoft/vscode-go/issues/1178
// When the pathToConvert is under GOROOT, replace the remote GOROOT with local GOROOT
if (!pathToConvert.startsWith(this.delve.remotePath)) {
let index = pathToConvert.indexOf(`${this.remotePathSeparator}src${this.remotePathSeparator}`);
let goroot = process.env['GOROOT'];
if (goroot && index > 0) {
return path.join(goroot, pathToConvert.substr(index));
}
}
return pathToConvert.replace(this.delve.remotePath, this.delve.program).split(this.remotePathSeparator).join(this.localPathSeparator);
}
private updateGoroutinesList(goroutines: DebugGoroutine[]): void {
// Assume we need to stop all the threads we saw before...
let needsToBeStopped = new Set<number>();
this.goroutines.forEach(id => needsToBeStopped.add(id));
for (let goroutine of goroutines) {
// ...but delete from list of threads to stop if we still see it
needsToBeStopped.delete(goroutine.id);
if (!this.goroutines.has(goroutine.id)) {
// Send started event if it's new
this.sendEvent(new ThreadEvent('started', goroutine.id));
}
this.goroutines.add(goroutine.id);
}
// Send existed event if it's no longer there
needsToBeStopped.forEach(id => {
this.sendEvent(new ThreadEvent('exited', id));
this.goroutines.delete(id);
});
}
private setBreakPoints(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): Thenable<void> {
let file = normalizePath(args.source.path);
if (!this.breakpoints.get(file)) {
this.breakpoints.set(file, []);
}
let remoteFile = this.toDebuggerPath(file);
return Promise.all(this.breakpoints.get(file).map(existingBP => {
log('Clearing: ' + existingBP.id);
return this.delve.callPromise('ClearBreakpoint', [this.delve.isApiV1 ? existingBP.id : { Id: existingBP.id }]);
})).then(() => {
log('All cleared');
return Promise.all(args.breakpoints.map(breakpoint => {
if (this.delve.remotePath.length === 0) {
log('Creating on: ' + file + ':' + breakpoint.line);
} else {
log('Creating on: ' + file + ' (' + remoteFile + ') :' + breakpoint.line);
}
let breakpointIn = <DebugBreakpoint>{};
breakpointIn.file = remoteFile;
breakpointIn.line = breakpoint.line;
breakpointIn.loadArgs = this.delve.loadConfig;
breakpointIn.loadLocals = this.delve.loadConfig;
breakpointIn.cond = breakpoint.condition;
return this.delve.callPromise('CreateBreakpoint', [this.delve.isApiV1 ? breakpointIn : { Breakpoint: breakpointIn }]).then(null, err => {
log('Error on CreateBreakpoint: ' + err.toString());
return null;
});
}));
}).then(newBreakpoints => {
if (!this.delve.isApiV1) {
// Unwrap breakpoints from v2 apicall
newBreakpoints = newBreakpoints.map((bp, i) => {
return bp ? bp.Breakpoint : null;
});
}
log('All set:' + JSON.stringify(newBreakpoints));
let breakpoints = newBreakpoints.map((bp, i) => {
if (bp) {
return { verified: true, line: bp.line };
} else {
return { verified: false, line: args.lines[i] };
}
});
this.breakpoints.set(file, newBreakpoints.filter(x => !!x));
return breakpoints;
}).then(breakpoints => {
response.body = { breakpoints };
this.sendResponse(response);
log('SetBreakPointsResponse');
}, err => {
this.sendErrorResponse(response, 2002, 'Failed to set breakpoint: "{e}"', { e: err.toString() });
logError(err);
});
}
protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void {
log('SetBreakPointsRequest');
if (!this.continueRequestRunning) {
this.setBreakPoints(response, args);
} else {
this.skipStopEventOnce = true;
this.delve.callPromise('Command', [{ name: 'halt' }]).then(() => {
return this.setBreakPoints(response, args).then(() => {
return this.continue(true).then(null, err => {
logError(`Failed to continue delve after halting it to set breakpoints: "${err.toString()}"`);
});
});
}, err => {
this.skipStopEventOnce = false;
logError(err);
return this.sendErrorResponse(response, 2008, 'Failed to halt delve before attempting to set breakpoint: "{e}"', { e: err.toString() });
});
}
}
protected threadsRequest(response: DebugProtocol.ThreadsResponse): void {
if (this.continueRequestRunning) {
// Thread request to delve is syncronous and will block if a previous async continue request didn't return
response.body = { threads: [new Thread(1, 'Dummy')] };
return this.sendResponse(response);
}
log('ThreadsRequest');
this.delve.call<DebugGoroutine[] | ListGoroutinesOut>('ListGoroutines', [], (err, out) => {
if (this.debugState && this.debugState.exited) {
// If the program exits very quickly, the initial threadsRequest will complete after it has exited.
// A TerminatedEvent has already been sent. Ignore the err returned in this case.
response.body = { threads: [] };
return this.sendResponse(response);
}
if (err) {
logError('Failed to get threads - ' + err.toString());
return this.sendErrorResponse(response, 2003, 'Unable to display threads: "{e}"', { e: err.toString() });
}
const goroutines = this.delve.isApiV1 ? <DebugGoroutine[]>out : (<ListGoroutinesOut>out).Goroutines;
log('goroutines', goroutines);
this.updateGoroutinesList(goroutines);
let threads = goroutines.map(goroutine =>
new Thread(
goroutine.id,
goroutine.userCurrentLoc.function ? goroutine.userCurrentLoc.function.name : (goroutine.userCurrentLoc.file + '@' + goroutine.userCurrentLoc.line)
)
);
response.body = { threads };
this.sendResponse(response);
log('ThreadsResponse', threads);
});
}
protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void {
log('StackTraceRequest');
// delve does not support frame paging, so we ask for a large depth
const goroutineId = args.threadId;
let stackTraceIn = { id: goroutineId, depth: this.delve.stackTraceDepth };
if (!this.delve.isApiV1) {
Object.assign(stackTraceIn, { full: false, cfg: this.delve.loadConfig });
}
this.delve.call<DebugLocation[] | StacktraceOut>(this.delve.isApiV1 ? 'StacktraceGoroutine' : 'Stacktrace', [stackTraceIn], (err, out) => {
if (err) {
logError('Failed to produce stack trace!');
return this.sendErrorResponse(response, 2004, 'Unable to produce stack trace: "{e}"', { e: err.toString() });
}
const locations = this.delve.isApiV1 ? <DebugLocation[]>out : (<StacktraceOut>out).Locations;
log('locations', locations);
let stackFrames = locations.map((location, frameId) => {
const uniqueStackFrameId = this.stackFrameHandles.create([goroutineId, frameId]);
return new StackFrame(
uniqueStackFrameId,
location.function ? location.function.name : '<unknown>',
location.file === '<autogenerated>' ? null : new Source(
basename(location.file),
this.toLocalPath(location.file)
),
location.line,
0
);
});
if (args.startFrame > 0) {
stackFrames = stackFrames.slice(args.startFrame);
}
if (args.levels > 0) {
stackFrames = stackFrames.slice(0, args.levels);
}
response.body = { stackFrames, totalFrames: locations.length };
this.sendResponse(response);
log('StackTraceResponse');
});
}
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void {
log('ScopesRequest');
const [goroutineId, frameId] = this.stackFrameHandles.get(args.frameId);
const listLocalVarsIn = { goroutineID: goroutineId, frame: frameId };
this.delve.call<DebugVariable[] | ListVarsOut>('ListLocalVars', this.delve.isApiV1 ? [listLocalVarsIn] : [{ scope: listLocalVarsIn, cfg: this.delve.loadConfig }], (err, out) => {
if (err) {
logError('Failed to list local variables - ' + err.toString());
return this.sendErrorResponse(response, 2005, 'Unable to list locals: "{e}"', { e: err.toString() });
}
const locals = this.delve.isApiV1 ? <DebugVariable[]>out : (<ListVarsOut>out).Variables;
log('locals', locals);
this.addFullyQualifiedName(locals);
let listLocalFunctionArgsIn = { goroutineID: goroutineId, frame: frameId };
this.delve.call<DebugVariable[] | ListFunctionArgsOut>('ListFunctionArgs', this.delve.isApiV1 ? [listLocalFunctionArgsIn] : [{ scope: listLocalFunctionArgsIn, cfg: this.delve.loadConfig }], (err, outArgs) => {
if (err) {
logError('Failed to list function args - ' + err.toString());
return this.sendErrorResponse(response, 2006, 'Unable to list args: "{e}"', { e: err.toString() });
}
const args = this.delve.isApiV1 ? <DebugVariable[]>outArgs : (<ListFunctionArgsOut>outArgs).Args;
log('functionArgs', args);
this.addFullyQualifiedName(args);
let vars = args.concat(locals);
// annotate shadowed variables in parentheses
const shadowedVars = new Map<string, Array<number>>();
for (let i = 0; i < vars.length; ++i) {
if ((vars[i].flags & GoVariableFlags.VariableShadowed) === 0) {
continue;
}
const varName = vars[i].name;
if (!shadowedVars.has(varName)) {
const indices = new Array<number>();
indices.push(i);
shadowedVars.set(varName, indices);
} else {
shadowedVars.get(varName).push(i);
}
}
for (const svIndices of shadowedVars.values()) {
// sort by declared line number in descending order
svIndices.sort((lhs: number, rhs: number) => {
return vars[rhs].DeclLine - vars[lhs].DeclLine;
});
// enclose in parentheses, one pair per scope
for (let scope = 0; scope < svIndices.length; ++scope) {
const svIndex = svIndices[scope];
// start at -1 so scope of 0 has one pair of parens
for (let count = -1; count < scope; ++count) {
vars[svIndex].name = `(${vars[svIndex].name})`;
}
}
}
let scopes = new Array<Scope>();
let localVariables = {
name: 'Local',
addr: 0,
type: '',
realType: '',
kind: 0,
flags: 0,
onlyAddr: false,
DeclLine: 0,
value: '',
len: 0,
cap: 0,
children: vars,
unreadable: '',
fullyQualifiedName: '',
};
scopes.push(new Scope('Local', this._variableHandles.create(localVariables), false));
response.body = { scopes };
if (!this.showGlobalVariables) {
this.sendResponse(response);
log('ScopesResponse');
return;
}
this.getPackageInfo(this.debugState).then(packageName => {
if (!packageName) {
this.sendResponse(response);
log('ScopesResponse');
return;
}
const filter = `^${packageName}\\.`;
this.delve.call<DebugVariable[] | ListVarsOut>('ListPackageVars', this.delve.isApiV1 ? [filter] : [{ filter, cfg: this.delve.loadConfig }], (err, out) => {
if (err) {
logError('Failed to list global vars - ' + err.toString());
return this.sendErrorResponse(response, 2007, 'Unable to list global vars: "{e}"', { e: err.toString() });
}
const globals = this.delve.isApiV1 ? <DebugVariable[]>out : (<ListVarsOut>out).Variables;
let initdoneIndex = -1;
for (let i = 0; i < globals.length; i++) {
globals[i].name = globals[i].name.substr(packageName.length + 1);
if (initdoneIndex === -1 && globals[i].name === this.initdone) {
initdoneIndex = i;
}
}
if (initdoneIndex > -1) {
globals.splice(initdoneIndex, 1);
}
log('global vars', globals);
const globalVariables = {
name: 'Global',
addr: 0,
type: '',
realType: '',
kind: 0,
flags: 0,
onlyAddr: false,
DeclLine: 0,
value: '',
len: 0,
cap: 0,
children: globals,
unreadable: '',