-
Notifications
You must be signed in to change notification settings - Fork 752
/
goDebug.ts
2755 lines (2544 loc) · 90.5 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 in the project root for license information.
*--------------------------------------------------------*/
import { ChildProcess, execFile, spawn, spawnSync } from 'child_process';
import { EventEmitter } from 'events';
import * as fs from 'fs';
import { existsSync, lstatSync } from 'fs';
import * as glob from 'glob';
import { Client, RPCConnection } from 'json-rpc2';
import * as os from 'os';
import * as path from 'path';
import * as util from 'util';
import {
DebugSession,
ErrorDestination,
Handles,
InitializedEvent,
logger,
Logger,
LoggingDebugSession,
OutputEvent,
Scope,
Source,
StackFrame,
StoppedEvent,
TerminatedEvent,
Thread
} from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import { parseEnvFiles } from '../utils/envUtils';
import {
correctBinname,
envPath,
expandFilePathInOutput,
fixDriveCasingInWindows,
getBinPathWithPreferredGopathGoroot,
getCurrentGoWorkspaceFromGOPATH,
getInferredGopath,
} from '../utils/pathUtils';
import { killProcessTree } from '../utils/processUtils';
const fsAccess = util.promisify(fs.access);
const fsUnlink = util.promisify(fs.unlink);
// 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/go-delve/delve/blob/master/service/api/types.go
interface CommandOut {
State: DebuggerState;
}
interface DebuggerState {
exited: boolean;
exitStatus: number;
currentThread: DebugThread;
currentGoroutine: DebugGoroutine;
Running: boolean;
Threads: DebugThread[];
NextInProgress: boolean;
}
export interface PackageBuildInfo {
ImportPath: string;
DirectoryPath: string;
Files: string[];
}
export interface ListPackagesBuildInfoOut {
List: PackageBuildInfo[];
}
export interface ListSourcesOut {
Sources: string[];
}
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;
goroutineID: number;
breakPoint: DebugBreakpoint;
breakPointInfo: {};
function?: DebugFunction;
ReturnValues: DebugVariable[];
}
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[];
optimized: boolean;
}
interface ListVarsOut {
Variables: DebugVariable[];
}
interface ListFunctionArgsOut {
Args: DebugVariable[];
}
interface EvalOut {
Variable: DebugVariable;
}
enum GoVariableFlags {
VariableEscaped = 1,
VariableShadowed = 2,
VariableConstant = 4,
VariableArgument = 8,
VariableReturnArgument = 16,
VariableFakeAddress = 32
}
interface DebugVariable {
// DebugVariable corresponds to api.Variable in Delve API.
// https://github.com/go-delve/delve/blob/328cf87808822693dc611591519689dcd42696a3/service/api/types.go#L239-L284
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;
base: number;
}
interface ListGoroutinesOut {
Goroutines: DebugGoroutine[];
}
interface DebugGoroutine {
id: number;
currentLoc: DebugLocation;
userCurrentLoc: DebugLocation;
goStatementLoc: DebugLocation;
}
interface DebuggerCommand {
name: string;
threadID?: number;
goroutineID?: number;
}
interface ListBreakpointsOut {
Breakpoints: DebugBreakpoint[];
}
interface RestartOut {
DiscardedBreakpoints: DiscardedBreakpoint[];
}
interface DiscardedBreakpoint {
breakpoint: DebugBreakpoint;
reason: string;
}
// Unrecovered panic and fatal throw breakpoint IDs taken from delve:
// https://github.com/go-delve/delve/blob/f90134eb4db1c423e24fddfbc6eff41b288e6297/pkg/proc/breakpoints.go#L11-L21
// UnrecoveredPanic is the name given to the unrecovered panic breakpoint.
const unrecoveredPanicID = -1;
// FatalThrow is the name given to the breakpoint triggered when the target
// process dies because of a fatal runtime error.
const fatalThrowID = -2;
// This interface should always match the schema found in `package.json`.
interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
request: 'launch';
[key: string]: any;
program: string;
stopOnEntry?: boolean;
dlvFlags?: string[];
args?: string[];
showLog?: boolean;
logOutput?: string;
cwd?: string;
env?: { [key: string]: string };
mode?: 'auto' | 'debug' | 'remote' | 'test' | 'exec';
remotePath?: string;
port?: number;
host?: string;
buildFlags?: string;
init?: string;
trace?: 'verbose' | 'log' | 'error';
backend?: string;
output?: string;
substitutePath?: {from: string, to: string}[];
/** Delve LoadConfig parameters */
dlvLoadConfig?: LoadConfig;
dlvToolPath: string;
/** Delve Version */
apiVersion: number;
/** Delve maximum stack trace depth */
stackTraceDepth: number;
showGlobalVariables?: boolean;
packagePathToGoModPathMap: { [key: string]: string };
/** Optional path to .env file. */
// TODO: deprecate .env file processing from DA.
// We expect the extension processes .env files
// and send the information to DA using the 'env' property.
envFile?: string | string[];
}
interface AttachRequestArguments extends DebugProtocol.AttachRequestArguments {
request: 'attach';
processId?: number;
stopOnEntry?: boolean;
dlvFlags?: string[];
showLog?: boolean;
logOutput?: string;
cwd?: string;
mode?: 'local' | 'remote';
remotePath?: string;
port?: number;
host?: string;
trace?: 'verbose' | 'log' | 'error';
backend?: string;
substitutePath?: {from: string, to: string}[];
/** Delve LoadConfig parameters */
dlvLoadConfig?: LoadConfig;
dlvToolPath: string;
/** Delve Version */
apiVersion: number;
/** Delve maximum stack trace depth */
stackTraceDepth: number;
showGlobalVariables?: boolean;
}
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 findPathSeparator(filePath: string) {
return filePath.includes('/') ? '/' : '\\';
}
// Comparing two different file paths while ignoring any different path separators.
function compareFilePathIgnoreSeparator(firstFilePath: string, secondFilePath: string): boolean {
const firstSeparator = findPathSeparator(firstFilePath);
const secondSeparator = findPathSeparator(secondFilePath);
if (firstSeparator === secondSeparator) {
return firstFilePath === secondFilePath;
}
return firstFilePath === secondFilePath.split(secondSeparator).join(firstSeparator);
}
export function escapeGoModPath(filePath: string) {
return filePath.replace(/[A-Z]/g, (match: string) => `!${match.toLocaleLowerCase()}`);
}
function normalizePath(filePath: string) {
if (process.platform === 'win32') {
const pathSeparator = findPathSeparator(filePath);
filePath = path.normalize(filePath);
// Normalize will replace everything with backslash on Windows.
filePath = filePath.replace(/\\/g, pathSeparator);
return fixDriveCasingInWindows(filePath);
}
return filePath;
}
// normalizeSeparators will prepare the filepath for comparison in mapping from
// local to debugger path and from debugger path to local path. All separators are
// replaced with '/', and the drive name is capitalized for windows paths.
// Exported for testing
export function normalizeSeparators(filePath: string): string {
// Although the current machine may not be running windows,
// the remote machine may be and we need to fix the drive
// casing.
// This is a workaround for issue in https://github.com/Microsoft/vscode/issues/9448#issuecomment-244804026
if (filePath.indexOf(':') === 1) {
filePath = filePath.substr(0, 1).toUpperCase() + filePath.substr(1);
}
return filePath.replace(/\/|\\/g, '/');
}
function getBaseName(filePath: string) {
return filePath.includes('/') ? path.basename(filePath) : path.win32.basename(filePath);
}
export class Delve {
public program: string;
public remotePath: string;
public loadConfig: LoadConfig;
public connection: Promise<RPCConnection|null>; // null if connection isn't necessary (e.g. noDebug mode)
public onstdout: (str: string) => void;
public onstderr: (str: string) => void;
public onclose: (code: number) => void;
public noDebug: boolean;
public isApiV1: boolean;
public dlvEnv: any;
public stackTraceDepth: number;
public isRemoteDebugging: boolean;
public goroot: string;
public delveConnectionClosed = false;
private localDebugeePath: string | undefined;
private debugProcess: ChildProcess;
private request: 'attach' | 'launch';
constructor(launchArgs: LaunchRequestArguments | AttachRequestArguments, program: string) {
this.request = launchArgs.request;
this.program = normalizePath(program);
this.remotePath = launchArgs.remotePath;
this.isApiV1 = false;
if (typeof launchArgs.apiVersion === 'number') {
this.isApiV1 = launchArgs.apiVersion === 1;
}
this.stackTraceDepth = typeof launchArgs.stackTraceDepth === 'number' ? launchArgs.stackTraceDepth : 50;
this.connection = new Promise(async (resolve, reject) => {
const mode = launchArgs.mode;
let dlvCwd = path.dirname(program);
let serverRunning = false;
const dlvArgs = new Array<string>();
// Get default LoadConfig values according to delve API:
// https://github.com/go-delve/delve/blob/c5c41f635244a22d93771def1c31cf1e0e9a2e63/service/rpc1/server.go#L13
// https://github.com/go-delve/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') {
log(`Start remote debugging: connecting ${launchArgs.host}:${launchArgs.port}`);
this.debugProcess = null;
this.isRemoteDebugging = true;
this.goroot = await queryGOROOT(dlvCwd, process.env);
serverRunning = true; // assume server is running when in remote mode
connectClient(launchArgs.port, launchArgs.host);
return;
}
this.isRemoteDebugging = false;
let env: NodeJS.ProcessEnv;
if (launchArgs.request === 'launch') {
let isProgramDirectory = false;
// Validations on the program
if (!program) {
return reject('The program attribute is missing in the debug configuration in launch.json');
}
try {
const 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' && path.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
try {
const fileEnvs = parseEnvFiles(launchArgs.envFile);
const launchArgsEnv = launchArgs.env || {};
env = Object.assign({}, process.env, fileEnvs, launchArgsEnv);
} catch (e) {
return reject(`failed to process 'envFile' and 'env' settings: ${e}`);
}
const 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;
this.goroot = await queryGOROOT(dlvCwd, env);
log(`Using GOPATH: ${env['GOPATH']}`);
log(`Using GOROOT: ${this.goroot}`);
log(`Using PATH: ${env['PATH']}`);
if (launchArgs.trace === 'verbose') {
Object.keys(env).forEach((key) => {
log(' export ' + key + '="' + env[key] + '"');
});
}
if (!!launchArgs.noDebug) {
if (mode === 'debug') {
this.noDebug = true;
const build = ['build'];
const output = path.join(os.tmpdir(), correctBinname('out'));
build.push(`-o=${output}`);
const buildOptions: { [key: string]: any } = { cwd: dirname, env };
if (launchArgs.buildFlags) {
build.push(launchArgs.buildFlags);
}
if (isProgramDirectory) {
build.push('.');
} else {
build.push(program);
}
const goExe = getBinPathWithPreferredGopathGoroot('go', []);
log(`Current working directory: ${dirname}`);
log(`Building: ${goExe} ${build.join(' ')}`);
// Use spawnSync to ensure that the binary exists before running it.
const buffer = spawnSync(goExe, build, buildOptions);
if (buffer.stderr && buffer.stderr.length > 0) {
const str = buffer.stderr.toString();
if (this.onstderr) {
this.onstderr(str);
}
}
if (buffer.stdout && buffer.stdout.length > 0) {
const str = buffer.stdout.toString();
if (this.onstdout) {
this.onstdout(str);
}
}
if (buffer.status) {
logError(`Build process exiting with code: ${buffer.status} signal: ${buffer.signal}`);
if (this.onclose) {
this.onclose(buffer.status);
}
} else {
log(`Build process exiting normally ${buffer.signal}`);
}
if (buffer.error) {
reject(buffer.error);
}
// Run the built binary
let wd = dirname;
if (!!launchArgs.cwd) {
wd = launchArgs.cwd;
}
const runOptions: { [key: string]: any } = { cwd: wd, env };
const run = [];
if (launchArgs.args) {
run.push(...launchArgs.args);
}
log(`Current working directory: ${wd}`);
log(`Running: ${output} ${run.join(' ')}`);
this.debugProcess = spawn(output, run, runOptions);
this.debugProcess.stderr.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstderr) {
this.onstderr(str);
}
});
this.debugProcess.stdout.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstdout) {
this.onstdout(str);
}
});
this.debugProcess.on('close', (code) => {
if (code) {
logError(`Process exiting with code: ${code} signal: ${this.debugProcess.killed}`);
} else {
log(`Process exiting normally ${this.debugProcess.killed}`);
}
if (this.onclose) {
this.onclose(code);
}
});
this.debugProcess.on('error', (err) => {
reject(err);
});
resolve(null);
return;
}
}
this.noDebug = false;
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/go-delve/delve & ensure it is in your Go tools path, "GOPATH/bin" or "PATH".`
);
}
const currentGOWorkspace = getCurrentGoWorkspaceFromGOPATH(env['GOPATH'], dirname);
if (!launchArgs.packagePathToGoModPathMap) {
launchArgs.packagePathToGoModPathMap = {};
}
dlvArgs.push(mode || 'debug');
if (mode === 'exec' || (mode === 'debug' && !isProgramDirectory)) {
dlvArgs.push(program);
} else if (currentGOWorkspace && !launchArgs.packagePathToGoModPathMap[dirname]) {
dlvArgs.push(dirname.substr(currentGOWorkspace.length + 1));
}
// add user-specified dlv flags first. When duplicate flags are specified,
// dlv doesn't mind but accepts the last flag value.
if (launchArgs.dlvFlags && launchArgs.dlvFlags.length > 0) {
dlvArgs.push(...launchArgs.dlvFlags);
}
dlvArgs.push('--headless=true', `--listen=${launchArgs.host}:${launchArgs.port}`);
if (!this.isApiV1) {
dlvArgs.push('--api-version=2');
}
if (launchArgs.showLog) {
dlvArgs.push('--log=' + launchArgs.showLog.toString());
}
if (launchArgs.logOutput) {
dlvArgs.push('--log-output=' + launchArgs.logOutput);
}
if (launchArgs.cwd) {
dlvArgs.push('--wd=' + launchArgs.cwd);
}
if (launchArgs.buildFlags) {
dlvArgs.push('--build-flags=' + launchArgs.buildFlags);
}
if (launchArgs.init) {
dlvArgs.push('--init=' + launchArgs.init);
}
if (launchArgs.backend) {
dlvArgs.push('--backend=' + launchArgs.backend);
}
if (launchArgs.output && (mode === 'debug' || mode === 'test')) {
dlvArgs.push('--output=' + launchArgs.output);
}
if (launchArgs.args && launchArgs.args.length > 0) {
dlvArgs.push('--', ...launchArgs.args);
}
this.localDebugeePath = this.getLocalDebugeePath(launchArgs.output);
} else if (launchArgs.request === 'attach') {
if (!launchArgs.processId) {
return reject(`Missing process ID`);
}
if (!existsSync(launchArgs.dlvToolPath)) {
return reject(
`Cannot find Delve debugger. Install from https://github.com/go-delve/delve & ensure it is in your Go tools path, "GOPATH/bin" or "PATH".`
);
}
dlvArgs.push('attach', `${launchArgs.processId}`);
// add user-specified dlv flags first. When duplicate flags are specified,
// dlv doesn't mind but accepts the last flag value.
if (launchArgs.dlvFlags && launchArgs.dlvFlags.length > 0) {
dlvArgs.push(...launchArgs.dlvFlags);
}
dlvArgs.push('--headless=true', '--listen=' + launchArgs.host + ':' + launchArgs.port.toString());
if (!this.isApiV1) {
dlvArgs.push('--api-version=2');
}
if (launchArgs.showLog) {
dlvArgs.push('--log=' + launchArgs.showLog.toString());
}
if (launchArgs.logOutput) {
dlvArgs.push('--log-output=' + launchArgs.logOutput);
}
if (launchArgs.cwd) {
dlvArgs.push('--wd=' + launchArgs.cwd);
}
if (launchArgs.backend) {
dlvArgs.push('--backend=' + launchArgs.backend);
}
}
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(() => {
const client = Client.$create(port, host);
client.connectSocket((err, conn) => {
if (err) {
return reject(err);
}
return resolve(conn);
});
client.on('error', reject);
}, 200);
}
this.debugProcess.stderr.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstderr) {
this.onstderr(str);
}
});
this.debugProcess.stdout.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstdout) {
this.onstdout(str);
}
if (!serverRunning) {
serverRunning = true;
connectClient(launchArgs.port, launchArgs.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', (err) => {
reject(err);
});
});
}
public 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);
}
);
}
public 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) => {
return err ? reject(err) : resolve(res);
});
},
(err) => {
reject(err);
}
);
});
}
/**
* Returns the current state of the delve debugger.
* This method does not block delve and should return immediately.
*/
public async getDebugState(): Promise<DebuggerState> {
// If a program is launched with --continue, the program is running
// before we can run attach. So we would need to check the state.
// We use NonBlocking so the call would return immediately.
const callResult = await this.callPromise<DebuggerState | CommandOut>('State', [{ NonBlocking: true }]);
return this.isApiV1 ? <DebuggerState>callResult : (<CommandOut>callResult).State;
}
/**
* Closing a debugging session follows different approaches for launch vs attach debugging.
*
* For launch without debugging, we kill the process since the extension started the `go run` process.
*
* For launch debugging, since the extension starts the delve process, the extension should close it as well.
* To gracefully clean up the assets created by delve, we send the Detach request with kill option set to true.
*
* For attach debugging there are two scenarios; attaching to a local process by ID or connecting to a
* remote delve server. For attach-local we start the delve process so will also terminate it however we
* detach from the debugee without killing it. For attach-remote we only close the client connection,
* but do not terminate the remote server.
*
* For local debugging, the only way to detach from delve when it is running a program is to send a Halt request first.
* Since the Halt request might sometimes take too long to complete, we have a timer in place to forcefully kill
* the debug process and clean up the assets in case of local debugging
*/
public async close(): Promise<void> {
const forceCleanup = async () => {
log(`killing debugee (pid: ${this.debugProcess.pid})...`);
await killProcessTree(this.debugProcess, log);
await removeFile(this.localDebugeePath);
};
if (this.noDebug) {
// delve isn't running so no need to halt
await forceCleanup();
return Promise.resolve();
}
const isLocalDebugging: boolean = this.request === 'launch' && !!this.debugProcess;
return new Promise(async (resolve) => {
this.delveConnectionClosed = true;
// For remote debugging, we want to leave the remote dlv server running,
// so instead of killing it via halt+detach, we just close the network connection.
// See https://www.github.com/go-delve/delve/issues/1587
if (this.isRemoteDebugging) {
log('Remote Debugging: close dlv connection.');
const rpcConnection = await this.connection;
// tslint:disable-next-line no-any
(rpcConnection as any)['conn']['end']();
return resolve();
}
const timeoutToken: NodeJS.Timer =
isLocalDebugging &&
setTimeout(async () => {
log('Killing debug process manually as we could not halt delve in time');
await forceCleanup();
resolve();
}, 1000);
let haltErrMsg: string;
try {
log('HaltRequest');
await this.callPromise('Command', [{ name: 'halt' }]);
} catch (err) {
log('HaltResponse');
haltErrMsg = err ? err.toString() : '';
log(`Failed to halt - ${haltErrMsg}`);
}
clearTimeout(timeoutToken);
const targetHasExited: boolean = haltErrMsg && haltErrMsg.endsWith('has exited with status 0');
const shouldDetach: boolean = !haltErrMsg || targetHasExited;
let shouldForceClean: boolean = !shouldDetach && isLocalDebugging;
if (shouldDetach) {
log('DetachRequest');
try {
await this.callPromise('Detach', [this.isApiV1 ? true : { Kill: isLocalDebugging }]);
} catch (err) {
log('DetachResponse');
logError(`Failed to detach - ${err.toString() || ''}`);
shouldForceClean = isLocalDebugging;
}
}
if (shouldForceClean) {
await forceCleanup();
}
return resolve();
});
}
private getLocalDebugeePath(output: string | undefined): string {
const configOutput = output || 'debug';
return path.isAbsolute(configOutput) ? configOutput : path.resolve(this.program, configOutput);
}
}
export class GoDebugSession extends LoggingDebugSession {
private variableHandles: Handles<DebugVariable>;
private breakpoints: Map<string, DebugBreakpoint[]>;
// Editing breakpoints requires halting delve, skip sending Stop Event to VS Code in such cases
private skipStopEventOnce: boolean;
private overrideStopReason: string;
private debugState: DebuggerState;
private delve: Delve;
private localPathSeparator: string;
private remotePathSeparator: string;
private stackFrameHandles: Handles<[number, number]>;
private packageInfo = new Map<string, string>();
private stopOnEntry: boolean;
private logLevel: Logger.LogLevel = Logger.LogLevel.Error;
private readonly initdone = 'initdone·';
private remoteSourcesAndPackages = new RemoteSourcesAndPackages();
private localToRemotePathMapping = new Map<string, string>();
private remoteToLocalPathMapping = new Map<string, string>();
// TODO(suzmue): Use delve's implementation of substitute-path.
private substitutePath: {from: string, to: string}[];
private showGlobalVariables: boolean = false;
private continueEpoch = 0;
private continueRequestRunning = false;
private nextEpoch = 0;
private nextRequestRunning = false;
public constructor(
debuggerLinesStartAt1: boolean,
isServer: boolean = false,
readonly fileSystem = fs) {
super('', debuggerLinesStartAt1, isServer);
this.variableHandles = new Handles<DebugVariable>();
this.skipStopEventOnce = false;
this.overrideStopReason = '';
this.stopOnEntry = false;
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');
// Set the capabilities that this debug adapter supports.
response.body.supportsConditionalBreakpoints = true;
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsSetVariable = true;
this.sendResponse(response);
log('InitializeResponse');
}
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
log('LaunchRequest');
if (!args.program) {
this.sendErrorResponse(
response,
3000,
'Failed to continue: The program attribute is missing in the debug configuration in launch.json'
);
return;
}
this.initLaunchAttachRequest(response, args);
}
protected attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments): void {
log('AttachRequest');
if (args.mode === 'local' && !args.processId) {
this.sendErrorResponse(
response,
3000,
'Failed to continue: the processId attribute is missing in the debug configuration in launch.json'
);
} else if (args.mode === 'remote' && !args.port) {
this.sendErrorResponse(
response,
3000,
'Failed to continue: the port attribute is missing in the debug configuration in launch.json'
);
}
this.initLaunchAttachRequest(response, args);
}
protected async disconnectRequest(
response: DebugProtocol.DisconnectResponse,
args: DebugProtocol.DisconnectArguments
): Promise<void> {
log('DisconnectRequest');
if (this.delve) {
// Since users want to reset when they issue a disconnect request,
// we should have a timeout in case disconnectRequestHelper hangs.
await Promise.race([
this.disconnectRequestHelper(response, args),
new Promise<void>((resolve) => setTimeout(() => {
log('DisconnectRequestHelper timed out after 5s.');
resolve();
}, 5_000))
]);
}
this.shutdownProtocolServer(response, args);
log('DisconnectResponse');
}
protected async disconnectRequestHelper(
response: DebugProtocol.DisconnectResponse,
args: DebugProtocol.DisconnectArguments
): Promise<void> {
// There is a chance that a second disconnectRequest can come through
// if users click detach multiple times. In that case, we want to
// guard against talking to the closed Delve connection.
// Note: this does not completely guard against users attempting to
// disconnect multiple times when a disconnect request is still running.
// The order of the execution may results in strange states that don't allow
// the delve connection to fully disconnect.
if (this.delve.delveConnectionClosed) {
log(`Skip disconnectRequestHelper as Delve's connection is already closed.`);
return;
}
// For remote process, we have to issue a continue request
// before disconnecting.
if (this.delve.isRemoteDebugging) {
if (!(await this.isDebuggeeRunning())) {
log(`Issuing a continue command before closing Delve's connection as the debuggee is not running.`);
this.continue();
}
}
log('Closing Delve.');