remote_debugger.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. #include "remote_debugger.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/debugger/debugger_marshalls.h"
  33. #include "core/debugger/engine_debugger.h"
  34. #include "core/debugger/engine_profiler.h"
  35. #include "core/debugger/script_debugger.h"
  36. #include "core/input/input.h"
  37. #include "core/io/resource_loader.h"
  38. #include "core/math/expression.h"
  39. #include "core/object/script_language.h"
  40. #include "core/os/os.h"
  41. #include "servers/display/display_server.h"
  42. class RemoteDebugger::PerformanceProfiler : public EngineProfiler {
  43. Object *performance = nullptr;
  44. int last_perf_time = 0;
  45. uint64_t last_monitor_modification_time = 0;
  46. public:
  47. void toggle(bool p_enable, const Array &p_opts) override {}
  48. void add(const Array &p_data) override {}
  49. void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) override {
  50. if (!performance) {
  51. return;
  52. }
  53. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  54. if (pt - last_perf_time < 1000) {
  55. return;
  56. }
  57. last_perf_time = pt;
  58. Array custom_monitor_names = performance->call("get_custom_monitor_names");
  59. uint64_t monitor_modification_time = performance->call("get_monitor_modification_time");
  60. if (monitor_modification_time > last_monitor_modification_time) {
  61. last_monitor_modification_time = monitor_modification_time;
  62. EngineDebugger::get_singleton()->send_message("performance:profile_names", custom_monitor_names);
  63. }
  64. int max = performance->get("MONITOR_MAX");
  65. Array arr;
  66. arr.resize(max + custom_monitor_names.size());
  67. for (int i = 0; i < max; i++) {
  68. arr[i] = performance->call("get_monitor", i);
  69. }
  70. for (int i = 0; i < custom_monitor_names.size(); i++) {
  71. Variant monitor_value = performance->call("get_custom_monitor", custom_monitor_names[i]);
  72. if (!monitor_value.is_num()) {
  73. ERR_PRINT(vformat("Value of custom monitor '%s' is not a number.", String(custom_monitor_names[i])));
  74. arr[i + max] = Variant();
  75. } else {
  76. arr[i + max] = monitor_value;
  77. }
  78. }
  79. EngineDebugger::get_singleton()->send_message("performance:profile_frame", arr);
  80. }
  81. explicit PerformanceProfiler(Object *p_performance) {
  82. performance = p_performance;
  83. }
  84. };
  85. Error RemoteDebugger::_put_msg(const String &p_message, const Array &p_data) {
  86. Array msg = { p_message, Thread::get_caller_id(), p_data };
  87. Error err = peer->put_message(msg);
  88. if (err != OK) {
  89. n_messages_dropped++;
  90. }
  91. return err;
  92. }
  93. 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) {
  94. RemoteDebugger *rd = static_cast<RemoteDebugger *>(p_this);
  95. if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive errors during flush.
  96. return;
  97. }
  98. Vector<ScriptLanguage::StackInfo> si;
  99. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  100. si = ScriptServer::get_language(i)->debug_get_current_stack_info();
  101. if (si.size()) {
  102. break;
  103. }
  104. }
  105. // send_error will lock internally.
  106. 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);
  107. }
  108. void RemoteDebugger::_print_handler(void *p_this, const String &p_string, bool p_error, bool p_rich) {
  109. RemoteDebugger *rd = static_cast<RemoteDebugger *>(p_this);
  110. if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive prints during flush.
  111. return;
  112. }
  113. String s = p_string;
  114. int allowed_chars = MIN(MAX(rd->max_chars_per_second - rd->char_count, 0), s.length());
  115. if (allowed_chars == 0 && s.length() > 0) {
  116. return;
  117. }
  118. if (allowed_chars < s.length()) {
  119. s = s.substr(0, allowed_chars);
  120. }
  121. MutexLock lock(rd->mutex);
  122. rd->char_count += allowed_chars;
  123. bool overflowed = rd->char_count >= rd->max_chars_per_second;
  124. if (rd->is_peer_connected()) {
  125. if (overflowed) {
  126. s += "[...]";
  127. }
  128. OutputString output_string;
  129. output_string.message = s;
  130. if (p_error) {
  131. output_string.type = MESSAGE_TYPE_ERROR;
  132. } else if (p_rich) {
  133. output_string.type = MESSAGE_TYPE_LOG_RICH;
  134. } else {
  135. output_string.type = MESSAGE_TYPE_LOG;
  136. }
  137. rd->output_strings.push_back(output_string);
  138. if (overflowed) {
  139. output_string.message = "[output overflow, print less text!]";
  140. output_string.type = MESSAGE_TYPE_ERROR;
  141. rd->output_strings.push_back(output_string);
  142. }
  143. }
  144. }
  145. RemoteDebugger::ErrorMessage RemoteDebugger::_create_overflow_error(const String &p_what, const String &p_descr) {
  146. ErrorMessage oe;
  147. oe.error = p_what;
  148. oe.error_descr = p_descr;
  149. oe.warning = false;
  150. uint64_t time = OS::get_singleton()->get_ticks_msec();
  151. oe.hr = time / 3600000;
  152. oe.min = (time / 60000) % 60;
  153. oe.sec = (time / 1000) % 60;
  154. oe.msec = time % 1000;
  155. return oe;
  156. }
  157. void RemoteDebugger::flush_output() {
  158. MutexLock lock(mutex);
  159. flush_thread = Thread::get_caller_id();
  160. flushing = true;
  161. if (!is_peer_connected()) {
  162. return;
  163. }
  164. if (n_messages_dropped > 0) {
  165. 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.");
  166. if (_put_msg("error", err_msg.serialize()) == OK) {
  167. n_messages_dropped = 0;
  168. }
  169. }
  170. if (output_strings.size()) {
  171. // Join output strings so we generate less messages.
  172. Vector<String> joined_log_strings;
  173. Vector<String> strings;
  174. Vector<int> types;
  175. for (const OutputString &output_string : output_strings) {
  176. if (output_string.type == MESSAGE_TYPE_ERROR) {
  177. if (!joined_log_strings.is_empty()) {
  178. strings.push_back(String("\n").join(joined_log_strings));
  179. types.push_back(MESSAGE_TYPE_LOG);
  180. joined_log_strings.clear();
  181. }
  182. strings.push_back(output_string.message);
  183. types.push_back(MESSAGE_TYPE_ERROR);
  184. } else if (output_string.type == MESSAGE_TYPE_LOG_RICH) {
  185. if (!joined_log_strings.is_empty()) {
  186. strings.push_back(String("\n").join(joined_log_strings));
  187. types.push_back(MESSAGE_TYPE_LOG_RICH);
  188. joined_log_strings.clear();
  189. }
  190. strings.push_back(output_string.message);
  191. types.push_back(MESSAGE_TYPE_LOG_RICH);
  192. } else {
  193. joined_log_strings.push_back(output_string.message);
  194. }
  195. }
  196. if (!joined_log_strings.is_empty()) {
  197. strings.push_back(String("\n").join(joined_log_strings));
  198. types.push_back(MESSAGE_TYPE_LOG);
  199. }
  200. Array arr = { strings, types };
  201. _put_msg("output", arr);
  202. output_strings.clear();
  203. }
  204. while (errors.size()) {
  205. ErrorMessage oe = errors.front()->get();
  206. _put_msg("error", oe.serialize());
  207. errors.pop_front();
  208. }
  209. // Update limits
  210. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  211. if (ticks - last_reset > 1000) {
  212. last_reset = ticks;
  213. char_count = 0;
  214. err_count = 0;
  215. n_errors_dropped = 0;
  216. warn_count = 0;
  217. n_warnings_dropped = 0;
  218. }
  219. flushing = false;
  220. }
  221. void RemoteDebugger::send_message(const String &p_message, const Array &p_args) {
  222. MutexLock lock(mutex);
  223. if (is_peer_connected()) {
  224. _put_msg(p_message, p_args);
  225. }
  226. }
  227. 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) {
  228. ErrorMessage oe;
  229. oe.error = p_err;
  230. oe.error_descr = p_descr;
  231. oe.source_file = p_file;
  232. oe.source_line = p_line;
  233. oe.source_func = p_func;
  234. oe.warning = p_type == ERR_HANDLER_WARNING;
  235. uint64_t time = OS::get_singleton()->get_ticks_msec();
  236. oe.hr = time / 3600000;
  237. oe.min = (time / 60000) % 60;
  238. oe.sec = (time / 1000) % 60;
  239. oe.msec = time % 1000;
  240. oe.callstack.append_array(script_debugger->get_error_stack_info());
  241. if (flushing && Thread::get_caller_id() == flush_thread) { // Can't handle recursive errors during flush.
  242. return;
  243. }
  244. MutexLock lock(mutex);
  245. if (oe.warning) {
  246. warn_count++;
  247. } else {
  248. err_count++;
  249. }
  250. if (is_peer_connected()) {
  251. if (oe.warning) {
  252. if (warn_count > max_warnings_per_second) {
  253. n_warnings_dropped++;
  254. if (n_warnings_dropped == 1) {
  255. // Only print one message about dropping per second
  256. ErrorMessage overflow = _create_overflow_error("TOO_MANY_WARNINGS", "Too many warnings! Ignoring warnings for up to 1 second.");
  257. errors.push_back(overflow);
  258. }
  259. } else {
  260. errors.push_back(oe);
  261. }
  262. } else {
  263. if (err_count > max_errors_per_second) {
  264. n_errors_dropped++;
  265. if (n_errors_dropped == 1) {
  266. // Only print one message about dropping per second
  267. ErrorMessage overflow = _create_overflow_error("TOO_MANY_ERRORS", "Too many errors! Ignoring errors for up to 1 second.");
  268. errors.push_back(overflow);
  269. }
  270. } else {
  271. errors.push_back(oe);
  272. }
  273. }
  274. }
  275. }
  276. void RemoteDebugger::_send_stack_vars(List<String> &p_names, List<Variant> &p_vals, int p_type) {
  277. DebuggerMarshalls::ScriptStackVariable stvar;
  278. List<String>::Element *E = p_names.front();
  279. List<Variant>::Element *F = p_vals.front();
  280. while (E) {
  281. stvar.name = E->get();
  282. stvar.value = F->get();
  283. stvar.type = p_type;
  284. send_message("stack_frame_var", stvar.serialize());
  285. E = E->next();
  286. F = F->next();
  287. }
  288. }
  289. Error RemoteDebugger::_try_capture(const String &p_msg, const Array &p_data, bool &r_captured) {
  290. const int idx = p_msg.find_char(':');
  291. r_captured = false;
  292. if (idx < 0) { // No prefix, unknown message.
  293. return OK;
  294. }
  295. const String cap = p_msg.substr(0, idx);
  296. if (!has_capture(cap)) {
  297. return ERR_UNAVAILABLE; // Unknown message...
  298. }
  299. const String msg = p_msg.substr(idx + 1);
  300. return capture_parse(cap, msg, p_data, r_captured);
  301. }
  302. void RemoteDebugger::_poll_messages() {
  303. MutexLock mutex_lock(mutex);
  304. peer->poll();
  305. while (peer->has_message()) {
  306. Array cmd = peer->get_message();
  307. ERR_CONTINUE(cmd.size() != 3);
  308. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  309. ERR_CONTINUE(cmd[1].get_type() != Variant::INT);
  310. ERR_CONTINUE(cmd[2].get_type() != Variant::ARRAY);
  311. Thread::ID thread = cmd[1];
  312. if (!messages.has(thread)) {
  313. continue; // This thread is not around to receive the messages
  314. }
  315. Message msg;
  316. msg.message = cmd[0];
  317. msg.data = cmd[2];
  318. messages[thread].push_back(msg);
  319. }
  320. }
  321. bool RemoteDebugger::_has_messages() {
  322. MutexLock mutex_lock(mutex);
  323. return messages.has(Thread::get_caller_id()) && !messages[Thread::get_caller_id()].is_empty();
  324. }
  325. Array RemoteDebugger::_get_message() {
  326. MutexLock mutex_lock(mutex);
  327. ERR_FAIL_COND_V(!messages.has(Thread::get_caller_id()), Array());
  328. List<Message> &message_list = messages[Thread::get_caller_id()];
  329. ERR_FAIL_COND_V(message_list.is_empty(), Array());
  330. Array msg;
  331. msg.resize(2);
  332. msg[0] = message_list.front()->get().message;
  333. msg[1] = message_list.front()->get().data;
  334. message_list.pop_front();
  335. return msg;
  336. }
  337. void RemoteDebugger::debug(bool p_can_continue, bool p_is_error_breakpoint) {
  338. //this function is called when there is a debugger break (bug on script)
  339. //or when execution is paused from editor
  340. {
  341. MutexLock lock(mutex);
  342. // Tests that require mutex.
  343. if (script_debugger->is_skipping_breakpoints() && !p_is_error_breakpoint) {
  344. return;
  345. }
  346. ERR_FAIL_COND_MSG(!is_peer_connected(), "Script Debugger failed to connect, but being used anyway.");
  347. if (!peer->can_block()) {
  348. return; // Peer does not support blocking IO. We could at least send the error though.
  349. }
  350. }
  351. if (p_is_error_breakpoint && script_debugger->is_ignoring_error_breaks()) {
  352. return;
  353. }
  354. ScriptLanguage *script_lang = script_debugger->get_break_language();
  355. ERR_FAIL_NULL(script_lang);
  356. Array msg = {
  357. p_can_continue,
  358. script_lang->debug_get_error(),
  359. script_lang->debug_get_stack_level_count() > 0,
  360. Thread::get_caller_id()
  361. };
  362. if (allow_focus_steal_fn) {
  363. allow_focus_steal_fn();
  364. }
  365. send_message("debug_enter", msg);
  366. Input::MouseMode mouse_mode = Input::MOUSE_MODE_VISIBLE;
  367. if (Thread::get_caller_id() == Thread::get_main_id()) {
  368. mouse_mode = Input::get_singleton()->get_mouse_mode();
  369. if (mouse_mode != Input::MOUSE_MODE_VISIBLE) {
  370. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  371. }
  372. } else {
  373. MutexLock mutex_lock(mutex);
  374. messages.insert(Thread::get_caller_id(), List<Message>());
  375. }
  376. while (is_peer_connected()) {
  377. flush_output();
  378. _poll_messages();
  379. if (_has_messages()) {
  380. Array cmd = _get_message();
  381. ERR_CONTINUE(cmd.size() != 2);
  382. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  383. ERR_CONTINUE(cmd[1].get_type() != Variant::ARRAY);
  384. String command = cmd[0];
  385. Array data = cmd[1];
  386. if (command == "step") {
  387. script_debugger->set_depth(-1);
  388. script_debugger->set_lines_left(1);
  389. break;
  390. } else if (command == "next") {
  391. script_debugger->set_depth(0);
  392. script_debugger->set_lines_left(1);
  393. break;
  394. } else if (command == "continue") {
  395. script_debugger->set_depth(-1);
  396. script_debugger->set_lines_left(-1);
  397. break;
  398. } else if (command == "break") {
  399. ERR_PRINT("Got break when already broke!");
  400. break;
  401. } else if (command == "get_stack_dump") {
  402. DebuggerMarshalls::ScriptStackDump dump;
  403. int slc = script_lang->debug_get_stack_level_count();
  404. for (int i = 0; i < slc; i++) {
  405. ScriptLanguage::StackInfo frame;
  406. frame.file = script_lang->debug_get_stack_level_source(i);
  407. frame.line = script_lang->debug_get_stack_level_line(i);
  408. frame.func = script_lang->debug_get_stack_level_function(i);
  409. dump.frames.push_back(frame);
  410. }
  411. send_message("stack_dump", dump.serialize());
  412. } else if (command == "get_stack_frame_vars") {
  413. ERR_FAIL_COND(data.size() != 1);
  414. ERR_FAIL_NULL(script_lang);
  415. int lv = data[0];
  416. List<String> members;
  417. List<Variant> member_vals;
  418. if (ScriptInstance *inst = script_lang->debug_get_stack_level_instance(lv)) {
  419. members.push_back("self");
  420. member_vals.push_back(inst->get_owner());
  421. }
  422. script_lang->debug_get_stack_level_members(lv, &members, &member_vals);
  423. ERR_FAIL_COND(members.size() != member_vals.size());
  424. List<String> locals;
  425. List<Variant> local_vals;
  426. script_lang->debug_get_stack_level_locals(lv, &locals, &local_vals);
  427. ERR_FAIL_COND(locals.size() != local_vals.size());
  428. List<String> globals;
  429. List<Variant> globals_vals;
  430. script_lang->debug_get_globals(&globals, &globals_vals);
  431. ERR_FAIL_COND(globals.size() != globals_vals.size());
  432. Array var_size = { local_vals.size() + member_vals.size() + globals_vals.size() };
  433. send_message("stack_frame_vars", var_size);
  434. _send_stack_vars(locals, local_vals, 0);
  435. _send_stack_vars(members, member_vals, 1);
  436. _send_stack_vars(globals, globals_vals, 2);
  437. } else if (command == "reload_scripts") {
  438. script_paths_to_reload = data;
  439. } else if (command == "reload_all_scripts") {
  440. reload_all_scripts = true;
  441. } else if (command == "breakpoint") {
  442. ERR_FAIL_COND(data.size() < 3);
  443. bool set = data[2];
  444. if (set) {
  445. script_debugger->insert_breakpoint(data[1], data[0]);
  446. } else {
  447. script_debugger->remove_breakpoint(data[1], data[0]);
  448. }
  449. } else if (command == "set_skip_breakpoints") {
  450. ERR_FAIL_COND(data.is_empty());
  451. script_debugger->set_skip_breakpoints(data[0]);
  452. } else if (command == "set_ignore_error_breaks") {
  453. ERR_FAIL_COND(data.is_empty());
  454. script_debugger->set_ignore_error_breaks(data[0]);
  455. } else if (command == "evaluate") {
  456. String expression_str = data[0];
  457. int frame = data[1];
  458. ScriptInstance *breaked_instance = script_debugger->get_break_language()->debug_get_stack_level_instance(frame);
  459. if (!breaked_instance) {
  460. break;
  461. }
  462. PackedStringArray input_names;
  463. Array input_vals;
  464. List<String> locals;
  465. List<Variant> local_vals;
  466. script_debugger->get_break_language()->debug_get_stack_level_locals(frame, &locals, &local_vals);
  467. ERR_FAIL_COND(locals.size() != local_vals.size());
  468. for (const String &S : locals) {
  469. input_names.append(S);
  470. }
  471. for (const Variant &V : local_vals) {
  472. input_vals.append(V);
  473. }
  474. List<String> globals;
  475. List<Variant> globals_vals;
  476. script_debugger->get_break_language()->debug_get_globals(&globals, &globals_vals);
  477. ERR_FAIL_COND(globals.size() != globals_vals.size());
  478. for (const String &S : globals) {
  479. input_names.append(S);
  480. }
  481. for (const Variant &V : globals_vals) {
  482. input_vals.append(V);
  483. }
  484. LocalVector<StringName> native_types;
  485. ClassDB::get_class_list(native_types);
  486. for (const StringName &class_name : native_types) {
  487. if (!ClassDB::is_class_exposed(class_name) || !Engine::get_singleton()->has_singleton(class_name) || Engine::get_singleton()->is_singleton_editor_only(class_name)) {
  488. continue;
  489. }
  490. input_names.append(class_name);
  491. input_vals.append(Engine::get_singleton()->get_singleton_object(class_name));
  492. }
  493. LocalVector<StringName> user_types;
  494. ScriptServer::get_global_class_list(user_types);
  495. for (const StringName &class_name : user_types) {
  496. String scr_path = ScriptServer::get_global_class_path(class_name);
  497. Ref<Script> scr = ResourceLoader::load(scr_path, "Script");
  498. ERR_CONTINUE_MSG(scr.is_null(), vformat(R"(Could not load the global class %s from resource path: "%s".)", class_name, scr_path));
  499. input_names.append(class_name);
  500. input_vals.append(scr);
  501. }
  502. Expression expression;
  503. expression.parse(expression_str, input_names);
  504. const Variant return_val = expression.execute(input_vals, breaked_instance->get_owner());
  505. DebuggerMarshalls::ScriptStackVariable stvar;
  506. stvar.name = expression_str;
  507. stvar.value = return_val;
  508. stvar.type = 3;
  509. send_message("evaluation_return", stvar.serialize());
  510. } else {
  511. bool captured = false;
  512. ERR_CONTINUE(_try_capture(command, data, captured) != OK);
  513. if (!captured) {
  514. WARN_PRINT(vformat("Unknown message received from debugger: %s.", command));
  515. }
  516. }
  517. } else {
  518. OS::get_singleton()->delay_usec(10000);
  519. if (Thread::get_caller_id() == Thread::get_main_id()) {
  520. // If this is a busy loop on the main thread, events still need to be processed.
  521. DisplayServer::get_singleton()->force_process_and_drop_events();
  522. }
  523. }
  524. }
  525. send_message("debug_exit", Array());
  526. if (Thread::get_caller_id() == Thread::get_main_id()) {
  527. if (mouse_mode != Input::MOUSE_MODE_VISIBLE) {
  528. Input::get_singleton()->set_mouse_mode(mouse_mode);
  529. }
  530. } else {
  531. MutexLock mutex_lock(mutex);
  532. messages.erase(Thread::get_caller_id());
  533. }
  534. }
  535. void RemoteDebugger::poll_events(bool p_is_idle) {
  536. if (peer.is_null()) {
  537. return;
  538. }
  539. flush_output();
  540. _poll_messages();
  541. while (_has_messages()) {
  542. Array arr = _get_message();
  543. ERR_CONTINUE(arr.size() != 2);
  544. ERR_CONTINUE(arr[0].get_type() != Variant::STRING);
  545. ERR_CONTINUE(arr[1].get_type() != Variant::ARRAY);
  546. const String cmd = arr[0];
  547. const int idx = cmd.find_char(':');
  548. bool parsed = false;
  549. if (idx < 0) { // Not prefix, use scripts capture.
  550. capture_parse("core", cmd, arr[1], parsed);
  551. continue;
  552. }
  553. const String cap = cmd.substr(0, idx);
  554. if (!has_capture(cap)) {
  555. continue; // Unknown message...
  556. }
  557. const String msg = cmd.substr(idx + 1);
  558. capture_parse(cap, msg, arr[1], parsed);
  559. }
  560. // Reload scripts during idle poll only.
  561. if (p_is_idle) {
  562. if (reload_all_scripts) {
  563. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  564. ScriptServer::get_language(i)->reload_all_scripts();
  565. }
  566. reload_all_scripts = false;
  567. } else if (!script_paths_to_reload.is_empty()) {
  568. Array scripts_to_reload;
  569. for (int i = 0; i < script_paths_to_reload.size(); ++i) {
  570. String path = script_paths_to_reload[i];
  571. Error err = OK;
  572. Ref<Script> script = ResourceLoader::load(path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
  573. ERR_CONTINUE_MSG(err != OK, vformat("Could not reload script '%s': %s", path, error_names[err]));
  574. ERR_CONTINUE_MSG(script.is_null(), vformat("Could not reload script '%s': Not a script!", path, error_names[err]));
  575. scripts_to_reload.push_back(script);
  576. }
  577. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  578. ScriptServer::get_language(i)->reload_scripts(scripts_to_reload, true);
  579. }
  580. }
  581. script_paths_to_reload.clear();
  582. }
  583. }
  584. Error RemoteDebugger::_core_capture(const String &p_cmd, const Array &p_data, bool &r_captured) {
  585. r_captured = true;
  586. if (p_cmd == "reload_scripts") {
  587. script_paths_to_reload = p_data;
  588. } else if (p_cmd == "reload_all_scripts") {
  589. reload_all_scripts = true;
  590. } else if (p_cmd == "breakpoint") {
  591. ERR_FAIL_COND_V(p_data.size() < 3, ERR_INVALID_DATA);
  592. bool set = p_data[2];
  593. if (set) {
  594. script_debugger->insert_breakpoint(p_data[1], p_data[0]);
  595. } else {
  596. script_debugger->remove_breakpoint(p_data[1], p_data[0]);
  597. }
  598. } else if (p_cmd == "set_skip_breakpoints") {
  599. ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_DATA);
  600. script_debugger->set_skip_breakpoints(p_data[0]);
  601. } else if (p_cmd == "set_ignore_error_breaks") {
  602. ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_DATA);
  603. script_debugger->set_ignore_error_breaks(p_data[0]);
  604. } else if (p_cmd == "break") {
  605. script_debugger->debug(script_debugger->get_break_language());
  606. } else {
  607. r_captured = false;
  608. }
  609. return OK;
  610. }
  611. Error RemoteDebugger::_profiler_capture(const String &p_cmd, const Array &p_data, bool &r_captured) {
  612. r_captured = false;
  613. ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_DATA);
  614. ERR_FAIL_COND_V(p_data[0].get_type() != Variant::BOOL, ERR_INVALID_DATA);
  615. ERR_FAIL_COND_V(!has_profiler(p_cmd), ERR_UNAVAILABLE);
  616. Array opts;
  617. if (p_data.size() > 1) { // Optional profiler parameters.
  618. ERR_FAIL_COND_V(p_data[1].get_type() != Variant::ARRAY, ERR_INVALID_DATA);
  619. opts = p_data[1];
  620. }
  621. r_captured = true;
  622. profiler_enable(p_cmd, p_data[0], opts);
  623. return OK;
  624. }
  625. RemoteDebugger::RemoteDebugger(Ref<RemoteDebuggerPeer> p_peer) {
  626. peer = p_peer;
  627. max_chars_per_second = GLOBAL_GET("network/limits/debugger/max_chars_per_second");
  628. max_errors_per_second = GLOBAL_GET("network/limits/debugger/max_errors_per_second");
  629. max_warnings_per_second = GLOBAL_GET("network/limits/debugger/max_warnings_per_second");
  630. // Performance Profiler
  631. Object *perf = Engine::get_singleton()->get_singleton_object("Performance");
  632. if (perf) {
  633. performance_profiler.instantiate(perf);
  634. performance_profiler->bind("performance");
  635. profiler_enable("performance", true);
  636. }
  637. // Core and profiler captures.
  638. Capture core_cap(this,
  639. [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
  640. return static_cast<RemoteDebugger *>(p_user)->_core_capture(p_cmd, p_data, r_captured);
  641. });
  642. register_message_capture("core", core_cap);
  643. Capture profiler_cap(this,
  644. [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
  645. return static_cast<RemoteDebugger *>(p_user)->_profiler_capture(p_cmd, p_data, r_captured);
  646. });
  647. register_message_capture("profiler", profiler_cap);
  648. // Error handlers
  649. phl.printfunc = _print_handler;
  650. phl.userdata = this;
  651. add_print_handler(&phl);
  652. eh.errfunc = _err_handler;
  653. eh.userdata = this;
  654. add_error_handler(&eh);
  655. messages.insert(Thread::get_main_id(), List<Message>());
  656. }
  657. RemoteDebugger::~RemoteDebugger() {
  658. remove_print_handler(&phl);
  659. remove_error_handler(&eh);
  660. }