remote_debugger.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. /*************************************************************************/
  2. /* remote_debugger.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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/script_debugger.h"
  35. #include "core/input/input.h"
  36. #include "core/object/script_language.h"
  37. #include "core/os/os.h"
  38. #include "scene/main/node.h"
  39. #include "servers/display_server.h"
  40. template <typename T>
  41. void RemoteDebugger::_bind_profiler(const String &p_name, T *p_prof) {
  42. EngineDebugger::Profiler prof(
  43. p_prof,
  44. [](void *p_user, bool p_enable, const Array &p_opts) {
  45. ((T *)p_user)->toggle(p_enable, p_opts);
  46. },
  47. [](void *p_user, const Array &p_data) {
  48. ((T *)p_user)->add(p_data);
  49. },
  50. [](void *p_user, double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) {
  51. ((T *)p_user)->tick(p_frame_time, p_idle_time, p_physics_time, p_physics_frame_time);
  52. });
  53. EngineDebugger::register_profiler(p_name, prof);
  54. }
  55. struct RemoteDebugger::NetworkProfiler {
  56. public:
  57. typedef DebuggerMarshalls::MultiplayerNodeInfo NodeInfo;
  58. struct BandwidthFrame {
  59. uint32_t timestamp;
  60. int packet_size;
  61. };
  62. int bandwidth_in_ptr = 0;
  63. Vector<BandwidthFrame> bandwidth_in;
  64. int bandwidth_out_ptr = 0;
  65. Vector<BandwidthFrame> bandwidth_out;
  66. uint64_t last_bandwidth_time = 0;
  67. Map<ObjectID, NodeInfo> multiplayer_node_data;
  68. uint64_t last_profile_time = 0;
  69. NetworkProfiler() {}
  70. int bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer) {
  71. ERR_FAIL_COND_V(p_buffer.size() == 0, 0);
  72. int total_bandwidth = 0;
  73. uint64_t timestamp = OS::get_singleton()->get_ticks_msec();
  74. uint64_t final_timestamp = timestamp - 1000;
  75. int i = (p_pointer + p_buffer.size() - 1) % p_buffer.size();
  76. while (i != p_pointer && p_buffer[i].packet_size > 0) {
  77. if (p_buffer[i].timestamp < final_timestamp) {
  78. return total_bandwidth;
  79. }
  80. total_bandwidth += p_buffer[i].packet_size;
  81. i = (i + p_buffer.size() - 1) % p_buffer.size();
  82. }
  83. ERR_FAIL_COND_V_MSG(i == p_pointer, total_bandwidth, "Reached the end of the bandwidth profiler buffer, values might be inaccurate.");
  84. return total_bandwidth;
  85. }
  86. void init_node(const ObjectID p_node) {
  87. if (multiplayer_node_data.has(p_node)) {
  88. return;
  89. }
  90. multiplayer_node_data.insert(p_node, DebuggerMarshalls::MultiplayerNodeInfo());
  91. multiplayer_node_data[p_node].node = p_node;
  92. multiplayer_node_data[p_node].node_path = Object::cast_to<Node>(ObjectDB::get_instance(p_node))->get_path();
  93. multiplayer_node_data[p_node].incoming_rpc = 0;
  94. multiplayer_node_data[p_node].incoming_rset = 0;
  95. multiplayer_node_data[p_node].outgoing_rpc = 0;
  96. multiplayer_node_data[p_node].outgoing_rset = 0;
  97. }
  98. void toggle(bool p_enable, const Array &p_opts) {
  99. multiplayer_node_data.clear();
  100. if (!p_enable) {
  101. bandwidth_in.clear();
  102. bandwidth_out.clear();
  103. } else {
  104. bandwidth_in_ptr = 0;
  105. bandwidth_in.resize(16384); // ~128kB
  106. for (int i = 0; i < bandwidth_in.size(); ++i) {
  107. bandwidth_in.write[i].packet_size = -1;
  108. }
  109. bandwidth_out_ptr = 0;
  110. bandwidth_out.resize(16384); // ~128kB
  111. for (int i = 0; i < bandwidth_out.size(); ++i) {
  112. bandwidth_out.write[i].packet_size = -1;
  113. }
  114. }
  115. }
  116. void add(const Array &p_data) {
  117. ERR_FAIL_COND(p_data.size() < 1);
  118. const String type = p_data[0];
  119. if (type == "node") {
  120. ERR_FAIL_COND(p_data.size() < 3);
  121. const ObjectID id = p_data[1];
  122. const String what = p_data[2];
  123. init_node(id);
  124. NodeInfo &info = multiplayer_node_data[id];
  125. if (what == "rpc_in") {
  126. info.incoming_rpc++;
  127. } else if (what == "rpc_out") {
  128. info.outgoing_rpc++;
  129. } else if (what == "rset_in") {
  130. info.incoming_rset = 0;
  131. } else if (what == "rset_out") {
  132. info.outgoing_rset++;
  133. }
  134. } else if (type == "bandwidth") {
  135. ERR_FAIL_COND(p_data.size() < 4);
  136. const String inout = p_data[1];
  137. int time = p_data[2];
  138. int size = p_data[3];
  139. if (inout == "in") {
  140. bandwidth_in.write[bandwidth_in_ptr].timestamp = time;
  141. bandwidth_in.write[bandwidth_in_ptr].packet_size = size;
  142. bandwidth_in_ptr = (bandwidth_in_ptr + 1) % bandwidth_in.size();
  143. } else if (inout == "out") {
  144. bandwidth_out.write[bandwidth_out_ptr].timestamp = time;
  145. bandwidth_out.write[bandwidth_out_ptr].packet_size = size;
  146. bandwidth_out_ptr = (bandwidth_out_ptr + 1) % bandwidth_out.size();
  147. }
  148. }
  149. }
  150. void tick(double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) {
  151. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  152. if (pt - last_bandwidth_time > 200) {
  153. last_bandwidth_time = pt;
  154. int incoming_bandwidth = bandwidth_usage(bandwidth_in, bandwidth_in_ptr);
  155. int outgoing_bandwidth = bandwidth_usage(bandwidth_out, bandwidth_out_ptr);
  156. Array arr;
  157. arr.push_back(incoming_bandwidth);
  158. arr.push_back(outgoing_bandwidth);
  159. EngineDebugger::get_singleton()->send_message("network:bandwidth", arr);
  160. }
  161. if (pt - last_profile_time > 100) {
  162. last_profile_time = pt;
  163. DebuggerMarshalls::NetworkProfilerFrame frame;
  164. for (const KeyValue<ObjectID, NodeInfo> &E : multiplayer_node_data) {
  165. frame.infos.push_back(E.value);
  166. }
  167. multiplayer_node_data.clear();
  168. EngineDebugger::get_singleton()->send_message("network:profile_frame", frame.serialize());
  169. }
  170. }
  171. };
  172. struct RemoteDebugger::ScriptsProfiler {
  173. typedef DebuggerMarshalls::ScriptFunctionSignature FunctionSignature;
  174. typedef DebuggerMarshalls::ScriptFunctionInfo FunctionInfo;
  175. struct ProfileInfoSort {
  176. bool operator()(ScriptLanguage::ProfilingInfo *A, ScriptLanguage::ProfilingInfo *B) const {
  177. return A->total_time < B->total_time;
  178. }
  179. };
  180. Vector<ScriptLanguage::ProfilingInfo> info;
  181. Vector<ScriptLanguage::ProfilingInfo *> ptrs;
  182. Map<StringName, int> sig_map;
  183. int max_frame_functions = 16;
  184. void toggle(bool p_enable, const Array &p_opts) {
  185. if (p_enable) {
  186. sig_map.clear();
  187. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  188. ScriptServer::get_language(i)->profiling_start();
  189. }
  190. if (p_opts.size() == 1 && p_opts[0].get_type() == Variant::INT) {
  191. max_frame_functions = MAX(0, int(p_opts[0]));
  192. }
  193. } else {
  194. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  195. ScriptServer::get_language(i)->profiling_stop();
  196. }
  197. }
  198. }
  199. void write_frame_data(Vector<FunctionInfo> &r_funcs, uint64_t &r_total, bool p_accumulated) {
  200. int ofs = 0;
  201. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  202. if (p_accumulated) {
  203. ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&info.write[ofs], info.size() - ofs);
  204. } else {
  205. ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&info.write[ofs], info.size() - ofs);
  206. }
  207. }
  208. for (int i = 0; i < ofs; i++) {
  209. ptrs.write[i] = &info.write[i];
  210. }
  211. SortArray<ScriptLanguage::ProfilingInfo *, ProfileInfoSort> sa;
  212. sa.sort(ptrs.ptrw(), ofs);
  213. int to_send = MIN(ofs, max_frame_functions);
  214. // Check signatures first, and compute total time.
  215. r_total = 0;
  216. for (int i = 0; i < to_send; i++) {
  217. if (!sig_map.has(ptrs[i]->signature)) {
  218. int idx = sig_map.size();
  219. FunctionSignature sig;
  220. sig.name = ptrs[i]->signature;
  221. sig.id = idx;
  222. EngineDebugger::get_singleton()->send_message("servers:function_signature", sig.serialize());
  223. sig_map[ptrs[i]->signature] = idx;
  224. }
  225. r_total += ptrs[i]->self_time;
  226. }
  227. // Send frame, script time, functions information then
  228. r_funcs.resize(to_send);
  229. FunctionInfo *w = r_funcs.ptrw();
  230. for (int i = 0; i < to_send; i++) {
  231. if (sig_map.has(ptrs[i]->signature)) {
  232. w[i].sig_id = sig_map[ptrs[i]->signature];
  233. }
  234. w[i].call_count = ptrs[i]->call_count;
  235. w[i].total_time = ptrs[i]->total_time / 1000000.0;
  236. w[i].self_time = ptrs[i]->self_time / 1000000.0;
  237. }
  238. }
  239. ScriptsProfiler() {
  240. info.resize(GLOBAL_GET("debug/settings/profiler/max_functions"));
  241. ptrs.resize(info.size());
  242. }
  243. };
  244. struct RemoteDebugger::ServersProfiler {
  245. bool skip_profile_frame = false;
  246. typedef DebuggerMarshalls::ServerInfo ServerInfo;
  247. typedef DebuggerMarshalls::ServerFunctionInfo ServerFunctionInfo;
  248. Map<StringName, ServerInfo> server_data;
  249. ScriptsProfiler scripts_profiler;
  250. double frame_time = 0;
  251. double idle_time = 0;
  252. double physics_time = 0;
  253. double physics_frame_time = 0;
  254. void toggle(bool p_enable, const Array &p_opts) {
  255. skip_profile_frame = false;
  256. if (p_enable) {
  257. server_data.clear(); // Clear old profiling data.
  258. } else {
  259. _send_frame_data(true); // Send final frame.
  260. }
  261. scripts_profiler.toggle(p_enable, p_opts);
  262. }
  263. void add(const Array &p_data) {
  264. String name = p_data[0];
  265. if (!server_data.has(name)) {
  266. ServerInfo info;
  267. info.name = name;
  268. server_data[name] = info;
  269. }
  270. ServerInfo &srv = server_data[name];
  271. ServerFunctionInfo fi;
  272. fi.name = p_data[1];
  273. fi.time = p_data[2];
  274. srv.functions.push_back(fi);
  275. }
  276. void tick(double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) {
  277. frame_time = p_frame_time;
  278. idle_time = p_idle_time;
  279. physics_time = p_physics_time;
  280. physics_frame_time = p_physics_frame_time;
  281. _send_frame_data(false);
  282. }
  283. void _send_frame_data(bool p_final) {
  284. DebuggerMarshalls::ServersProfilerFrame frame;
  285. frame.frame_number = Engine::get_singleton()->get_process_frames();
  286. frame.frame_time = frame_time;
  287. frame.idle_time = idle_time;
  288. frame.physics_time = physics_time;
  289. frame.physics_frame_time = physics_frame_time;
  290. Map<StringName, ServerInfo>::Element *E = server_data.front();
  291. while (E) {
  292. if (!p_final) {
  293. frame.servers.push_back(E->get());
  294. }
  295. E->get().functions.clear();
  296. E = E->next();
  297. }
  298. uint64_t time = 0;
  299. scripts_profiler.write_frame_data(frame.script_functions, time, p_final);
  300. frame.script_time = USEC_TO_SEC(time);
  301. if (skip_profile_frame) {
  302. skip_profile_frame = false;
  303. return;
  304. }
  305. if (p_final) {
  306. EngineDebugger::get_singleton()->send_message("servers:profile_total", frame.serialize());
  307. } else {
  308. EngineDebugger::get_singleton()->send_message("servers:profile_frame", frame.serialize());
  309. }
  310. }
  311. };
  312. struct RemoteDebugger::VisualProfiler {
  313. typedef DebuggerMarshalls::ServerInfo ServerInfo;
  314. typedef DebuggerMarshalls::ServerFunctionInfo ServerFunctionInfo;
  315. Map<StringName, ServerInfo> server_data;
  316. void toggle(bool p_enable, const Array &p_opts) {
  317. RS::get_singleton()->set_frame_profiling_enabled(p_enable);
  318. }
  319. void add(const Array &p_data) {}
  320. void tick(double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) {
  321. Vector<RS::FrameProfileArea> profile_areas = RS::get_singleton()->get_frame_profile();
  322. DebuggerMarshalls::VisualProfilerFrame frame;
  323. if (!profile_areas.size()) {
  324. return;
  325. }
  326. frame.frame_number = RS::get_singleton()->get_frame_profile_frame();
  327. frame.areas.append_array(profile_areas);
  328. EngineDebugger::get_singleton()->send_message("visual:profile_frame", frame.serialize());
  329. }
  330. };
  331. struct RemoteDebugger::PerformanceProfiler {
  332. Object *performance = nullptr;
  333. int last_perf_time = 0;
  334. uint64_t last_monitor_modification_time = 0;
  335. void toggle(bool p_enable, const Array &p_opts) {}
  336. void add(const Array &p_data) {}
  337. void tick(double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) {
  338. if (!performance) {
  339. return;
  340. }
  341. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  342. if (pt - last_perf_time < 1000) {
  343. return;
  344. }
  345. last_perf_time = pt;
  346. Array custom_monitor_names = performance->call("get_custom_monitor_names");
  347. uint64_t monitor_modification_time = performance->call("get_monitor_modification_time");
  348. if (monitor_modification_time > last_monitor_modification_time) {
  349. last_monitor_modification_time = monitor_modification_time;
  350. EngineDebugger::get_singleton()->send_message("performance:profile_names", custom_monitor_names);
  351. }
  352. int max = performance->get("MONITOR_MAX");
  353. Array arr;
  354. arr.resize(max + custom_monitor_names.size());
  355. for (int i = 0; i < max; i++) {
  356. arr[i] = performance->call("get_monitor", i);
  357. }
  358. for (int i = 0; i < custom_monitor_names.size(); i++) {
  359. Variant monitor_value = performance->call("get_custom_monitor", custom_monitor_names[i]);
  360. if (!monitor_value.is_num()) {
  361. ERR_PRINT("Value of custom monitor '" + String(custom_monitor_names[i]) + "' is not a number");
  362. arr[i + max] = Variant();
  363. }
  364. arr[i + max] = monitor_value;
  365. }
  366. EngineDebugger::get_singleton()->send_message("performance:profile_frame", arr);
  367. }
  368. PerformanceProfiler(Object *p_performance) {
  369. performance = p_performance;
  370. }
  371. };
  372. void RemoteDebugger::_send_resource_usage() {
  373. DebuggerMarshalls::ResourceUsage usage;
  374. List<RS::TextureInfo> tinfo;
  375. RS::get_singleton()->texture_debug_usage(&tinfo);
  376. for (const RS::TextureInfo &E : tinfo) {
  377. DebuggerMarshalls::ResourceInfo info;
  378. info.path = E.path;
  379. info.vram = E.bytes;
  380. info.id = E.texture;
  381. info.type = "Texture";
  382. if (E.depth == 0) {
  383. info.format = itos(E.width) + "x" + itos(E.height) + " " + Image::get_format_name(E.format);
  384. } else {
  385. info.format = itos(E.width) + "x" + itos(E.height) + "x" + itos(E.depth) + " " + Image::get_format_name(E.format);
  386. }
  387. usage.infos.push_back(info);
  388. }
  389. EngineDebugger::get_singleton()->send_message("memory:usage", usage.serialize());
  390. }
  391. Error RemoteDebugger::_put_msg(String p_message, Array p_data) {
  392. Array msg;
  393. msg.push_back(p_message);
  394. msg.push_back(p_data);
  395. Error err = peer->put_message(msg);
  396. if (err != OK) {
  397. n_messages_dropped++;
  398. }
  399. return err;
  400. }
  401. 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) {
  402. if (p_type == ERR_HANDLER_SCRIPT) {
  403. return; //ignore script errors, those go through debugger
  404. }
  405. RemoteDebugger *rd = (RemoteDebugger *)p_this;
  406. if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive errors during flush.
  407. return;
  408. }
  409. Vector<ScriptLanguage::StackInfo> si;
  410. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  411. si = ScriptServer::get_language(i)->debug_get_current_stack_info();
  412. if (si.size()) {
  413. break;
  414. }
  415. }
  416. // send_error will lock internally.
  417. 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);
  418. }
  419. void RemoteDebugger::_print_handler(void *p_this, const String &p_string, bool p_error) {
  420. RemoteDebugger *rd = (RemoteDebugger *)p_this;
  421. if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive prints during flush.
  422. return;
  423. }
  424. String s = p_string;
  425. int allowed_chars = MIN(MAX(rd->max_chars_per_second - rd->char_count, 0), s.length());
  426. if (allowed_chars == 0 && s.length() > 0) {
  427. return;
  428. }
  429. if (allowed_chars < s.length()) {
  430. s = s.substr(0, allowed_chars);
  431. }
  432. MutexLock lock(rd->mutex);
  433. rd->char_count += allowed_chars;
  434. bool overflowed = rd->char_count >= rd->max_chars_per_second;
  435. if (rd->is_peer_connected()) {
  436. if (overflowed) {
  437. s += "[...]";
  438. }
  439. OutputString output_string;
  440. output_string.message = s;
  441. output_string.type = p_error ? MESSAGE_TYPE_ERROR : MESSAGE_TYPE_LOG;
  442. rd->output_strings.push_back(output_string);
  443. if (overflowed) {
  444. output_string.message = "[output overflow, print less text!]";
  445. output_string.type = MESSAGE_TYPE_ERROR;
  446. rd->output_strings.push_back(output_string);
  447. }
  448. }
  449. }
  450. RemoteDebugger::ErrorMessage RemoteDebugger::_create_overflow_error(const String &p_what, const String &p_descr) {
  451. ErrorMessage oe;
  452. oe.error = p_what;
  453. oe.error_descr = p_descr;
  454. oe.warning = false;
  455. uint64_t time = OS::get_singleton()->get_ticks_msec();
  456. oe.hr = time / 3600000;
  457. oe.min = (time / 60000) % 60;
  458. oe.sec = (time / 1000) % 60;
  459. oe.msec = time % 1000;
  460. return oe;
  461. }
  462. void RemoteDebugger::flush_output() {
  463. flush_thread = Thread::get_caller_id();
  464. flushing = true;
  465. MutexLock lock(mutex);
  466. if (!is_peer_connected()) {
  467. return;
  468. }
  469. if (n_messages_dropped > 0) {
  470. 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.");
  471. if (_put_msg("error", err_msg.serialize()) == OK) {
  472. n_messages_dropped = 0;
  473. }
  474. }
  475. if (output_strings.size()) {
  476. // Join output strings so we generate less messages.
  477. Vector<String> joined_log_strings;
  478. Vector<String> strings;
  479. Vector<int> types;
  480. for (int i = 0; i < output_strings.size(); i++) {
  481. const OutputString &output_string = output_strings[i];
  482. if (output_string.type == MESSAGE_TYPE_ERROR) {
  483. if (!joined_log_strings.is_empty()) {
  484. strings.push_back(String("\n").join(joined_log_strings));
  485. types.push_back(MESSAGE_TYPE_LOG);
  486. joined_log_strings.clear();
  487. }
  488. strings.push_back(output_string.message);
  489. types.push_back(MESSAGE_TYPE_ERROR);
  490. } else {
  491. joined_log_strings.push_back(output_string.message);
  492. }
  493. }
  494. if (!joined_log_strings.is_empty()) {
  495. strings.push_back(String("\n").join(joined_log_strings));
  496. types.push_back(MESSAGE_TYPE_LOG);
  497. }
  498. Array arr;
  499. arr.push_back(strings);
  500. arr.push_back(types);
  501. _put_msg("output", arr);
  502. output_strings.clear();
  503. }
  504. while (errors.size()) {
  505. ErrorMessage oe = errors.front()->get();
  506. _put_msg("error", oe.serialize());
  507. errors.pop_front();
  508. }
  509. // Update limits
  510. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  511. if (ticks - last_reset > 1000) {
  512. last_reset = ticks;
  513. char_count = 0;
  514. err_count = 0;
  515. n_errors_dropped = 0;
  516. warn_count = 0;
  517. n_warnings_dropped = 0;
  518. }
  519. flushing = false;
  520. }
  521. void RemoteDebugger::send_message(const String &p_message, const Array &p_args) {
  522. MutexLock lock(mutex);
  523. if (is_peer_connected()) {
  524. _put_msg(p_message, p_args);
  525. }
  526. }
  527. 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) {
  528. ErrorMessage oe;
  529. oe.error = p_err;
  530. oe.error_descr = p_descr;
  531. oe.source_file = p_file;
  532. oe.source_line = p_line;
  533. oe.source_func = p_func;
  534. oe.warning = p_type == ERR_HANDLER_WARNING;
  535. uint64_t time = OS::get_singleton()->get_ticks_msec();
  536. oe.hr = time / 3600000;
  537. oe.min = (time / 60000) % 60;
  538. oe.sec = (time / 1000) % 60;
  539. oe.msec = time % 1000;
  540. oe.callstack.append_array(script_debugger->get_error_stack_info());
  541. if (flushing && Thread::get_caller_id() == flush_thread) { // Can't handle recursive errors during flush.
  542. return;
  543. }
  544. MutexLock lock(mutex);
  545. if (oe.warning) {
  546. warn_count++;
  547. } else {
  548. err_count++;
  549. }
  550. if (is_peer_connected()) {
  551. if (oe.warning) {
  552. if (warn_count > max_warnings_per_second) {
  553. n_warnings_dropped++;
  554. if (n_warnings_dropped == 1) {
  555. // Only print one message about dropping per second
  556. ErrorMessage overflow = _create_overflow_error("TOO_MANY_WARNINGS", "Too many warnings! Ignoring warnings for up to 1 second.");
  557. errors.push_back(overflow);
  558. }
  559. } else {
  560. errors.push_back(oe);
  561. }
  562. } else {
  563. if (err_count > max_errors_per_second) {
  564. n_errors_dropped++;
  565. if (n_errors_dropped == 1) {
  566. // Only print one message about dropping per second
  567. ErrorMessage overflow = _create_overflow_error("TOO_MANY_ERRORS", "Too many errors! Ignoring errors for up to 1 second.");
  568. errors.push_back(overflow);
  569. }
  570. } else {
  571. errors.push_back(oe);
  572. }
  573. }
  574. }
  575. }
  576. void RemoteDebugger::_send_stack_vars(List<String> &p_names, List<Variant> &p_vals, int p_type) {
  577. DebuggerMarshalls::ScriptStackVariable stvar;
  578. List<String>::Element *E = p_names.front();
  579. List<Variant>::Element *F = p_vals.front();
  580. while (E) {
  581. stvar.name = E->get();
  582. stvar.value = F->get();
  583. stvar.type = p_type;
  584. send_message("stack_frame_var", stvar.serialize());
  585. E = E->next();
  586. F = F->next();
  587. }
  588. }
  589. Error RemoteDebugger::_try_capture(const String &p_msg, const Array &p_data, bool &r_captured) {
  590. const int idx = p_msg.find(":");
  591. r_captured = false;
  592. if (idx < 0) { // No prefix, unknown message.
  593. return OK;
  594. }
  595. const String cap = p_msg.substr(0, idx);
  596. if (!has_capture(cap)) {
  597. return ERR_UNAVAILABLE; // Unknown message...
  598. }
  599. const String msg = p_msg.substr(idx + 1);
  600. return capture_parse(cap, msg, p_data, r_captured);
  601. }
  602. void RemoteDebugger::debug(bool p_can_continue, bool p_is_error_breakpoint) {
  603. //this function is called when there is a debugger break (bug on script)
  604. //or when execution is paused from editor
  605. if (script_debugger->is_skipping_breakpoints() && !p_is_error_breakpoint) {
  606. return;
  607. }
  608. ERR_FAIL_COND_MSG(!is_peer_connected(), "Script Debugger failed to connect, but being used anyway.");
  609. if (!peer->can_block()) {
  610. return; // Peer does not support blocking IO. We could at least send the error though.
  611. }
  612. ScriptLanguage *script_lang = script_debugger->get_break_language();
  613. const String error_str = script_lang ? script_lang->debug_get_error() : "";
  614. Array msg;
  615. msg.push_back(p_can_continue);
  616. msg.push_back(error_str);
  617. ERR_FAIL_COND(!script_lang);
  618. msg.push_back(script_lang->debug_get_stack_level_count() > 0);
  619. send_message("debug_enter", msg);
  620. servers_profiler->skip_profile_frame = true; // Avoid frame time spike in debug.
  621. Input::MouseMode mouse_mode = Input::get_singleton()->get_mouse_mode();
  622. if (mouse_mode != Input::MOUSE_MODE_VISIBLE) {
  623. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  624. }
  625. uint64_t loop_begin_usec = 0;
  626. uint64_t loop_time_sec = 0;
  627. while (is_peer_connected()) {
  628. loop_begin_usec = OS::get_singleton()->get_ticks_usec();
  629. flush_output();
  630. peer->poll();
  631. if (peer->has_message()) {
  632. Array cmd = peer->get_message();
  633. ERR_CONTINUE(cmd.size() != 2);
  634. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  635. ERR_CONTINUE(cmd[1].get_type() != Variant::ARRAY);
  636. String command = cmd[0];
  637. Array data = cmd[1];
  638. if (command == "step") {
  639. script_debugger->set_depth(-1);
  640. script_debugger->set_lines_left(1);
  641. break;
  642. } else if (command == "next") {
  643. script_debugger->set_depth(0);
  644. script_debugger->set_lines_left(1);
  645. break;
  646. } else if (command == "continue") {
  647. script_debugger->set_depth(-1);
  648. script_debugger->set_lines_left(-1);
  649. DisplayServer::get_singleton()->window_move_to_foreground();
  650. break;
  651. } else if (command == "break") {
  652. ERR_PRINT("Got break when already broke!");
  653. break;
  654. } else if (command == "get_stack_dump") {
  655. DebuggerMarshalls::ScriptStackDump dump;
  656. int slc = script_lang->debug_get_stack_level_count();
  657. for (int i = 0; i < slc; i++) {
  658. ScriptLanguage::StackInfo frame;
  659. frame.file = script_lang->debug_get_stack_level_source(i);
  660. frame.line = script_lang->debug_get_stack_level_line(i);
  661. frame.func = script_lang->debug_get_stack_level_function(i);
  662. dump.frames.push_back(frame);
  663. }
  664. send_message("stack_dump", dump.serialize());
  665. } else if (command == "get_stack_frame_vars") {
  666. ERR_FAIL_COND(data.size() != 1);
  667. ERR_FAIL_COND(!script_lang);
  668. int lv = data[0];
  669. List<String> members;
  670. List<Variant> member_vals;
  671. if (ScriptInstance *inst = script_lang->debug_get_stack_level_instance(lv)) {
  672. members.push_back("self");
  673. member_vals.push_back(inst->get_owner());
  674. }
  675. script_lang->debug_get_stack_level_members(lv, &members, &member_vals);
  676. ERR_FAIL_COND(members.size() != member_vals.size());
  677. List<String> locals;
  678. List<Variant> local_vals;
  679. script_lang->debug_get_stack_level_locals(lv, &locals, &local_vals);
  680. ERR_FAIL_COND(locals.size() != local_vals.size());
  681. List<String> globals;
  682. List<Variant> globals_vals;
  683. script_lang->debug_get_globals(&globals, &globals_vals);
  684. ERR_FAIL_COND(globals.size() != globals_vals.size());
  685. Array var_size;
  686. var_size.push_back(local_vals.size() + member_vals.size() + globals_vals.size());
  687. send_message("stack_frame_vars", var_size);
  688. _send_stack_vars(locals, local_vals, 0);
  689. _send_stack_vars(members, member_vals, 1);
  690. _send_stack_vars(globals, globals_vals, 2);
  691. } else if (command == "reload_scripts") {
  692. reload_all_scripts = true;
  693. } else if (command == "breakpoint") {
  694. ERR_FAIL_COND(data.size() < 3);
  695. bool set = data[2];
  696. if (set) {
  697. script_debugger->insert_breakpoint(data[1], data[0]);
  698. } else {
  699. script_debugger->remove_breakpoint(data[1], data[0]);
  700. }
  701. } else if (command == "set_skip_breakpoints") {
  702. ERR_FAIL_COND(data.size() < 1);
  703. script_debugger->set_skip_breakpoints(data[0]);
  704. } else {
  705. bool captured = false;
  706. ERR_CONTINUE(_try_capture(command, data, captured) != OK);
  707. if (!captured) {
  708. WARN_PRINT("Unknown message received from debugger: " + command);
  709. }
  710. }
  711. } else {
  712. OS::get_singleton()->delay_usec(10000);
  713. OS::get_singleton()->process_and_drop_events();
  714. }
  715. // This is for the camera override to stay live even when the game is paused from the editor
  716. loop_time_sec = (OS::get_singleton()->get_ticks_usec() - loop_begin_usec) / 1000000.0f;
  717. RenderingServer::get_singleton()->sync();
  718. if (RenderingServer::get_singleton()->has_changed()) {
  719. RenderingServer::get_singleton()->draw(true, loop_time_sec * Engine::get_singleton()->get_time_scale());
  720. }
  721. }
  722. send_message("debug_exit", Array());
  723. if (mouse_mode != Input::MOUSE_MODE_VISIBLE) {
  724. Input::get_singleton()->set_mouse_mode(mouse_mode);
  725. }
  726. }
  727. void RemoteDebugger::poll_events(bool p_is_idle) {
  728. if (peer.is_null()) {
  729. return;
  730. }
  731. flush_output();
  732. peer->poll();
  733. while (peer->has_message()) {
  734. Array arr = peer->get_message();
  735. ERR_CONTINUE(arr.size() != 2);
  736. ERR_CONTINUE(arr[0].get_type() != Variant::STRING);
  737. ERR_CONTINUE(arr[1].get_type() != Variant::ARRAY);
  738. const String cmd = arr[0];
  739. const int idx = cmd.find(":");
  740. bool parsed = false;
  741. if (idx < 0) { // Not prefix, use scripts capture.
  742. capture_parse("core", cmd, arr[1], parsed);
  743. continue;
  744. }
  745. const String cap = cmd.substr(0, idx);
  746. if (!has_capture(cap)) {
  747. continue; // Unknown message...
  748. }
  749. const String msg = cmd.substr(idx + 1);
  750. capture_parse(cap, msg, arr[1], parsed);
  751. }
  752. // Reload scripts during idle poll only.
  753. if (p_is_idle && reload_all_scripts) {
  754. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  755. ScriptServer::get_language(i)->reload_all_scripts();
  756. }
  757. reload_all_scripts = false;
  758. }
  759. }
  760. Error RemoteDebugger::_core_capture(const String &p_cmd, const Array &p_data, bool &r_captured) {
  761. r_captured = true;
  762. if (p_cmd == "reload_scripts") {
  763. reload_all_scripts = true;
  764. } else if (p_cmd == "breakpoint") {
  765. ERR_FAIL_COND_V(p_data.size() < 3, ERR_INVALID_DATA);
  766. bool set = p_data[2];
  767. if (set) {
  768. script_debugger->insert_breakpoint(p_data[1], p_data[0]);
  769. } else {
  770. script_debugger->remove_breakpoint(p_data[1], p_data[0]);
  771. }
  772. } else if (p_cmd == "set_skip_breakpoints") {
  773. ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_DATA);
  774. script_debugger->set_skip_breakpoints(p_data[0]);
  775. } else if (p_cmd == "memory") {
  776. _send_resource_usage();
  777. } else if (p_cmd == "break") {
  778. script_debugger->debug(script_debugger->get_break_language());
  779. } else {
  780. r_captured = false;
  781. }
  782. return OK;
  783. }
  784. Error RemoteDebugger::_profiler_capture(const String &p_cmd, const Array &p_data, bool &r_captured) {
  785. r_captured = false;
  786. ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_DATA);
  787. ERR_FAIL_COND_V(p_data[0].get_type() != Variant::BOOL, ERR_INVALID_DATA);
  788. ERR_FAIL_COND_V(!has_profiler(p_cmd), ERR_UNAVAILABLE);
  789. Array opts;
  790. if (p_data.size() > 1) { // Optional profiler parameters.
  791. ERR_FAIL_COND_V(p_data[1].get_type() != Variant::ARRAY, ERR_INVALID_DATA);
  792. opts = p_data[1];
  793. }
  794. r_captured = true;
  795. profiler_enable(p_cmd, p_data[0], opts);
  796. return OK;
  797. }
  798. RemoteDebugger::RemoteDebugger(Ref<RemoteDebuggerPeer> p_peer) {
  799. peer = p_peer;
  800. max_chars_per_second = GLOBAL_GET("network/limits/debugger/max_chars_per_second");
  801. max_errors_per_second = GLOBAL_GET("network/limits/debugger/max_errors_per_second");
  802. max_warnings_per_second = GLOBAL_GET("network/limits/debugger/max_warnings_per_second");
  803. // Network Profiler
  804. network_profiler = memnew(NetworkProfiler);
  805. _bind_profiler("network", network_profiler);
  806. // Servers Profiler (audio/physics/...)
  807. servers_profiler = memnew(ServersProfiler);
  808. _bind_profiler("servers", servers_profiler);
  809. // Visual Profiler (cpu/gpu times)
  810. visual_profiler = memnew(VisualProfiler);
  811. _bind_profiler("visual", visual_profiler);
  812. // Performance Profiler
  813. Object *perf = Engine::get_singleton()->get_singleton_object("Performance");
  814. if (perf) {
  815. performance_profiler = memnew(PerformanceProfiler(perf));
  816. _bind_profiler("performance", performance_profiler);
  817. profiler_enable("performance", true);
  818. }
  819. // Core and profiler captures.
  820. Capture core_cap(this,
  821. [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
  822. return ((RemoteDebugger *)p_user)->_core_capture(p_cmd, p_data, r_captured);
  823. });
  824. register_message_capture("core", core_cap);
  825. Capture profiler_cap(this,
  826. [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) {
  827. return ((RemoteDebugger *)p_user)->_profiler_capture(p_cmd, p_data, r_captured);
  828. });
  829. register_message_capture("profiler", profiler_cap);
  830. // Error handlers
  831. phl.printfunc = _print_handler;
  832. phl.userdata = this;
  833. add_print_handler(&phl);
  834. eh.errfunc = _err_handler;
  835. eh.userdata = this;
  836. add_error_handler(&eh);
  837. }
  838. RemoteDebugger::~RemoteDebugger() {
  839. remove_print_handler(&phl);
  840. remove_error_handler(&eh);
  841. EngineDebugger::get_singleton()->unregister_profiler("servers");
  842. EngineDebugger::get_singleton()->unregister_profiler("network");
  843. EngineDebugger::get_singleton()->unregister_profiler("visual");
  844. if (EngineDebugger::has_profiler("performance")) {
  845. EngineDebugger::get_singleton()->unregister_profiler("performance");
  846. }
  847. memdelete(servers_profiler);
  848. memdelete(network_profiler);
  849. memdelete(visual_profiler);
  850. if (performance_profiler) {
  851. memdelete(performance_profiler);
  852. }
  853. }