forked from godotengine/godot-vscode-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_controller.ts
639 lines (552 loc) · 17.9 KB
/
server_controller.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
import { StoppedEvent, TerminatedEvent } from "@vscode/debugadapter";
import { DebugProtocol } from "@vscode/debugprotocol";
import * as fs from "node:fs";
import * as net from "node:net";
import { debug, window } from "vscode";
import {
ansi,
convert_resource_path_to_uri,
createLogger,
get_configuration,
get_free_port,
get_project_version,
verify_godot_version,
VERIFY_RESULT,
} from "../../utils";
import { prompt_for_godot_executable } from "../../utils/prompts";
import { killSubProcesses, subProcess } from "../../utils/subspawn";
import { GodotStackFrame, GodotStackVars } from "../debug_runtime";
import { AttachRequestArguments, LaunchRequestArguments, pinnedScene } from "../debugger";
import { GodotDebugSession } from "./debug_session";
import { build_sub_values, parse_next_scene_node, split_buffers } from "./helpers";
import { VariantDecoder } from "./variables/variant_decoder";
import { VariantEncoder } from "./variables/variant_encoder";
import { RawObject } from "./variables/variants";
import BBCodeToAnsi from 'bbcode-to-ansi';
const log = createLogger("debugger.controller", { output: "Godot Debugger" });
const socketLog = createLogger("debugger.socket");
//initialize bbcodeParser and set default output color to grey
const bbcodeParser = new BBCodeToAnsi("\u001b[38;2;211;211;211m");
class Command {
public command: string = "";
public paramCount: number = -1;
public parameters: any[] = [];
public complete: boolean = false;
public threadId: number = 0;
}
export class ServerController {
private commandBuffer: Buffer[] = [];
private encoder = new VariantEncoder();
private decoder = new VariantDecoder();
private draining = false;
private exception = "";
private server?: net.Server;
private socket?: net.Socket;
private steppingOut = false;
private currentCommand: Command = undefined;
private didFirstOutput: boolean = false;
private connectedVersion = "";
public constructor(public session: GodotDebugSession) {}
public break() {
this.send_command("break");
}
public continue() {
this.send_command("continue");
}
public next() {
this.send_command("next");
}
public step() {
this.send_command("step");
}
public step_out() {
this.steppingOut = true;
this.send_command("next");
}
public set_breakpoint(path_to: string, line: number) {
this.send_command("breakpoint", [path_to, line, true]);
}
public remove_breakpoint(path_to: string, line: number) {
this.session.debug_data.remove_breakpoint(path_to, line);
this.send_command("breakpoint", [path_to, line, false]);
}
public request_inspect_object(object_id: bigint) {
this.send_command("inspect_object", [object_id]);
}
public request_scene_tree() {
this.send_command("request_scene_tree");
}
public request_stack_dump() {
this.send_command("get_stack_dump");
}
public request_stack_frame_vars(frame_id: number) {
this.send_command("get_stack_frame_vars", [frame_id]);
}
public set_object_property(objectId: bigint, label: string, newParsedValue) {
this.send_command("set_object_property", [objectId, label, newParsedValue]);
}
public set_exception(exception: string) {
this.exception = exception;
}
private async start_game(args: LaunchRequestArguments) {
log.info("Starting game process");
let godotPath: string;
let result: VERIFY_RESULT;
if (args.editor_path) {
log.info("Using 'editor_path' variable from launch.json");
log.info(`Verifying version of '${args.editor_path}'`);
result = verify_godot_version(args.editor_path, "3");
godotPath = result.godotPath;
log.info(`Verification result: ${result.status}, version: "${result.version}"`);
switch (result.status) {
case "WRONG_VERSION": {
const projectVersion = await get_project_version();
const message = `Cannot launch debug session: The current project uses Godot v${projectVersion}, but the specified Godot executable is v${result.version}`;
log.warn(message);
window.showErrorMessage(message, "Ok");
this.abort();
return;
}
case "INVALID_EXE": {
const message = `Cannot launch debug session: '${godotPath}' is not a valid Godot executable`;
log.warn(message);
window.showErrorMessage(message, "Ok");
this.abort();
return;
}
default: {
break;
}
}
} else {
log.info("Using 'editorPath.godot3' from settings");
const settingName = "editorPath.godot3";
godotPath = get_configuration(settingName);
log.info(`Verifying version of '${godotPath}'`);
result = verify_godot_version(godotPath, "3");
godotPath = result.godotPath;
log.info(`Verification result: ${result.status}, version: "${result.version}"`);
switch (result.status) {
case "WRONG_VERSION": {
const projectVersion = await get_project_version();
const message = `Cannot launch debug session: The current project uses Godot v${projectVersion}, but the specified Godot executable is v${result.version}`;
log.warn(message);
prompt_for_godot_executable(message, settingName);
this.abort();
return;
}
case "INVALID_EXE": {
const message = `Cannot launch debug session: '${godotPath}' is not a valid Godot executable`;
log.warn(message);
prompt_for_godot_executable(message, settingName);
this.abort();
return;
}
}
}
this.connectedVersion = result.version;
let command = `"${godotPath}" --path "${args.project}"`;
const address = args.address.replace("tcp://", "");
command += ` --remote-debug "${address}:${args.port}"`;
if (args.profiling) command += " --profiling";
if (args.debug_collisions) command += " --debug-collisions";
if (args.debug_paths) command += " --debug-paths";
if (args.frame_delay) command += ` --frame-delay ${args.frame_delay}`;
if (args.time_scale) command += ` --time-scale ${args.time_scale}`;
if (args.fixed_fps) command += ` --fixed-fps ${args.fixed_fps}`;
if (args.scene && args.scene !== "main") {
log.info(`Custom scene argument provided: ${args.scene}`);
let filename = args.scene;
if (args.scene === "current") {
let path = window.activeTextEditor.document.fileName;
if (path.endsWith(".gd")) {
path = path.replace(".gd", ".tscn");
if (!fs.existsSync(path)) {
const message = `Can't find associated scene file for ${path}`;
log.warn(message);
window.showErrorMessage(message, "Ok");
this.abort();
return;
}
}
filename = path;
}
if (args.scene === "pinned") {
if (!pinnedScene) {
const message = "No pinned scene found";
log.warn(message);
window.showErrorMessage(message, "Ok");
this.abort();
return;
}
let path = pinnedScene.fsPath;
if (path.endsWith(".gd")) {
path = path.replace(".gd", ".tscn");
if (!fs.existsSync(path)) {
const message = `Can't find associated scene file for ${path}`;
log.warn(message);
window.showErrorMessage(message, "Ok");
this.abort();
return;
}
}
filename = path;
}
command += ` "${filename}"`;
}
command += this.session.debug_data.get_breakpoint_string();
if (args.additional_options) {
command += ` ${args.additional_options}`;
}
log.info(`Launching game process using command: '${command}'`);
const debugProcess = subProcess("debug", command, { shell: true, detached: true });
debugProcess.stdout.on("data", (data) => {});
debugProcess.stderr.on("data", (data) => {});
debugProcess.on("close", (code) => {});
}
private stash: Buffer;
private on_data(buffer: Buffer) {
if (this.stash) {
buffer = Buffer.concat([this.stash, buffer]);
this.stash = undefined;
}
const buffers = split_buffers(buffer);
while (buffers.length > 0) {
const chunk = buffers.shift();
const data = this.decoder.get_dataset(chunk)?.slice(1);
if (data === undefined) {
this.stash = Buffer.alloc(chunk.length);
chunk.copy(this.stash);
return;
}
this.parse_message(data);
}
}
public async launch(args: LaunchRequestArguments) {
log.info("Starting debug controller in 'launch' mode");
this.server = net.createServer((socket) => {
this.socket = socket;
socket.on("data", this.on_data.bind(this));
socket.on("close", (had_error) => {
// log.debug("socket close");
this.abort();
});
socket.on("end", () => {
// log.debug("socket end");
this.abort();
});
socket.on("error", (error) => {
// log.debug("socket error");
// this.session.sendEvent(new TerminatedEvent());
// this.stop();
});
socket.on("drain", () => {
// log.debug("socket drain");
socket.resume();
this.draining = false;
this.send_buffer();
});
});
if (args.port === -1) {
args.port = await get_free_port();
}
this.server.listen(args.port, args.address);
this.start_game(args);
}
public async attach(args: AttachRequestArguments) {
log.info("Starting debug controller in 'attach' mode");
this.server = net.createServer((socket) => {
this.socket = socket;
socket.on("data", this.on_data.bind(this));
socket.on("close", (had_error) => {
// log.debug("socket close");
// this.session.sendEvent(new TerminatedEvent());
// this.stop();
});
socket.on("end", () => {
// log.debug("socket end");
// this.session.sendEvent(new TerminatedEvent());
// this.stop();
});
socket.on("error", (error) => {
// log.error("socket error", error);
});
socket.on("drain", () => {
// log.debug("socket drain");
socket.resume();
this.draining = false;
this.send_buffer();
});
});
this.server.listen(args.port, args.address);
}
private parse_message(dataset: any[]) {
if (!this.currentCommand || this.currentCommand.complete) {
this.currentCommand = new Command();
this.currentCommand.command = dataset.shift();
}
while (dataset && dataset.length > 0) {
if (this.currentCommand.paramCount === -1) {
this.currentCommand.paramCount = dataset.shift();
} else {
this.currentCommand.parameters.push(dataset.shift());
}
if (this.currentCommand.paramCount === this.currentCommand.parameters.length) {
this.currentCommand.complete = true;
}
}
if (this.currentCommand.complete) {
socketLog.debug("rx:", [this.currentCommand.command, ...this.currentCommand.parameters]);
this.handle_command(this.currentCommand);
}
}
private async handle_command(command: Command) {
switch (command.command) {
case "debug_enter": {
const reason: string = command.parameters[1];
if (reason !== "Breakpoint") {
this.set_exception(reason);
} else {
this.set_exception("");
}
this.request_stack_dump();
break;
}
case "debug_exit":
break;
case "message:click_ctrl":
// TODO: what is this?
break;
case "performance":
// TODO: what is this?
break;
case "message:scene_tree": {
const tree = parse_next_scene_node(command.parameters);
this.session.sceneTree.fill_tree(tree);
break;
}
case "message:inspect_object": {
let id = BigInt(command.parameters[0]);
const className: string = command.parameters[1];
const properties: string[] = command.parameters[2];
// message:inspect_object returns the id as an unsigned 64 bit integer, but it is decoded as a signed 64 bit integer,
// thus we need to convert it to its equivalent unsigned value here.
if (id < 0) {
id = id + BigInt(2) ** BigInt(64);
}
const rawObject = new RawObject(className);
for (const prop of properties) {
rawObject.set(prop[0], prop[5]);
}
const inspectedVariable = { name: "", value: rawObject };
build_sub_values(inspectedVariable);
if (this.session.inspect_callbacks.has(BigInt(id))) {
this.session.inspect_callbacks.get(BigInt(id))(inspectedVariable.name, inspectedVariable);
this.session.inspect_callbacks.delete(BigInt(id));
}
this.session.set_inspection(id, inspectedVariable);
break;
}
case "stack_dump": {
const frames: GodotStackFrame[] = command.parameters.map((sf, i) => {
return {
id: i,
file: sf.get("file"),
function: sf.get("function"),
line: sf.get("line"),
};
});
this.trigger_breakpoint(frames);
this.request_scene_tree();
break;
}
case "stack_frame_vars": {
this.do_stack_frame_vars(command.parameters);
break;
}
case "output": {
if (!this.didFirstOutput) {
this.didFirstOutput = true;
// this.request_scene_tree();
}
for (const output of command.parameters){
output[0].split("\n").forEach(line => debug.activeDebugConsole.appendLine(bbcodeParser.parse(line)));
}
break;
}
case "error": {
if (!this.didFirstOutput) {
this.didFirstOutput = true;
}
this.handle_error(command);
break;
}
}
}
async handle_error(command: Command) {
const params = command.parameters[0];
const e = {
hr: params[0],
min: params[1],
sec: params[2],
msec: params[3],
func: params[4] as string,
file: params[5] as string,
line: params[6],
cond: params[7] as string,
msg: params[8] as string,
warning: params[9] as boolean,
stack: [],
};
const stackCount = command.parameters[1];
for (let i = 0; i < stackCount; i += 3) {
const file = command.parameters[i + 2];
const func = command.parameters[i + 3];
const line = command.parameters[i + 4];
const msg = `${file}:${line} @ ${func}()`;
const extras = {
source: { name: (await convert_resource_path_to_uri(file)).toString() },
line: line,
};
e.stack.push({ msg: msg, extras: extras });
}
const time = `${e.hr}:${e.min}:${e.sec}.${e.msec}`;
const location = `${e.file}:${e.line} @ ${e.func}()`;
const color = e.warning ? "yellow" : "red";
const lang = e.file.startsWith("res://") ? "GDScript" : "C++";
const extras = {
source: { name: (await convert_resource_path_to_uri(e.file)).toString() },
line: e.line,
group: "startCollapsed",
};
if (e.msg) {
this.stderr(`${ansi[color]}${time} | ${e.func}: ${e.msg}`, extras);
this.stderr(`${ansi.dim.white}<${lang} Error> ${ansi.white}${e.cond}`);
} else {
this.stderr(`${ansi[color]}${time} | ${e.func}: ${e.cond}`, extras);
}
this.stderr(`${ansi.dim.white}<${lang} Source> ${ansi.white}${location}`);
if (stackCount !== 0) {
this.stderr(`${ansi.dim.white}<Stack Trace>`, { group: "start" });
for (const frame of e.stack) {
this.stderr(`${ansi.white}${frame.msg}`, frame.extras);
}
this.stderr("", { group: "end" });
}
this.stderr("", { group: "end" });
}
stdout(output = "", extra = {}) {
this.session.sendEvent({
event: "output",
body: {
category: "stdout",
output: output + ansi.reset,
...extra,
},
} as DebugProtocol.OutputEvent);
}
stderr(output = "", extra = {}) {
this.session.sendEvent({
event: "output",
body: {
category: "stderr",
output: output + ansi.reset,
...extra,
},
} as DebugProtocol.OutputEvent);
}
public abort() {
log.info("Aborting debug controller");
this.session.sendEvent(new TerminatedEvent());
this.stop();
}
public stop() {
log.info("Stopping debug controller");
killSubProcesses("debug");
this.socket?.destroy();
this.server?.close((error) => {
if (error) {
log.error(error);
}
this.server.unref();
this.server = undefined;
});
}
public trigger_breakpoint(stackFrames: GodotStackFrame[]) {
let continueStepping = false;
const stackCount = stackFrames.length;
if (stackCount === 0) {
// Engine code is being executed, no user stack trace
this.session.debug_data.last_frames = [];
this.session.sendEvent(new StoppedEvent("breakpoint", 0));
return;
}
const file = stackFrames[0].file.replace("res://", `${this.session.debug_data.projectPath}/`);
const line = stackFrames[0].line;
if (this.steppingOut) {
const breakpoint = this.session.debug_data.get_breakpoints(file).find((bp) => bp.line === line);
if (!breakpoint) {
if (this.session.debug_data.stack_count > 1) {
continueStepping = this.session.debug_data.stack_count === stackCount;
} else {
const fileSame = stackFrames[0].file === this.session.debug_data.last_frame.file;
const funcSame = stackFrames[0].function === this.session.debug_data.last_frame.function;
const lineGreater = stackFrames[0].line >= this.session.debug_data.last_frame.line;
continueStepping = fileSame && funcSame && lineGreater;
}
}
}
this.session.debug_data.stack_count = stackCount;
this.session.debug_data.last_frame = stackFrames[0];
this.session.debug_data.last_frames = stackFrames;
if (continueStepping) {
this.next();
return;
}
this.steppingOut = false;
this.session.debug_data.stack_files = stackFrames.map((sf) => {
return sf.file;
});
if (this.exception.length === 0) {
this.session.sendEvent(new StoppedEvent("breakpoint", 0));
} else {
this.session.sendEvent(new StoppedEvent("exception", 0, this.exception));
}
}
private send_command(command: string, parameters: any[] = []) {
const commandArray: any[] = [command, ...parameters];
socketLog.debug("tx:", commandArray);
const buffer = this.encoder.encode_variant(commandArray);
this.commandBuffer.push(buffer);
this.send_buffer();
}
private send_buffer() {
if (!this.socket) {
return;
}
while (!this.draining && this.commandBuffer.length > 0) {
const command = this.commandBuffer.shift();
this.draining = !this.socket.write(command);
}
}
private do_stack_frame_vars(parameters: any[]) {
const stackVars = new GodotStackVars();
let localsRemaining = parameters[0];
let membersRemaining = parameters[1 + localsRemaining * 2];
let globalsRemaining = parameters[2 + (localsRemaining + membersRemaining) * 2];
let i = 1;
while (localsRemaining--) {
stackVars.locals.push({ name: parameters[i++], value: parameters[i++] });
}
i++;
while (membersRemaining--) {
stackVars.members.push({ name: parameters[i++], value: parameters[i++] });
}
i++;
while (globalsRemaining--) {
stackVars.globals.push({ name: parameters[i++], value: parameters[i++] });
}
stackVars.forEach((item) => build_sub_values(item));
this.session.set_scopes(stackVars);
}
}