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
1639 lines (1515 loc) · 55 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 * as fs from 'fs';
import * as util from 'util';
import { DebugProtocol } from 'vscode-debugprotocol';
import { DebugSession, InitializedEvent, TerminatedEvent, ThreadEvent, StoppedEvent, OutputEvent, Thread, StackFrame, Scope, Source, Handles, LoggingDebugSession, Logger, logger, Breakpoint } 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, getInferredGopath, getCurrentGoWorkspaceFromGOPATH, envPath, fixDriveCasingInWindows } 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;
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;
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;
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;
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;
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;
localDebugeePath: string | undefined;
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;
isRemoteDebugging: boolean;
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 = 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' && 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);
}
const launchArgsEnv = launchArgs.env || {};
env = Object.assign({}, process.env, fileEnv, 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') {
if (isProgramDirectory && launchArgs.currentFile) {
program = launchArgs.currentFile;
isProgramDirectory = false;
}
if (!isProgramDirectory) {
this.noDebug = true;
const 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 => {
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') {
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 () => {
killTree(this.debugProcess.pid);
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[]>;
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 stopOnEntry: boolean;
private logLevel: Logger.LogLevel = Logger.LogLevel.Error;
private readonly initdone = 'initdone·';
private showGlobalVariables: boolean = false;
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false) {
super('', debuggerLinesStartAt1, isServer);
this.variableHandles = new Handles<DebugVariable>();
this.skipStopEventOnce = false;
this.stopOnEntry = 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: string) {
if (/^(\w:[\\/]|\\\\)/.test(path)) {
return '\\';
}
return path.includes('/') ? '/' : '\\';
}
// contains common code for launch and attach debugging initialization
private initLaunchAttachRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments | AttachRequestArguments) {
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.stopOnEntry) {
this.stopOnEntry = args.stopOnEntry;
}
if (!args.port) {
args.port = random(2000, 50000);
}
if (!args.host) {
args.host = '127.0.0.1';
}
let localPath: string;
if (args.request === 'attach') {
localPath = args.cwd;
} else if (args.request === 'launch') {
localPath = args.program;
}
if (!args.remotePath) {
// too much code relies on remotePath never being null
args.remotePath = '';
}
if (args.remotePath.length > 0) {
this.localPathSeparator = this.findPathSeperator(localPath);
this.remotePathSeparator = this.findPathSeperator(args.remotePath);
const llist = localPath.split(/\/|\\/).reverse();
const rlist = args.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;
args.remotePath = rlist.reverse().slice(0, -i).join(this.remotePathSeparator) + this.remotePathSeparator;
} else if (args.remotePath.length > 1 &&
(args.remotePath.endsWith('\\') || args.remotePath.endsWith('/'))) {
args.remotePath = args.remotePath.substring(0, args.remotePath.length - 1);
}
}
// Launch the Delve debugger on the program
this.delve = new Delve(args, localPath);
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() });
}
const 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 property "apiVersion" in your launch.json file.`;
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 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('breakpoint', 1));
log('StoppedEvent("breakpoint")');
this.sendResponse(response);
} else {
this.debugState = await this.delve.getDebugState();
if (!this.debugState.Running) {
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)) {
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));
}
}
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...
const needsToBeStopped = new Set<number>();
this.goroutines.forEach(id => needsToBeStopped.add(id));
for (const 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> {
const file = normalizePath(args.source.path);
if (!this.breakpoints.get(file)) {
this.breakpoints.set(file, []);
}
const 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');
let existingBreakpoints: DebugBreakpoint[] | undefined;
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);
}
const 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,
async (err) => {
// Delve does not seem to support error code at this time.
// TODO(quoct): Follow up with delve team.
if (err.toString().startsWith('Breakpoint exists at')) {
log('Encounter existing breakpoint: ' + breakpointIn);
// We need to call listbreakpoints to find the ID.
// Otherwise, we would not be able to clear the breakpoints.
if (!existingBreakpoints) {
try {
const listBreakpointsResponse =
await this.delve.callPromise<ListBreakpointsOut | DebugBreakpoint[]>('ListBreakpoints', this.delve.isApiV1 ? [] : [{}]);
existingBreakpoints = this.delve.isApiV1 ?
listBreakpointsResponse as DebugBreakpoint[] : (listBreakpointsResponse as ListBreakpointsOut).Breakpoints;
} catch (error) {
log('Error listing breakpoints: ' + error.toString());
return null;
}
}
const matchedBreakpoint = existingBreakpoints.find(breakpoint =>
breakpoint.line === breakpointIn.line && breakpoint.file === breakpointIn.file);
if (!matchedBreakpoint) {
log(`Cannot match breakpoint ${breakpointIn} with existing breakpoints.`);
return null;
}
return this.delve.isApiV1 ? matchedBreakpoint : { Breakpoint: matchedBreakpoint };
}
log('Error on CreateBreakpoint: ' + err.toString());
return null;
});
}));
}).then(newBreakpoints => {
let convertedBreakpoints: DebugBreakpoint[];
if (!this.delve.isApiV1) {
// Unwrap breakpoints from v2 apicall
convertedBreakpoints = newBreakpoints.map((bp, i) => {
return bp ? (bp as CreateBreakpointOut).Breakpoint : null;
});
} else {
convertedBreakpoints = newBreakpoints as DebugBreakpoint[];
}
log('All set:' + JSON.stringify(newBreakpoints));
const breakpoints = convertedBreakpoints.map((bp, i) => {
if (bp) {
return { verified: true, line: bp.line };
} else {
return { verified: false, line: args.lines[i] };
}
});
this.breakpoints.set(file, convertedBreakpoints.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 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) {
logError(`Failed to get state ${String(error)}`);
}
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(() => {