Debian Codegraph @

core/debugger/remote_debugger.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* remote_debugger.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "remote_debugger.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/debugger/debugger_marshalls.h"
35 #include "core/debugger/engine_debugger.h"
36 #include "core/debugger/engine_profiler.h"
37 #include "core/debugger/script_debugger.h"
38 #include "core/input/input.h"
39 #include "core/io/resource_loader.h"
40 #include "core/math/expression.h"
41 #include "core/object/script_language.h"
42 #include "core/os/os.h"
43 #include "servers/display/display_server.h"
44
45 class RemoteDebugger::PerformanceProfiler : public EngineProfiler {
46 Object *performance = nullptr;
47 int last_perf_time = 0;
48 uint64_t last_monitor_modification_time = 0;
49
50 public:
51 void toggle(bool p_enable, const Array &p_opts) override {}
52 void add(const Array &p_data) override {}
53 void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) override {
54 if (!performance) {
55 return;
56 }
57
58 uint64_t pt = OS::get_singleton()->get_ticks_msec();
59 if (pt - last_perf_time < 1000) {
60 return;
61 }
62 last_perf_time = pt;
63
64 Array custom_monitor_names = performance->call("get_custom_monitor_names");
65 Array custom_monitor_types = performance->call("get_custom_monitor_types");
66
67 Array custom_monitor_data;
68 custom_monitor_data.push_back(custom_monitor_names);
69 custom_monitor_data.push_back(custom_monitor_types);
70
71 uint64_t monitor_modification_time = performance->call("get_monitor_modification_time");
72 if (monitor_modification_time > last_monitor_modification_time) {
73 last_monitor_modification_time = monitor_modification_time;
74 EngineDebugger::get_singleton()->send_message("performance:profile_names", custom_monitor_data);
75 }
76
77 int max = performance->get("MONITOR_MAX");
78 Array arr;
79 arr.resize(max + custom_monitor_names.size());
80 for (int i = 0; i < max; i++) {
81 arr[i] = performance->call("get_monitor", i);
82 }
83
84 for (int i = 0; i < custom_monitor_names.size(); i++) {
85 Variant monitor_value = performance->call("get_custom_monitor", custom_monitor_names[i]);
86 if (!monitor_value.is_num()) {
87 ERR_PRINT(vformat("Value of custom monitor '%s' is not a number.", String(custom_monitor_names[i])));
88 arr[i + max] = Variant();
89 } else {
90 arr[i + max] = monitor_value;
91 }
92 }
93
94 EngineDebugger::get_singleton()->send_message("performance:profile_frame", arr);
95 }
96
97 explicit PerformanceProfiler(Object *p_performance) {
98 performance = p_performance;
99 }
100 };
101
102 Error RemoteDebugger::_put_msg(const String &p_message, const Array &p_data) {
103 Array msg = { p_message, Thread::get_caller_id(), p_data };
104 Error err = peer->put_message(msg);
105 if (err != OK) {
106 n_messages_dropped++;
107 }
108 return err;
109 }
110
111 void RemoteDebugger::_err_handler(void *p_this, const char *p_func, const char *p_file, int p_line, const char *p_err, const char *p_descr, bool p_editor_notify, ErrorHandlerType p_type) {
112 RemoteDebugger *rd = static_cast<RemoteDebugger *>(p_this);
113 if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive errors during flush.
114 return;
115 }
116
117 Vector<ScriptLanguage::StackInfo> si;
118
119 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
120 si = ScriptServer::get_language(i)->debug_get_current_stack_info();
121 if (si.size()) {
122 break;
123 }
124 }
125
126 // send_error will lock internally.
127 rd->script_debugger->send_error(String::utf8(p_func), String::utf8(p_file), p_line, String::utf8(p_err), String::utf8(p_descr), p_editor_notify, p_type, si);
128 }
129
130 void RemoteDebugger::_print_handler(void *p_this, const String &p_string, bool p_error, bool p_rich) {
131 RemoteDebugger *rd = static_cast<RemoteDebugger *>(p_this);
132
133 if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive prints during flush.
134 return;
135 }
136
137 String s = p_string;
138 int allowed_chars = MIN(MAX(rd->max_chars_per_second - rd->char_count, 0), s.length());
139
140 if (allowed_chars == 0 && s.length() > 0) {
141 return;
142 }
143
144 if (allowed_chars < s.length()) {
145 s = s.substr(0, allowed_chars);
146 }
147
148 MutexLock lock(rd->mutex);
149
150 rd->char_count += allowed_chars;
151 bool overflowed = rd->char_count >= rd->max_chars_per_second;
152 if (rd->is_peer_connected()) {
153 if (overflowed) {
154 s += "[...]";
155 }
156
157 OutputString output_string;
158 output_string.message = s;
159 if (p_error) {
160 output_string.type = MESSAGE_TYPE_ERROR;
161 } else if (p_rich) {
162 output_string.type = MESSAGE_TYPE_LOG_RICH;
163 } else {
164 output_string.type = MESSAGE_TYPE_LOG;
165 }
166 rd->output_strings.push_back(output_string);
167
168 if (overflowed) {
169 output_string.message = "[output overflow, print less text!]";
170 output_string.type = MESSAGE_TYPE_ERROR;
171 rd->output_strings.push_back(output_string);
172 }
173 }
174 }
175
176 RemoteDebugger::ErrorMessage RemoteDebugger::_create_overflow_error(const String &p_what, const String &p_descr) {
177 ErrorMessage oe;
178 oe.error = p_what;
179 oe.error_descr = p_descr;
180 oe.warning = false;
181 uint64_t time = OS::get_singleton()->get_ticks_msec();
182 oe.hr = time / 3600000;
183 oe.min = (time / 60000) % 60;
184 oe.sec = (time / 1000) % 60;
185 oe.msec = time % 1000;
186 return oe;
187 }
188
189 void RemoteDebugger::flush_output() {
190 MutexLock lock(mutex);
191 flush_thread = Thread::get_caller_id();
192 flushing = true;
193 if (!is_peer_connected()) {
194 return;
195 }
196
197 if (n_messages_dropped > 0) {
198 ErrorMessage err_msg = _create_overflow_error("TOO_MANY_MESSAGES", "Too many messages! " + String::num_int64(n_messages_dropped) + " messages were dropped. Profiling might misbheave, try raising 'network/limits/debugger/max_queued_messages' in project setting.");
199 if (_put_msg("error", err_msg.serialize()) == OK) {
200 n_messages_dropped = 0;
201 }
202 }
203
204 if (output_strings.size()) {
205 // Join output strings so we generate less messages.
206 Vector<String> joined_log_strings;
207 Vector<String> strings;
208 Vector<int> types;
209 for (const OutputString &output_string : output_strings) {
210 if (output_string.type == MESSAGE_TYPE_ERROR) {
211 if (!joined_log_strings.is_empty()) {
212 strings.push_back(String("\n").join(joined_log_strings));
213 types.push_back(MESSAGE_TYPE_LOG);
214 joined_log_strings.clear();
215 }
216 strings.push_back(output_string.message);
217 types.push_back(MESSAGE_TYPE_ERROR);
218 } else if (output_string.type == MESSAGE_TYPE_LOG_RICH) {
219 if (!joined_log_strings.is_empty()) {
220 strings.push_back(String("\n").join(joined_log_strings));
221 types.push_back(MESSAGE_TYPE_LOG_RICH);
222 joined_log_strings.clear();
223 }
224 strings.push_back(output_string.message);
225 types.push_back(MESSAGE_TYPE_LOG_RICH);
226 } else {
227 joined_log_strings.push_back(output_string.message);
228 }
229 }
230
231 if (!joined_log_strings.is_empty()) {
232 strings.push_back(String("\n").join(joined_log_strings));
233 types.push_back(MESSAGE_TYPE_LOG);
234 }
235
236 Array arr = { strings, types };
237 _put_msg("output", arr);
238 output_strings.clear();
239 }
240
241 while (errors.size()) {
242 ErrorMessage oe = errors.front()->get();
243 _put_msg("error", oe.serialize());
244 errors.pop_front();
245 }
246
247 // Update limits
248 uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
249
250 if (ticks - last_reset > 1000) {
251 last_reset = ticks;
252 char_count = 0;
253 err_count = 0;
254 n_errors_dropped = 0;
255 warn_count = 0;
256 n_warnings_dropped = 0;
257 }
258 flushing = false;
259 }
260
261 void RemoteDebugger::send_message(const String &p_message, const Array &p_args) {
262 MutexLock lock(mutex);
263 if (is_peer_connected()) {
264 _put_msg(p_message, p_args);
265 }
266 }
267
268 void RemoteDebugger::send_error(const String &p_func, const String &p_file, int p_line, const String &p_err, const String &p_descr, bool p_editor_notify, ErrorHandlerType p_type) {
269 ErrorMessage oe;
270 oe.error = p_err;
271 oe.error_descr = p_descr;
272 oe.source_file = p_file;
273 oe.source_line = p_line;
274 oe.source_func = p_func;
275 oe.warning = p_type == ERR_HANDLER_WARNING;
276 uint64_t time = OS::get_singleton()->get_ticks_msec();
277 oe.hr = time / 3600000;
278 oe.min = (time / 60000) % 60;
279 oe.sec = (time / 1000) % 60;
280 oe.msec = time % 1000;
281 oe.callstack.append_array(script_debugger->get_error_stack_info());
282
283 if (flushing && Thread::get_caller_id() == flush_thread) { // Can't handle recursive errors during flush.
284 return;
285 }
286
287 MutexLock lock(mutex);
288
289 if (oe.warning) {
290 warn_count++;
291 } else {
292 err_count++;
293 }
294
295 if (is_peer_connected()) {
296 if (oe.warning) {
297 if (warn_count > max_warnings_per_second) {
298 n_warnings_dropped++;
299 if (n_warnings_dropped == 1) {
300 // Only print one message about dropping per second
301 ErrorMessage overflow = _create_overflow_error("TOO_MANY_WARNINGS", "Too many warnings! Ignoring warnings for up to 1 second.");
302 errors.push_back(overflow);
303 }
304 } else {
305 errors.push_back(oe);
306 }
307 } else {
308 if (err_count > max_errors_per_second) {
309 n_errors_dropped++;
310 if (n_errors_dropped == 1) {
311 // Only print one message about dropping per second
312 ErrorMessage overflow = _create_overflow_error("TOO_MANY_ERRORS", "Too many errors! Ignoring errors for up to 1 second.");
313 errors.push_back(overflow);
314 }
315 } else {
316 errors.push_back(oe);
317 }
318 }
319 }
320 }
321
322 void RemoteDebugger::_send_stack_vars(List<String> &p_names, List<Variant> &p_vals, int p_type) {
323 DebuggerMarshalls::ScriptStackVariable stvar;
324 List<String>::Element *E = p_names.front();
325 List<Variant>::Element *F = p_vals.front();
326 while (E) {
327 stvar.name = E->get();
328 stvar.value = F->get();
329 stvar.type = p_type;
330 send_message("stack_frame_var", stvar.serialize());
331 E = E->next();
332 F = F->next();
333 }
334 }
335
336 Error RemoteDebugger::_try_capture(const String &p_msg, const Array &p_data, bool &r_captured) {
337 const int idx = p_msg.find_char(':');
338 r_captured = false;
339 if (idx < 0) { // No prefix, unknown message.
340 return OK;
341 }
342 const String cap = p_msg.substr(0, idx);
343 if (!has_capture(cap)) {
344 return ERR_UNAVAILABLE; // Unknown message...
345 }
346 const String msg = p_msg.substr(idx + 1);
347 return capture_parse(cap, msg, p_data, r_captured);
348 }
349
350 void RemoteDebugger::_poll_messages() {
351 MutexLock mutex_lock(mutex);
352
353 peer->poll();
354 while (peer->has_message()) {
355 Array cmd = peer->get_message();
356 ERR_CONTINUE(cmd.size() != 3);
357 ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
358 ERR_CONTINUE(cmd[1].get_type() != Variant::INT);
359 ERR_CONTINUE(cmd[2].get_type() != Variant::ARRAY);
360
361 Thread::ID thread = cmd[1];
362
363 if (!messages.has(thread)) {
364 continue; // This thread is not around to receive the messages
365 }
366
367 Message msg;
368 msg.message = cmd[0];
369 msg.data = cmd[2];
370 messages[thread].push_back(msg);
371 }
372 }
373
374 bool RemoteDebugger::_has_messages() {
375 MutexLock mutex_lock(mutex);
376 return messages.has(Thread::get_caller_id()) && !messages[Thread::get_caller_id()].is_empty();
377 }
378
379 Array RemoteDebugger::_get_message() {
380 MutexLock mutex_lock(mutex);
381 ERR_FAIL_COND_V(!messages.has(Thread::get_caller_id()), Array());
382 List<Message> &message_list = messages[Thread::get_caller_id()];
383 ERR_FAIL_COND_V(message_list.is_empty(), Array());
384
385 Array msg;
386 msg.resize(2);
387 msg[0] = message_list.front()->get().message;
388 msg[1] = message_list.front()->get().data;
389 message_list.pop_front();
390 return msg;
391 }
392
393 void RemoteDebugger::debug(bool p_can_continue, bool p_is_error_breakpoint) {
394 //this function is called when there is a debugger break (bug on script)
395 //or when execution is paused from editor
396
397 {
398 MutexLock lock(mutex);
399 // Tests that require mutex.
400 if (script_debugger->is_skipping_breakpoints() && !p_is_error_breakpoint) {
401 return;
402 }
403
404 if (script_debugger->is_ignoring_error_breaks() && p_is_error_breakpoint) {
405 return;
406 }
407
408 ERR_FAIL_COND_MSG(!is_peer_connected(), "Script Debugger failed to connect, but being used anyway.");
409
410 if (!peer->can_block()) {
411 return; // Peer does not support blocking IO. We could at least send the error though.
412 }
413
414 threads_in_break.insert(Thread::get_caller_id());
415 }
416
417 ScriptLanguage *script_lang = script_debugger->get_break_language();
418 Array msg = {
419 p_can_continue,
420 script_lang ? script_lang->debug_get_error() : String(),
421 script_lang && (script_lang->debug_get_stack_level_count() > 0),
422 Thread::get_caller_id()
423 };
424 if (allow_focus_steal_fn) {
425 allow_focus_steal_fn();
426 }
427 send_message("debug_enter", msg);
428
429 Input::MouseMode mouse_mode = Input::MOUSE_MODE_VISIBLE;
430
431 if (Thread::is_main_thread()) {
432 mouse_mode = Input::get_singleton()->get_mouse_mode();
433 if (mouse_mode != Input::MOUSE_MODE_VISIBLE) {
434 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
435 }
436 } else {
437 MutexLock mutex_lock(mutex);
438 messages.insert(Thread::get_caller_id(), List<Message>());
439 }
440
441 while (is_peer_connected()) {
442 flush_output();
443
444 _poll_messages();
445
446 if (_has_messages()) {
447 Array cmd = _get_message();
448
449 ERR_CONTINUE(cmd.size() != 2);
450 ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
451 ERR_CONTINUE(cmd[1].get_type() != Variant::ARRAY);
452
453 String command = cmd[0];
454 Array data = cmd[1];
455
456 if (command == "step") {
457 script_debugger->set_depth(-1);
458 script_debugger->set_lines_left(1);
459 break;
460
461 } else if (command == "next") {
462 script_debugger->set_depth(0);
463 script_debugger->set_lines_left(1);
464 break;
465
466 } else if (command == "out") {
467 script_debugger->set_depth(1);
468 script_debugger->set_lines_left(1);
469 break;
470
471 } else if (command == "continue") {
472 script_debugger->set_depth(-1);
473 script_debugger->set_lines_left(-1);
474 break;
475
476 } else if (command == "break") {
477 ERR_PRINT("Got break when already broke!");
478 break;
479
480 } else if (command == "get_stack_dump") {
481 DebuggerMarshalls::ScriptStackDump dump;
482 if (script_lang) {
483 int slc = script_lang->debug_get_stack_level_count();
484 for (int i = 0; i < slc; i++) {
485 ScriptLanguage::StackInfo frame;
486 frame.file = script_lang->debug_get_stack_level_source(i);
487 frame.line = script_lang->debug_get_stack_level_line(i);
488 frame.func = script_lang->debug_get_stack_level_function(i);
489 dump.frames.push_back(frame);
490 }
491 }
492 send_message("stack_dump", dump.serialize());
493
494 } else if (command == "get_stack_frame_vars") {
495 ERR_FAIL_COND(data.size() != 1);
496 if (!script_lang) {
497 send_message("stack_frame_vars", Array{ 0 });
498 continue;
499 }
500 int lv = data[0];
501
502 List<String> members;
503 List<Variant> member_vals;
504 if (ScriptInstance *inst = script_lang->debug_get_stack_level_instance(lv)) {
505 members.push_back("self");
506 member_vals.push_back(inst->get_owner());
507 }
508 script_lang->debug_get_stack_level_members(lv, &members, &member_vals);
509 ERR_FAIL_COND(members.size() != member_vals.size());
510
511 List<String> locals;
512 List<Variant> local_vals;
513 script_lang->debug_get_stack_level_locals(lv, &locals, &local_vals);
514 ERR_FAIL_COND(locals.size() != local_vals.size());
515
516 List<String> globals;
517 List<Variant> globals_vals;
518 script_lang->debug_get_globals(&globals, &globals_vals);
519 ERR_FAIL_COND(globals.size() != globals_vals.size());
520
521 Array var_size = { local_vals.size() + member_vals.size() + globals_vals.size() };
522 send_message("stack_frame_vars", var_size);
523 _send_stack_vars(locals, local_vals, 0);
524 _send_stack_vars(members, member_vals, 1);
525 _send_stack_vars(globals, globals_vals, 2);
526
527 } else if (command == "reload_scripts") {
528 script_paths_to_reload = data;
529 } else if (command == "reload_all_scripts") {
530 reload_all_scripts = true;
531 } else if (command == "breakpoint") {
532 ERR_FAIL_COND(data.size() < 3);
533 bool set = data[2];
534 if (set) {
535 script_debugger->insert_breakpoint(data[1], data[0]);
536 } else {
537 script_debugger->remove_breakpoint(data[1], data[0]);
538 }
539
540 } else if (command == "set_skip_breakpoints") {
541 ERR_FAIL_COND(data.is_empty());
542 script_debugger->set_skip_breakpoints(data[0]);
543 } else if (command == "set_ignore_error_breaks") {
544 ERR_FAIL_COND(data.is_empty());
545 script_debugger->set_ignore_error_breaks(data[0]);
546 } else if (command == "evaluate") {
547 String expression_str = data[0];
548 int frame = data[1];
549
550 ScriptInstance *breaked_instance = script_debugger->get_break_language()->debug_get_stack_level_instance(frame);
551 if (!breaked_instance) {
552 break;
553 }
554
555 PackedStringArray input_names;
556 Array input_vals;
557
558 List<String> locals;
559 List<Variant> local_vals;
560 script_debugger->get_break_language()->debug_get_stack_level_locals(frame, &locals, &local_vals);
561 ERR_FAIL_COND(locals.size() != local_vals.size());
562
563 for (const String &S : locals) {
564 input_names.append(S);
565 }
566
567 for (const Variant &V : local_vals) {
568 input_vals.append(V);
569 }
570
571 List<String> globals;
572 List<Variant> globals_vals;
573 script_debugger->get_break_language()->debug_get_globals(&globals, &globals_vals);
574 ERR_FAIL_COND(globals.size() != globals_vals.size());
575
576 for (const String &S : globals) {
577 input_names.append(S);
578 }
579
580 for (const Variant &V : globals_vals) {
581 input_vals.append(V);
582 }
583
584 LocalVector<StringName> native_types;
585 ClassDB::get_class_list(native_types);
586 for (const StringName &class_name : native_types) {
587 if (!ClassDB::is_class_exposed(class_name) || !Engine::get_singleton()->has_singleton(class_name) || Engine::get_singleton()->is_singleton_editor_only(class_name)) {
588 continue;
589 }
590
591 input_names.append(class_name);
592 input_vals.append(Engine::get_singleton()->get_singleton_object(class_name));
593 }
594
595 LocalVector<StringName> user_types;
596 ScriptServer::get_global_class_list(user_types);
597 for (const StringName &class_name : user_types) {
598 String scr_path = ScriptServer::get_global_class_path(class_name);
599 Ref<Script> scr = ResourceLoader::load(scr_path, "Script");
600 ERR_CONTINUE_MSG(scr.is_null(), vformat(R"(Could not load the global class %s from resource path: "%s".)", class_name, scr_path));
601
602 input_names.append(class_name);
603 input_vals.append(scr);
604 }
605
606 Expression expression;
607 expression.parse(expression_str, input_names);
608 const Variant return_val = expression.execute(input_vals, breaked_instance->get_owner());
609
610 DebuggerMarshalls::ScriptStackVariable stvar;
611 stvar.name = expression_str;
612 stvar.value = return_val;
613 stvar.type = 3;
614
615 send_message("evaluation_return", stvar.serialize());
616 } else {
617 bool captured = false;
618 ERR_CONTINUE(_try_capture(command, data, captured) != OK);
619 if (!captured) {
620 WARN_PRINT(vformat("Unknown message received from debugger: %s.", command));
621 }
622 }
623 } else {
624 OS::get_singleton()->delay_usec(10000);
625 if (Thread::is_main_thread()) {
626 // If this is a busy loop on the main thread, events still need to be processed.
627 DisplayServer::get_singleton()->force_process_and_drop_events();
628 }
629 }
630 }
631
632 send_message("debug_exit", Array());
633
634 if (Thread::is_main_thread() && mouse_mode != Input::MouseMode::MOUSE_MODE_VISIBLE) {
635 Input::get_singleton()->set_mouse_mode(mouse_mode);
636 }
637
638 {
639 MutexLock mutex_lock(mutex);
640
641 if (!Thread::is_main_thread()) {
642 messages.erase(Thread::get_caller_id());
643 }
644
645 threads_in_break.erase(Thread::get_caller_id());
646 }
647 }
648
649 void RemoteDebugger::poll_events(bool p_is_idle) {
650 {
651 MutexLock lock(mutex);
652 if (threads_in_break.has(Thread::get_caller_id())) {
653 // We're already in `RemoteDebugger::debug`, so messages should be handled there instead.
654 return;
655 }
656 }
657
658 flush_output();
659
660 _poll_messages();
661
662 while (_has_messages()) {
663 Array arr = _get_message();
664
665 ERR_CONTINUE(arr.size() != 2);
666 ERR_CONTINUE(arr[0].get_type() != Variant::STRING);
667 ERR_CONTINUE(arr[1].get_type() != Variant::ARRAY);
668
669 const String cmd = arr[0];
670 const int idx = cmd.find_char(':');
671 bool parsed = false;
672 if (idx < 0) { // Not prefix, use scripts capture.
673 capture_parse("core", cmd, arr[1], parsed);
674 continue;
675 }
676
677 const String cap = cmd.substr(0, idx);
678 if (!has_capture(cap)) {
679 continue; // Unknown message...
680 }
681
682 const String msg = cmd.substr(idx + 1);
683 capture_parse(cap, msg, arr[1], parsed);
684 }
685
686 // Reload scripts during idle poll only.
687 if (p_is_idle) {
688 if (reload_all_scripts) {
689 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
690 ScriptServer::get_language(i)->reload_all_scripts();
691 }
692 reload_all_scripts = false;
693 } else if (!script_paths_to_reload.is_empty()) {
694 Array scripts_to_reload;
695 for (const Variant &v : script_paths_to_reload) {
696 const String &path = v;
697 Error err = OK;
698 Ref<Script> script = ResourceCache::get_ref(path);
699 if (script.is_null()) {
700 if (path.is_resource_file()) {
701 script = ResourceLoader::load(path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
702 } else {
703 // Built-in script that isn't in ResourceCache, no need to reload.
704 continue;
705 }
706 }
707 ERR_CONTINUE_MSG(err != OK, vformat("Could not reload script '%s': %s", path, error_names[err]));
708 ERR_CONTINUE_MSG(script.is_null(), vformat("Could not reload script '%s': Not a script!", path, error_names[err]));
709 scripts_to_reload.push_back(script);
710 }
711 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
712 ScriptServer::get_language(i)->reload_scripts(scripts_to_reload, true);
713 }
714 }
715 script_paths_to_reload.clear();
716 }
717 }
718
719 Error RemoteDebugger::_core_capture(const String &p_cmd, const Array &p_data, bool &r_captured) {
720 r_captured = true;
721 if (p_cmd == "reload_scripts") {
722 script_paths_to_reload = p_data;
723 } else if (p_cmd == "reload_all_scripts") {
724 reload_all_scripts = true;
725 } else if (p_cmd == "breakpoint") {
726 ERR_FAIL_COND_V(p_data.size() < 3, ERR_INVALID_DATA);
727 bool set = p_data[2];
728 if (set) {
729 script_debugger->insert_breakpoint(p_data[1], p_data[0]);
730 } else {
731 script_debugger->remove_breakpoint(p_data[1], p_data[0]);
732 }
733
734 } else if (p_cmd == "set_skip_breakpoints") {
735 ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_DATA);
736 script_debugger->set_skip_breakpoints(p_data[0]);
737 } else if (p_cmd == "set_ignore_error_breaks") {
738 ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_DATA);
739 script_debugger->set_ignore_error_breaks(p_data[0]);
740 } else if (p_cmd == "break") {
741 script_debugger->debug(script_debugger->get_break_language());
742 } else {
743 r_captured = false;
744 }
745 return OK;
746 }
747
748 Error RemoteDebugger::_profiler_capture(const String &p_cmd, const Array &p_data, bool &r_captured) {
749 r_captured = false;
750 ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_DATA);
751 ERR_FAIL_COND_V(p_data[0].get_type() != Variant::BOOL, ERR_INVALID_DATA);
752 ERR_FAIL_COND_V(!has_profiler(p_cmd), ERR_UNAVAILABLE);
753 Array opts;
754 if (p_data.size() > 1) { // Optional profiler parameters.
755 ERR_FAIL_COND_V(p_data[1].get_type() != Variant::ARRAY, ERR_INVALID_DATA);
756 opts = p_data[1];
757 }
758 r_captured = true;
759 profiler_enable(p_cmd, p_data[0], opts);
760 return OK;
761 }
762
763 RemoteDebugger::RemoteDebugger(Ref<RemoteDebuggerPeer> p_peer) {
764 peer = p_peer;
765 max_chars_per_second = GLOBAL_GET("network/limits/debugger/max_chars_per_second");
766 max_errors_per_second = GLOBAL_GET("network/limits/debugger/max_errors_per_second");
767 max_warnings_per_second = GLOBAL_GET("network/limits/debugger/max_warnings_per_second");
768
769 // Performance Profiler
770 Object *perf = Engine::get_singleton()->get_singleton_object("Performance");
771 if (perf) {
772 performance_profiler.instantiate(perf);
773 performance_profiler->bind("performance");
774 profiler_enable("performance", true);
775 }
776
777 // Core and profiler captures.
778 Capture core_cap(this,
779 [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
780 return static_cast<RemoteDebugger *>(p_user)->_core_capture(p_cmd, p_data, r_captured);
781 });
782 register_message_capture("core", core_cap);
783 Capture profiler_cap(this,
784 [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
785 return static_cast<RemoteDebugger *>(p_user)->_profiler_capture(p_cmd, p_data, r_captured);
786 });
787 register_message_capture("profiler", profiler_cap);
788
789 // Error handlers
790 phl.printfunc = _print_handler;
791 phl.userdata = this;
792 add_print_handler(&phl);
793
794 eh.errfunc = _err_handler;
795 eh.userdata = this;
796 add_error_handler(&eh);
797
798 messages.insert(Thread::get_main_id(), List<Message>());
799 }
800
801 RemoteDebugger::~RemoteDebugger() {
802 remove_print_handler(&phl);
803 remove_error_handler(&eh);
804 }