remote_debugger.cpp 30 KB

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