remote_debugger.cpp 31 KB

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