2
0

remote_debugger.cpp 30 KB

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