-
Notifications
You must be signed in to change notification settings - Fork 757
/
goDlvDebug.ts
779 lines (687 loc) · 22.7 KB
/
goDlvDebug.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
/*---------------------------------------------------------
* Copyright 2020 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
// NOTE: This debug adapter is experimental, in-development code. If you
// actually need to debug Go code, please use the default adapter.
import { ChildProcess, spawn } from 'child_process';
import * as fs from 'fs';
import net = require('net');
import * as os from 'os';
import * as path from 'path';
import {
logger,
Logger,
LoggingDebugSession,
OutputEvent,
TerminatedEvent
} from 'vscode-debugadapter';
import { DebugProtocol } from 'vscode-debugprotocol';
import { envPath, expandFilePathInOutput, getBinPathWithPreferredGopathGoroot } from '../utils/pathUtils';
import { killProcessTree } from '../utils/processUtils';
import { DAPClient } from './dapClient';
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;
}
// 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;
/** 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;
}
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));
}
// GoDlvDapDebugSession implements a DAP debug adapter to talk to the editor.
//
// This adapter serves as a DAP proxy between the editor and the DAP server
// inside Delve. It relies on functionality inherited from DebugSession to
// implement the server side interfacing the editor, and on DapClient to
// implement the client side interfacing Delve:
//
// Editor GoDlvDapDebugSession Delve
// +------------+ +--------------+-----------+ +------------+
// | DAP Client | <====> | DebugSession | DAPClient | <====> | DAP Server |
// +------------+ +--------------+-----------+ +------------+
export class GoDlvDapDebugSession extends LoggingDebugSession {
private readonly DEFAULT_DELVE_HOST = '127.0.0.1';
private readonly DEFAULT_DELVE_PORT = 42042;
private logLevel: Logger.LogLevel = Logger.LogLevel.Error;
private dlvClient: DelveClient = null;
// Child process used to track debugee launched without debugging (noDebug
// mode). Either debugProcess or dlvClient are null.
private debugProcess: ChildProcess = null;
public constructor() {
super();
// Invoke logger.init here because we want logging to work in 'inline'
// DA mode. It's typically called in the start() method of our parent
// class, but this method isn't called in 'inline' mode.
logger.init((e) => this.sendEvent(e));
// this debugger uses zero-based lines and columns
this.setDebuggerLinesStartAt1(false);
this.setDebuggerColumnsStartAt1(false);
}
protected initializeRequest(
response: DebugProtocol.InitializeResponse,
args: DebugProtocol.InitializeRequestArguments,
request?: DebugProtocol.Request
): void {
log('InitializeRequest');
response.body.supportsConfigurationDoneRequest = true;
// We respond to InitializeRequest here, because Delve hasn't been
// launched yet. Delve will start responding to DAP requests after
// LaunchRequest is received, which tell us how to start it.
// TODO: we could send an InitializeRequest to Delve when
// it launches, wait for its response and sanity check the capabilities
// it reports. Once DAP support in Delve is complete, this can be part
// of making sure that the "dlv" binary we find is sufficiently
// up-to-date to talk DAP with us.
this.sendResponse(response);
log('InitializeResponse');
}
protected launchRequest(
response: DebugProtocol.LaunchResponse,
args: LaunchRequestArguments,
request: DebugProtocol.Request
): void {
// Setup logger now that we have the 'trace' level passed in from
// LaunchRequestArguments.
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-godlvdapdebug.txt') : undefined;
logger.setup(this.logLevel, logPath);
log('launchRequest');
// In noDebug mode with the 'debug' launch mode, we don't launch Delve
// but run the debugee directly.
// For other launch modes we currently still defer to Delve, for
// compatibility with the old debugAdapter.
// See https://github.com/golang/vscode-go/issues/336
if (args.noDebug && args.mode === 'debug') {
try {
this.launchNoDebug(args);
} catch (e) {
logError(`launchNoDebug failed: "${e}"`);
// TODO: define error constants
// https://github.com/golang/vscode-go/issues/305
this.sendErrorResponse(
response,
3000,
`Failed to launch "${e}"`);
}
return;
}
if (!args.port) {
args.port = this.DEFAULT_DELVE_PORT;
}
if (!args.host) {
args.host = this.DEFAULT_DELVE_HOST;
}
this.dlvClient = new DelveClient(args);
this.dlvClient.on('stdout', (str) => {
log('dlv stdout:', str);
});
this.dlvClient.on('stderr', (str) => {
log('dlv stderr:', str);
});
this.dlvClient.on('connected', () => {
// Once the client is connected to Delve, forward it the launch
// request to begin the actual debugging session.
this.dlvClient.send(request);
});
this.dlvClient.on('close', (rc) => {
if (rc !== 0) {
// TODO: define error constants
// https://github.com/golang/vscode-go/issues/305
this.sendErrorResponse(
response,
3000,
'Failed to continue: Check the debug console for details.');
}
log('Sending TerminatedEvent as delve is closed');
this.sendEvent(new TerminatedEvent());
});
// Relay events and responses back to vscode. In the future we will
// add middleware here to intercept specific kinds of responses/events
// for special handling.
this.dlvClient.on('event', (event) => {
this.sendEvent(event);
});
this.dlvClient.on('response', (resp) => {
this.sendResponse(resp);
});
}
protected attachRequest(
response: DebugProtocol.AttachResponse,
args: AttachRequestArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected disconnectRequest(
response: DebugProtocol.DisconnectResponse,
args: DebugProtocol.DisconnectArguments,
request?: DebugProtocol.Request
): void {
log('DisconnectRequest');
// How we handle DisconnectRequest depends on whether Delve was launched
// at all.
// * In noDebug node, the Go program was spawned directly without
// debugging: this.debugProcess will be non-null, and this.dlvClient
// will be null.
// * Otherwise, Delve was spawned: this.debugProcess will be null, and
// this.dlvClient will be non-null.
if (this.debugProcess !== null) {
log(`killing debugee (pid: ${this.debugProcess.pid})...`);
// Kill the debugee and notify the client when the killing is
// completed, to ensure a clean shutdown sequence.
killProcessTree(this.debugProcess, log).then(() => {
super.disconnectRequest(response, args);
log('DisconnectResponse');
});
} else if (this.dlvClient !== null) {
// Forward this DisconnectRequest to Delve.
this.dlvClient.send(request);
} else {
logError(`both debug process and dlv client are null`);
// TODO: define all error codes as constants
// https://github.com/golang/vscode-go/issues/305
this.sendErrorResponse(
response,
3000,
'Failed to disconnect: Check the debug console for details.');
}
}
protected terminateRequest(
response: DebugProtocol.TerminateResponse,
args: DebugProtocol.TerminateArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected restartRequest(
response: DebugProtocol.RestartResponse,
args: DebugProtocol.RestartArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setBreakPointsRequest(
response: DebugProtocol.SetBreakpointsResponse,
args: DebugProtocol.SetBreakpointsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setFunctionBreakPointsRequest(
response: DebugProtocol.SetFunctionBreakpointsResponse,
args: DebugProtocol.SetFunctionBreakpointsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setExceptionBreakPointsRequest(
response: DebugProtocol.SetExceptionBreakpointsResponse,
args: DebugProtocol.SetExceptionBreakpointsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected configurationDoneRequest(
response: DebugProtocol.ConfigurationDoneResponse,
args: DebugProtocol.ConfigurationDoneArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected continueRequest(
response: DebugProtocol.ContinueResponse,
args: DebugProtocol.ContinueArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected nextRequest(
response: DebugProtocol.NextResponse,
args: DebugProtocol.NextArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected stepInRequest(
response: DebugProtocol.StepInResponse,
args: DebugProtocol.StepInArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected stepOutRequest(
response: DebugProtocol.StepOutResponse,
args: DebugProtocol.StepOutArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected stepBackRequest(
response: DebugProtocol.StepBackResponse,
args: DebugProtocol.StepBackArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected reverseContinueRequest(
response: DebugProtocol.ReverseContinueResponse,
args: DebugProtocol.ReverseContinueArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected restartFrameRequest(
response: DebugProtocol.RestartFrameResponse,
args: DebugProtocol.RestartFrameArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected gotoRequest(
response: DebugProtocol.GotoResponse,
args: DebugProtocol.GotoArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected pauseRequest(
response: DebugProtocol.PauseResponse,
args: DebugProtocol.PauseArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected sourceRequest(
response: DebugProtocol.SourceResponse,
args: DebugProtocol.SourceArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected threadsRequest(
response: DebugProtocol.ThreadsResponse,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected terminateThreadsRequest(
response: DebugProtocol.TerminateThreadsResponse,
args: DebugProtocol.TerminateThreadsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected stackTraceRequest(
response: DebugProtocol.StackTraceResponse,
args: DebugProtocol.StackTraceArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected scopesRequest(
response: DebugProtocol.ScopesResponse,
args: DebugProtocol.ScopesArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected variablesRequest(
response: DebugProtocol.VariablesResponse,
args: DebugProtocol.VariablesArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setVariableRequest(
response: DebugProtocol.SetVariableResponse,
args: DebugProtocol.SetVariableArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setExpressionRequest(
response: DebugProtocol.SetExpressionResponse,
args: DebugProtocol.SetExpressionArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected evaluateRequest(
response: DebugProtocol.EvaluateResponse,
args: DebugProtocol.EvaluateArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected stepInTargetsRequest(
response: DebugProtocol.StepInTargetsResponse,
args: DebugProtocol.StepInTargetsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected gotoTargetsRequest(
response: DebugProtocol.GotoTargetsResponse,
args: DebugProtocol.GotoTargetsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected completionsRequest(
response: DebugProtocol.CompletionsResponse,
args: DebugProtocol.CompletionsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected exceptionInfoRequest(
response: DebugProtocol.ExceptionInfoResponse,
args: DebugProtocol.ExceptionInfoArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected loadedSourcesRequest(
response: DebugProtocol.LoadedSourcesResponse,
args: DebugProtocol.LoadedSourcesArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected dataBreakpointInfoRequest(
response: DebugProtocol.DataBreakpointInfoResponse,
args: DebugProtocol.DataBreakpointInfoArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setDataBreakpointsRequest(
response: DebugProtocol.SetDataBreakpointsResponse,
args: DebugProtocol.SetDataBreakpointsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected readMemoryRequest(
response: DebugProtocol.ReadMemoryResponse,
args: DebugProtocol.ReadMemoryArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected disassembleRequest(
response: DebugProtocol.DisassembleResponse,
args: DebugProtocol.DisassembleArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected cancelRequest(
response: DebugProtocol.CancelResponse,
args: DebugProtocol.CancelArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected breakpointLocationsRequest(
response: DebugProtocol.BreakpointLocationsResponse,
args: DebugProtocol.BreakpointLocationsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
protected setInstructionBreakpointsRequest(
response: DebugProtocol.SetInstructionBreakpointsResponse,
args: DebugProtocol.SetInstructionBreakpointsArguments,
request?: DebugProtocol.Request
): void {
this.dlvClient.send(request);
}
// Launch the debugee process without starting a debugger.
// This implements the `Run > Run Without Debugger` functionality in vscode.
// Note: this method currently assumes launchArgs.mode === 'debug'.
private launchNoDebug(launchArgs: LaunchRequestArguments): void {
if (launchArgs.mode !== 'debug') {
throw new Error('launchNoDebug requires "debug" mode');
}
const {program, dirname, programIsDirectory} = parseProgramArgSync(launchArgs);
const goRunArgs = ['run'];
if (launchArgs.buildFlags) {
goRunArgs.push(launchArgs.buildFlags);
}
if (programIsDirectory) {
goRunArgs.push('.');
} else {
goRunArgs.push(program);
}
if (launchArgs.args) {
goRunArgs.push(...launchArgs.args);
}
// launchArgs.env includes all the environment variables
// including vscode-go's toolsExecutionEnvironment (PATH, GOPATH, ...),
// and those read from .env files.
const launchArgsEnv = launchArgs.env || {};
const programEnv = Object.assign({}, process.env, launchArgsEnv);
log(`Current working directory: ${dirname}`);
const goExe = getBinPathWithPreferredGopathGoroot('go', []);
log(`Running: ${goExe} ${goRunArgs.join(' ')}`);
this.debugProcess = spawn(goExe, goRunArgs, {
cwd: dirname,
env: programEnv
});
this.debugProcess.stderr.on('data', (str) => {
this.sendEvent(new OutputEvent(str.toString(), 'stderr'));
});
this.debugProcess.stdout.on('data', (str) => {
this.sendEvent(new OutputEvent(str.toString(), 'stdout'));
});
this.debugProcess.on('close', (rc) => {
this.sendEvent(new TerminatedEvent());
});
}
}
// DelveClient provides a DAP client to talk to a DAP server in Delve.
//
// After creation, it emits the following events:
//
// 'connected': client is connected to delve
// 'request (request)': delve sent request
// 'response (response)': delve sent response
// 'event (event)': delve sent event
// 'stdout' (str): delve emitted str to stdout
// 'stderr' (str): delve emitted str to stderr
// 'close' (rc): delve exited with return code rc
class DelveClient extends DAPClient {
private debugProcess: ChildProcess;
private serverStarted: boolean = false;
constructor(launchArgs: LaunchRequestArguments) {
super();
const launchArgsEnv = launchArgs.env || {};
const env = Object.assign({}, process.env, launchArgsEnv);
// Let users override direct path to delve by setting it in the env
// map in launch.json; if unspecified, fall back to dlvToolPath.
let dlvPath = launchArgsEnv['dlvPath'];
if (!dlvPath) {
dlvPath = launchArgs.dlvToolPath;
}
if (!fs.existsSync(dlvPath)) {
log(
`Couldn't find dlv at the Go tools path, ${process.env['GOPATH']}${
env['GOPATH'] ? ', ' + env['GOPATH'] : ''
} or ${envPath}`
);
throw new Error(
`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 dlvArgs = new Array<string>();
dlvArgs.push('dap');
// 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(`--listen=${launchArgs.host}:${launchArgs.port}`);
if (launchArgs.showLog) {
dlvArgs.push('--log=' + launchArgs.showLog.toString());
}
if (launchArgs.logOutput) {
dlvArgs.push('--log-output=' + launchArgs.logOutput);
}
log(`Running: ${dlvPath} ${dlvArgs.join(' ')}`);
const dir = parseProgramArgSync(launchArgs).dirname;
this.debugProcess = spawn(dlvPath, dlvArgs, {
cwd: dir,
env
});
this.debugProcess.stderr.on('data', (chunk) => {
let str = chunk.toString();
str = expandFilePathInOutput(str, dir);
this.emit('stderr', str);
});
this.debugProcess.stdout.on('data', (chunk) => {
const str = chunk.toString();
this.emit('stdout', str);
if (!this.serverStarted) {
this.serverStarted = true;
this.connectSocketToServer(launchArgs.port, launchArgs.host);
}
});
this.debugProcess.on('close', (rc) => {
if (rc) {
logError(`Process exiting with code: ${rc} signal: ${this.debugProcess.killed}`);
} else {
log(`Process exiting normally ${this.debugProcess.killed}`);
}
this.emit('close', rc);
});
this.debugProcess.on('error', (err) => {
throw err;
});
}
// Connect this client to the server. The server is expected to be listening
// on host:port.
private connectSocketToServer(port: number, host: string) {
// Add a slight delay to ensure that Delve started up the server.
setTimeout(() => {
const socket = net.createConnection(
port,
host,
() => {
this.connect(socket, socket);
this.emit('connected');
});
socket.on('error', (err) => {
throw err;
});
}, 200);
}
}
// Helper function to parse a program from LaunchRequestArguments. Returns:
// {
// program: the program arg,
// dirname: the directory containing the program (or 'program' itself if
// it's already a directory),
// programIsDirectory: is the program a directory?
// }
//
// The program argument is taken as-is from launchArgs. If the program path
// is relative, dirname will also be relative. If the program path is absolute,
// dirname will also be absolute.
//
// Throws an exception in case args.program is not a valid file or directory.
// This function can block because it calls a blocking fs function.
function parseProgramArgSync(launchArgs: LaunchRequestArguments
): { program: string, dirname: string, programIsDirectory: boolean } {
const program = launchArgs.program;
if (!program) {
throw new Error('The program attribute is missing in the debug configuration in launch.json');
}
let programIsDirectory = false;
try {
programIsDirectory = fs.lstatSync(program).isDirectory();
} catch (e) {
throw new Error('The program attribute must point to valid directory, .go file or executable.');
}
if (!programIsDirectory && path.extname(program) !== '.go') {
throw new Error('The program attribute must be a directory or .go file in debug mode');
}
const dirname = programIsDirectory ? program : path.dirname(program);
return {program, dirname, programIsDirectory};
}