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 645
/
goDebug.ts
1929 lines (1801 loc) · 59.9 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 { ChildProcess, execFile, execSync, spawn, spawnSync } from 'child_process';
import * as fs from 'fs';
import { existsSync, lstatSync } from 'fs';
import { Client, RPCConnection } from 'json-rpc2';
import * as os from 'os';
import * as path from 'path';
import kill = require('tree-kill');
import * as util from 'util';
import {
DebugSession,
Handles,
InitializedEvent,
logger,
Logger,
LoggingDebugSession,
OutputEvent,
Scope,
Source,
StackFrame,
StoppedEvent,
TerminatedEvent,
Thread
} from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import {
envPath,
fixDriveCasingInWindows,
getBinPathWithPreferredGopath,
getCurrentGoWorkspaceFromGOPATH,
getInferredGopath,
parseEnvFile
} from '../goPath';
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;
breakPoint: DebugBreakpoint;
breakPointInfo: {};
currentThread: DebugThread;
currentGoroutine: DebugGoroutine;
Running: boolean;
}
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;
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[];
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
}
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;
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;
}
// 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;
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';
/** Optional path to .env file. */
envFile?: string | 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;
packagePathToGoModPathMap: { [key: string]: string };
}
interface AttachRequestArguments extends DebugProtocol.AttachRequestArguments {
request: 'attach';
processId?: number;
stopOnEntry?: boolean;
showLog?: boolean;
logOutput?: string;
cwd?: string;
mode?: 'local' | 'remote';
remotePath?: string;
port?: number;
host?: string;
trace?: 'verbose' | 'log' | 'error';
backend?: 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('/') ? '/' : '\\';
}
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;
}
class Delve {
public program: string;
public remotePath: string;
public loadConfig: LoadConfig;
public connection: Promise<RPCConnection>;
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;
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((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') {
this.debugProcess = null;
this.isRemoteDebugging = true;
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
const fileEnvs = [];
try {
if (typeof launchArgs.envFile === 'string') {
fileEnvs.push(parseEnvFile(launchArgs.envFile));
}
if (Array.isArray(launchArgs.envFile)) {
launchArgs.envFile.forEach((envFile) => {
fileEnvs.push(parseEnvFile(envFile));
});
}
} catch (e) {
return reject(e);
}
const launchArgsEnv = launchArgs.env || {};
env = Object.assign({}, process.env, ...fileEnvs, launchArgsEnv);
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;
log(`Using GOPATH: ${env['GOPATH']}`);
if (!!launchArgs.noDebug) {
if (mode === 'debug') {
this.noDebug = true;
const runArgs = ['run'];
const runOptions: { [key: string]: any } = { cwd: dirname, env };
if (launchArgs.buildFlags) {
runArgs.push(launchArgs.buildFlags);
}
if (isProgramDirectory) {
runArgs.push('.');
} else {
runArgs.push(program);
}
if (launchArgs.args) {
runArgs.push(...launchArgs.args);
}
this.debugProcess = spawn(getBinPathWithPreferredGopath('go', []), runArgs, 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) => {
logError('Process exiting with code: ' + code);
if (this.onclose) {
this.onclose(code);
}
});
this.debugProcess.on('error', (err) => {
reject(err);
});
resolve();
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/derekparker/delve & ensure it is in your Go tools path, "GOPATH/bin" or "PATH".`
);
}
const currentGOWorkspace = getCurrentGoWorkspaceFromGOPATH(env['GOPATH'], dirname);
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));
}
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}`);
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);
});
}, 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 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 detach from delve.
*
* 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 close(): Thenable<void> {
if (this.noDebug) {
// delve isn't running so no need to halt
return Promise.resolve();
}
log('HaltRequest');
const isLocalDebugging: boolean = this.request === 'launch' && !!this.debugProcess;
const forceCleanup = async () => {
kill(this.debugProcess.pid, (err) => console.log('Error killing debug process: ' + err));
await removeFile(this.localDebugeePath);
};
return new Promise(async (resolve) => {
// For remote debugging, closing the connection would terminate the
// program as well so we just want to disconnect.
// See https://www.github.com/go-delve/delve/issues/1587
if (this.isRemoteDebugging) {
const rpcConnection = await this.connection;
// tslint:disable-next-line no-any
(rpcConnection as any)['conn']['end']();
return;
}
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 {
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);
}
}
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 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 showGlobalVariables: boolean = false;
private continueEpoch = 0;
private continueRequestRunning = false;
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false) {
super('', debuggerLinesStartAt1, isServer);
this.variableHandles = new Handles<DebugVariable>();
this.skipStopEventOnce = false;
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');
// This debug adapter implements the configurationDoneRequest.
response.body.supportsConfigurationDoneRequest = true;
response.body.supportsSetVariable = true;
this.sendResponse(response);
log('InitializeResponse');
}
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void {
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 {
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');
// For remote process, we have to issue a continue request
// before disconnecting.
if (this.delve.isRemoteDebugging) {
// We don't have to wait for continue call
// because we are not doing anything with the result.
// Also, DisconnectRequest will return before
// we get the result back from delve.
this.debugState = await this.delve.getDebugState();
if (!this.debugState.Running) {
this.continue();
}
}
this.delve.close().then(() => {
log('DisconnectRequest to parent');
super.disconnectRequest(response, args);
log('DisconnectResponse');
});
}
protected async configurationDoneRequest(
response: DebugProtocol.ConfigurationDoneResponse,
args: DebugProtocol.ConfigurationDoneArguments
): Promise<void> {
log('ConfigurationDoneRequest');
if (this.stopOnEntry) {
this.sendEvent(new StoppedEvent('entry', 1));
log('StoppedEvent("entry")');
this.sendResponse(response);
} else {
this.debugState = await this.delve.getDebugState();
if (!this.debugState.Running) {
this.continueRequest(<DebugProtocol.ContinueResponse>response);
}
}
}
protected toDebuggerPath(filePath: string): string {
if (this.delve.remotePath.length === 0) {
return this.convertClientPathToDebugger(filePath);
}
// The filePath may have a different path separator than the localPath
// So, update it to use the same separator as the remote path to ease
// in replacing the local path in it with remote path
filePath = filePath.replace(/\/|\\/g, this.remotePathSeparator);
return filePath.replace(this.delve.program.replace(/\/|\\/g, this.remotePathSeparator), this.delve.remotePath);
}
protected toLocalPath(pathToConvert: string): string {
if (this.delve.remotePath.length === 0) {
return this.convertDebuggerPathToClient(pathToConvert);
}
// When the pathToConvert is under GOROOT or Go module cache, replace path appropriately
if (!pathToConvert.startsWith(this.delve.remotePath)) {
// Fix for https://github.com/Microsoft/vscode-go/issues/1178
const index = pathToConvert.indexOf(`${this.remotePathSeparator}src${this.remotePathSeparator}`);
const goroot = process.env['GOROOT'];
if (goroot && index > 0) {
return path.join(goroot, pathToConvert.substr(index));
}
const indexGoModCache = pathToConvert.indexOf(
`${this.remotePathSeparator}pkg${this.remotePathSeparator}mod${this.remotePathSeparator}`
);
const gopath = (process.env['GOPATH'] || '').split(path.delimiter)[0];
if (gopath && indexGoModCache > 0) {
return path.join(
gopath,
pathToConvert
.substr(indexGoModCache)
.split(this.remotePathSeparator)
.join(this.localPathSeparator)
);
}
}
return pathToConvert
.replace(this.delve.remotePath, this.delve.program)
.split(this.remotePathSeparator)
.join(this.localPathSeparator);
}
protected async setBreakPointsRequest(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments
): Promise<void> {
log('SetBreakPointsRequest');
try {
// 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.
this.debugState = await this.delve.getDebugState();
} catch (error) {
this.logDelveError(error, 'Failed to get state');
}
if (!this.debugState.Running && !this.continueRequestRunning) {
await this.setBreakPoints(response, args);
} else {
this.skipStopEventOnce = this.continueRequestRunning;
this.delve.callPromise('Command', [{ name: 'halt' }]).then(
() => {
return this.setBreakPoints(response, args).then(() => {
return this.continue(true).then(null, (err) => {
this.logDelveError(err, 'Failed to continue delve after halting it to set breakpoints');
});
});
},
(err) => {
this.skipStopEventOnce = false;
this.logDelveError(err, 'Failed to halt delve before attempting to set breakpoint');
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) {
this.logDelveError(err, 'Failed to get threads');
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);
const threads = goroutines.map(
(goroutine) =>
new Thread(
goroutine.id,
goroutine.userCurrentLoc.function
? goroutine.userCurrentLoc.function.name
: goroutine.userCurrentLoc.file + '@' + goroutine.userCurrentLoc.line
)
);
if (threads.length === 0) {
threads.push(new Thread(1, 'Dummy'));
}
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;
const 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) {
this.logDelveError(err, 'Failed to produce stacktrace');
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(path.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');