forked from devcat-studio/VSCodeLuaDebug
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDebugSession.cs
More file actions
581 lines (510 loc) · 21 KB
/
Copy pathDebugSession.cs
File metadata and controls
581 lines (510 loc) · 21 KB
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
// Original work by:
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Modified by:
/*---------------------------------------------------------------------------------------------
* Copyright (c) NEXON Korea Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using GiderosPlayerRemote;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
namespace VSCodeDebug
{
public class DebugSession : ICDPListener, IDebuggeeListener, IRemoteControllerListener
{
public ICDPSender toVSCode;
public IDebuggeeSender toDebuggee;
Process process;
RemoteController giderosRemoteController;
string giderosStdoutBuffer = "";
string workingDirectory;
string sourceBasePath;
Tuple<string, int> fakeBreakpointMode = null;
string startCommand;
int startSeq;
bool jumpToGiderosErrorPosition = false;
bool stopGiderosWhenDebuggerStops = false;
TcpListener listener;
Encoding encoding;
public DebugSession()
{
Program.WaitingUI.SetLabelText(
"Waiting for commands from Visual Studio Code...");
}
void ICDPListener.X_FromVSCode(string command, int seq, dynamic args, string reqText)
{
lock (this)
{
//MessageBox.OK(reqText);
if (args == null) { args = new { }; }
if (fakeBreakpointMode != null)
{
if (command == "configurationDone")
{
SendResponse(command, seq, null);
}
else if (command == "threads")
{
SendResponse(command, seq, new ThreadsResponseBody(
new List<Thread>() { new Thread(999, "fake-thread") }));
}
else if (command == "stackTrace")
{
var src = new Source(Path.Combine(sourceBasePath, fakeBreakpointMode.Item1));
var f = new StackFrame(9999, "fake-frame", src, fakeBreakpointMode.Item2, 0);
SendResponse(command, seq, new StackTraceResponseBody(
new List<StackFrame>() { f }));
}
else if (command == "scopes")
{
SendResponse(command, seq, new ScopesResponseBody(
new List<Scope>()));
System.Threading.Thread.Sleep(1000);
toVSCode.SendMessage(new TerminatedEvent());
}
else
{
SendErrorResponse(command, seq, 999, "", new { });
}
return;
}
try
{
switch (command)
{
case "initialize":
Initialize(command, seq, args);
break;
case "launch":
Launch(command, seq, args);
break;
case "attach":
Attach(command, seq, args);
break;
case "disconnect":
Disconnect(command, seq, args);
break;
case "next":
case "continue":
case "stepIn":
case "stepOut":
case "stackTrace":
case "scopes":
case "variables":
case "threads":
case "setBreakpoints":
case "configurationDone":
case "evaluate":
case "pause":
if (toDebuggee != null)
{
toDebuggee.Send(reqText);
}
break;
case "source":
SendErrorResponse(command, seq, 1020, "command not supported: " + command);
break;
default:
SendErrorResponse(command, seq, 1014, "unrecognized request: {_request}", new { _request = command });
break;
}
}
catch (Exception e)
{
MessageBox.WTF(e.ToString());
SendErrorResponse(command, seq, 1104, "error while processing request '{_request}' (exception: {_exception})", new { _request = command, _exception = e.Message });
Environment.Exit(1);
}
}
}
void SendResponse(string command, int seq, dynamic body)
{
var response = new Response(command, seq);
if (body != null)
{
response.SetBody(body);
}
toVSCode.SendMessage(response);
}
void SendErrorResponse(string command, int seq, int id, string format, dynamic arguments = null, bool user = true, bool telemetry = false)
{
var response = new Response(command, seq);
var msg = new Message(id, format, arguments, user, telemetry);
var message = Utilities.ExpandVariables(msg.format, msg.variables);
response.SetErrorBody(message, new ErrorResponseBody(msg));
toVSCode.SendMessage(response);
}
void Disconnect(string command, int seq, dynamic arguments)
{
if (giderosRemoteController != null &&
stopGiderosWhenDebuggerStops)
{
giderosRemoteController.SendStop();
}
if (process != null)
{
try
{
process.Kill();
}
catch(Exception)
{
// 정상 종료하면 이쪽 경로로 들어온다.
}
process = null;
}
SendResponse(command, seq, null);
toVSCode.Stop();
}
void Initialize(string command, int seq, dynamic args)
{
SendResponse(command, seq, new Capabilities()
{
supportsConfigurationDoneRequest = true,
supportsFunctionBreakpoints = false,
supportsConditionalBreakpoints = false,
supportsEvaluateForHovers = false,
exceptionBreakpointFilters = new dynamic[0]
});
}
public static string GetFullPath(string fileName)
{
if (File.Exists(fileName))
return Path.GetFullPath(fileName);
var values = Environment.GetEnvironmentVariable("PATH");
foreach (var path in values.Split(Path.PathSeparator))
{
var fullPath = Path.Combine(path, fileName);
if (File.Exists(fullPath))
return fullPath;
}
return null;
}
void Launch(string command, int seq, dynamic args)
{
// 런치 전에 디버기가 접속할 수 있게 포트를 먼저 열어야 한다.
var listener = PrepareForDebuggee(command, seq, args);
string gprojPath = args.gprojPath;
if (gprojPath == null)
{
//--------------------------------
// validate argument 'executable'
var runtimeExecutable = (string)args.executable;
if (runtimeExecutable == null) { runtimeExecutable = ""; }
runtimeExecutable = runtimeExecutable.Trim();
if (runtimeExecutable.Length == 0)
{
SendErrorResponse(command, seq, 3005, "Property 'executable' is empty.");
return;
}
var runtimeExecutableFull = GetFullPath(runtimeExecutable);
if (runtimeExecutableFull == null)
{
SendErrorResponse(command, seq, 3006, "Runtime executable '{path}' does not exist.", new { path = runtimeExecutable });
return;
}
//--------------------------------
if (!ReadBasicConfiguration(command, seq, args)) { return; }
//--------------------------------
var arguments = (string)args.arguments;
if (arguments == null) { arguments = ""; }
// validate argument 'env'
Dictionary<string, string> env = null;
var environmentVariables = args.env;
if (environmentVariables != null)
{
env = new Dictionary<string, string>();
foreach (var entry in environmentVariables)
{
env.Add((string)entry.Name, entry.Value.ToString());
}
if (env.Count == 0)
{
env = null;
}
}
process = new Process();
process.StartInfo.CreateNoWindow = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = true;
process.StartInfo.WorkingDirectory = workingDirectory;
process.StartInfo.FileName = runtimeExecutableFull;
process.StartInfo.Arguments = arguments;
process.EnableRaisingEvents = true;
process.Exited += (object sender, EventArgs e) =>
{
lock (this)
{
toVSCode.SendMessage(new TerminatedEvent());
}
};
if (env != null)
{
foreach (var entry in env)
{
System.Environment.SetEnvironmentVariable(entry.Key, entry.Value);
}
}
var cmd = string.Format("{0} {1}\n", runtimeExecutableFull, arguments);
toVSCode.SendOutput("console", cmd);
try
{
process.Start();
}
catch (Exception e)
{
SendErrorResponse(command, seq, 3012, "Can't launch terminal ({reason}).", new { reason = e.Message });
return;
}
}
else
{
giderosRemoteController = new RemoteController();
var connectStartedAt = DateTime.Now;
bool alreadyLaunched = false;
while (!giderosRemoteController.TryStart("127.0.0.1", 15000, gprojPath, this))
{
if (DateTime.Now - connectStartedAt > TimeSpan.FromSeconds(10))
{
SendErrorResponse(command, seq, 3012, "Can't connect to GiderosPlayer.", new { });
return;
}
else if (alreadyLaunched)
{
System.Threading.Thread.Sleep(100);
}
else
{
try
{
var giderosPath = (string)args.giderosPath;
process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.WorkingDirectory = giderosPath;
// I don't know why this fix keeps GiderosPlayer.exe running
// after DebugAdapter stops.
// And I don't want to know..
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c \"start GiderosPlayer.exe\"";
process.Start();
Program.WaitingUI.SetLabelText(
"Launching " + process.StartInfo.FileName + " " +
process.StartInfo.Arguments + "...");
}
catch (Exception e)
{
SendErrorResponse(command, seq, 3012, "Can't launch GiderosPlayer ({reason}).", new { reason = e.Message });
return;
}
alreadyLaunched = true;
}
}
new System.Threading.Thread(giderosRemoteController.ReadLoop).Start();
}
AcceptDebuggee(command, seq, args, listener);
}
void Attach(string command, int seq, dynamic args)
{
var listener = PrepareForDebuggee(command, seq, args);
AcceptDebuggee(command, seq, args, listener);
}
TcpListener PrepareForDebuggee(string command, int seq, dynamic args)
{
IPAddress listenAddr = (bool)args.listenPublicly
? IPAddress.Any
: IPAddress.Parse("127.0.0.1");
int port = (int)args.listenPort;
listener = new TcpListener(listenAddr, port);
listener.Start();
return listener;
}
void AcceptDebuggee(string command, int seq, dynamic args, TcpListener listener)
{
if (!ReadBasicConfiguration(command, seq, args)) { return; }
var encodingName = (string)args.encoding;
if (encodingName != null)
{
int codepage;
if (int.TryParse(encodingName, out codepage))
{
encoding = Encoding.GetEncoding(codepage);
}
else
{
encoding = Encoding.GetEncoding(encodingName);
}
}
else
{
encoding = Encoding.UTF8;
}
Program.WaitingUI.SetLabelText(
"Waiting for debugee at TCP " +
listener.LocalEndpoint.ToString() + "...");
var ncom = new DebuggeeProtocol(
this,
listener,
encoding);
this.startCommand = command;
this.startSeq = seq;
ncom.StartThread();
}
bool ReadBasicConfiguration(string command, int seq, dynamic args)
{
workingDirectory = (string)args.workingDirectory;
if (workingDirectory == null) { workingDirectory = ""; }
workingDirectory = workingDirectory.Trim();
if (workingDirectory.Length == 0)
{
SendErrorResponse(command, seq, 3003, "Property 'workingDirectory' is empty.");
return false;
}
if (!Directory.Exists(workingDirectory))
{
SendErrorResponse(command, seq, 3004, "Working directory '{path}' does not exist.", new { path = workingDirectory });
return false;
}
if (args.jumpToGiderosErrorPosition != null &&
(bool)args.jumpToGiderosErrorPosition == true)
{
jumpToGiderosErrorPosition = true;
}
if (args.stopGiderosWhenDebuggerStops != null &&
(bool)args.stopGiderosWhenDebuggerStops == true)
{
stopGiderosWhenDebuggerStops = true;
}
if (args.sourceBasePath != null)
{
sourceBasePath = (string)args.sourceBasePath;
}
else
{
sourceBasePath = workingDirectory;
}
return true;
}
void IDebuggeeListener.X_DebuggeeArrived(IDebuggeeSender toDebuggee)
{
lock (this)
{
if (fakeBreakpointMode != null) { return; }
this.toDebuggee = toDebuggee;
Program.WaitingUI.BeginInvoke(new Action(() => {
Program.WaitingUI.Hide();
}));
var welcome = new
{
command = "welcome",
sourceBasePath = sourceBasePath,
directorySeperator = Path.DirectorySeparatorChar,
};
toDebuggee.Send(JsonConvert.SerializeObject(welcome));
SendResponse(startCommand, startSeq, null);
toVSCode.SendMessage(new InitializedEvent());
}
}
void IDebuggeeListener.X_FromDebuggee(byte[] json)
{
lock (this)
{
if (fakeBreakpointMode != null) { return; }
toVSCode.SendJSONEncodedMessage(json);
}
}
void IDebuggeeListener.X_DebuggeeHasGone()
{
System.Threading.Thread.Sleep(500);
lock (this)
{
if (fakeBreakpointMode != null) { return; }
// attach 일 경우 Terminate하지 않고 재시작
if (startCommand == "attach")
{
toDebuggee = null;
Program.WaitingUI.BeginInvoke(new Action(() =>
{
Program.WaitingUI.Show();
}));
listener.Start();
Program.WaitingUI.SetLabelText(
"Waiting for debugee at TCP " +
listener.LocalEndpoint.ToString() + "...");
var ncom = new DebuggeeProtocol(
this,
listener,
encoding);
ncom.StartThread();
}
else
{
toVSCode.SendMessage(new TerminatedEvent());
}
}
}
void IRemoteControllerListener.X_Log(LogType logType, string content)
{
lock (this)
{
switch (logType)
{
case LogType.Info:
toVSCode.SendOutput("console", content);
break;
case LogType.PlayerOutput:
CheckGiderosOutput(content);
// Gideros sends '\n' as seperate packet,
// and VS Code adds linefeed to the end of each output message.
if (content == "\n")
{
bool looksLikeGiderosError = errorMatcher.Match(giderosStdoutBuffer).Success;
toVSCode.SendOutput(
(looksLikeGiderosError ? "stderr" : "stdout"),
giderosStdoutBuffer);
giderosStdoutBuffer = "";
}
else
{
giderosStdoutBuffer += content;
}
break;
case LogType.Warning:
toVSCode.SendOutput("stderr", content);
break;
}
}
}
protected static readonly Regex errorMatcher = new Regex(@"^([^:\n\r]+):(\d+): ");
void CheckGiderosOutput(string content)
{
Match m = errorMatcher.Match(content);
if (!m.Success) { return; }
if (jumpToGiderosErrorPosition)
{
// Entering fake breakpoint mode:
string file = m.Groups[1].ToString();
int line = int.Parse(m.Groups[2].ToString());
this.fakeBreakpointMode = new Tuple<string, int>(file, line);
if (startCommand != null)
{
SendResponse(startCommand, startSeq, null);
toVSCode.SendMessage(new InitializedEvent());
startCommand = null;
}
toVSCode.SendMessage(new StoppedEvent(999, "error"));
}
}
}
}