script_debugger_remote.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. /*************************************************************************/
  2. /* script_debugger_remote.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 "script_debugger_remote.h"
  31. #include "core/engine.h"
  32. #include "core/io/ip.h"
  33. #include "core/io/marshalls.h"
  34. #include "core/os/input.h"
  35. #include "core/os/os.h"
  36. #include "core/project_settings.h"
  37. #include "servers/visual_server.h"
  38. #define CHECK_SIZE(arr, expected, what) ERR_FAIL_COND_V_MSG((uint32_t)arr.size() < (uint32_t)(expected), false, String("Malformed ") + what + " message from script debugger, message too short. Exptected size: " + itos(expected) + ", actual size: " + itos(arr.size()))
  39. #define CHECK_END(arr, expected, what) ERR_FAIL_COND_V_MSG((uint32_t)arr.size() > (uint32_t)expected, false, String("Malformed ") + what + " message from script debugger, message too short. Exptected size: " + itos(expected) + ", actual size: " + itos(arr.size()))
  40. Array ScriptDebuggerRemote::ScriptStackDump::serialize() {
  41. Array arr;
  42. arr.push_back(frames.size() * 3);
  43. for (int i = 0; i < frames.size(); i++) {
  44. arr.push_back(frames[i].file);
  45. arr.push_back(frames[i].line);
  46. arr.push_back(frames[i].func);
  47. }
  48. return arr;
  49. }
  50. bool ScriptDebuggerRemote::ScriptStackDump::deserialize(const Array &p_arr) {
  51. CHECK_SIZE(p_arr, 1, "ScriptStackDump");
  52. uint32_t size = p_arr[0];
  53. CHECK_SIZE(p_arr, size, "ScriptStackDump");
  54. int idx = 1;
  55. for (uint32_t i = 0; i < size / 3; i++) {
  56. ScriptLanguage::StackInfo sf;
  57. sf.file = p_arr[idx];
  58. sf.line = p_arr[idx + 1];
  59. sf.func = p_arr[idx + 2];
  60. frames.push_back(sf);
  61. idx += 3;
  62. }
  63. CHECK_END(p_arr, idx, "ScriptStackDump");
  64. return true;
  65. }
  66. Array ScriptDebuggerRemote::ScriptStackVariable::serialize(int max_size) {
  67. Array arr;
  68. arr.push_back(name);
  69. arr.push_back(type);
  70. Variant var = value;
  71. if (value.get_type() == Variant::OBJECT && value.get_validated_object() == nullptr) {
  72. var = Variant();
  73. }
  74. int len = 0;
  75. Error err = encode_variant(var, NULL, len, true);
  76. if (err != OK)
  77. ERR_PRINT("Failed to encode variant.");
  78. if (len > max_size) {
  79. arr.push_back(Variant());
  80. } else {
  81. arr.push_back(var);
  82. }
  83. return arr;
  84. }
  85. bool ScriptDebuggerRemote::ScriptStackVariable::deserialize(const Array &p_arr) {
  86. CHECK_SIZE(p_arr, 3, "ScriptStackVariable");
  87. name = p_arr[0];
  88. type = p_arr[1];
  89. value = p_arr[2];
  90. CHECK_END(p_arr, 3, "ScriptStackVariable");
  91. return true;
  92. }
  93. Array ScriptDebuggerRemote::OutputError::serialize() {
  94. Array arr;
  95. arr.push_back(hr);
  96. arr.push_back(min);
  97. arr.push_back(sec);
  98. arr.push_back(msec);
  99. arr.push_back(source_file);
  100. arr.push_back(source_func);
  101. arr.push_back(source_line);
  102. arr.push_back(error);
  103. arr.push_back(error_descr);
  104. arr.push_back(warning);
  105. unsigned int size = callstack.size();
  106. const ScriptLanguage::StackInfo *r = callstack.ptr();
  107. arr.push_back(size * 3);
  108. for (int i = 0; i < callstack.size(); i++) {
  109. arr.push_back(r[i].file);
  110. arr.push_back(r[i].func);
  111. arr.push_back(r[i].line);
  112. }
  113. return arr;
  114. }
  115. bool ScriptDebuggerRemote::OutputError::deserialize(const Array &p_arr) {
  116. CHECK_SIZE(p_arr, 11, "OutputError");
  117. hr = p_arr[0];
  118. min = p_arr[1];
  119. sec = p_arr[2];
  120. msec = p_arr[3];
  121. source_file = p_arr[4];
  122. source_func = p_arr[5];
  123. source_line = p_arr[6];
  124. error = p_arr[7];
  125. error_descr = p_arr[8];
  126. warning = p_arr[9];
  127. unsigned int stack_size = p_arr[10];
  128. CHECK_SIZE(p_arr, stack_size, "OutputError");
  129. int idx = 11;
  130. callstack.resize(stack_size / 3);
  131. ScriptLanguage::StackInfo *w = callstack.ptrw();
  132. for (unsigned int i = 0; i < stack_size / 3; i++) {
  133. w[i].file = p_arr[idx];
  134. w[i].func = p_arr[idx + 1];
  135. w[i].line = p_arr[idx + 2];
  136. idx += 3;
  137. }
  138. CHECK_END(p_arr, idx, "OutputError");
  139. return true;
  140. }
  141. Array ScriptDebuggerRemote::ResourceUsage::serialize() {
  142. infos.sort();
  143. Array arr;
  144. arr.push_back(infos.size() * 4);
  145. for (List<ResourceInfo>::Element *E = infos.front(); E; E = E->next()) {
  146. arr.push_back(E->get().path);
  147. arr.push_back(E->get().format);
  148. arr.push_back(E->get().type);
  149. arr.push_back(E->get().vram);
  150. }
  151. return arr;
  152. }
  153. bool ScriptDebuggerRemote::ResourceUsage::deserialize(const Array &p_arr) {
  154. CHECK_SIZE(p_arr, 1, "ResourceUsage");
  155. uint32_t size = p_arr[0];
  156. CHECK_SIZE(p_arr, size, "ResourceUsage");
  157. int idx = 1;
  158. for (uint32_t i = 0; i < size / 4; i++) {
  159. ResourceInfo info;
  160. info.path = p_arr[idx];
  161. info.format = p_arr[idx + 1];
  162. info.type = p_arr[idx + 2];
  163. info.vram = p_arr[idx + 3];
  164. infos.push_back(info);
  165. }
  166. CHECK_END(p_arr, idx, "ResourceUsage");
  167. return true;
  168. }
  169. Array ScriptDebuggerRemote::ProfilerSignature::serialize() {
  170. Array arr;
  171. arr.push_back(name);
  172. arr.push_back(id);
  173. return arr;
  174. }
  175. bool ScriptDebuggerRemote::ProfilerSignature::deserialize(const Array &p_arr) {
  176. CHECK_SIZE(p_arr, 2, "ProfilerSignature");
  177. name = p_arr[0];
  178. id = p_arr[1];
  179. CHECK_END(p_arr, 2, "ProfilerSignature");
  180. return true;
  181. }
  182. Array ScriptDebuggerRemote::ProfilerFrame::serialize() {
  183. Array arr;
  184. arr.push_back(frame_number);
  185. arr.push_back(frame_time);
  186. arr.push_back(idle_time);
  187. arr.push_back(physics_time);
  188. arr.push_back(physics_frame_time);
  189. arr.push_back(USEC_TO_SEC(script_time));
  190. arr.push_back(frames_data.size());
  191. arr.push_back(frame_functions.size() * 4);
  192. // Servers profiling info.
  193. for (int i = 0; i < frames_data.size(); i++) {
  194. arr.push_back(frames_data[i].name); // Type (physics/process/audio/...)
  195. arr.push_back(frames_data[i].data.size());
  196. for (int j = 0; j < frames_data[i].data.size() / 2; j++) {
  197. arr.push_back(frames_data[i].data[2 * j]); // NAME
  198. arr.push_back(frames_data[i].data[2 * j + 1]); // TIME
  199. }
  200. }
  201. for (int i = 0; i < frame_functions.size(); i++) {
  202. arr.push_back(frame_functions[i].sig_id);
  203. arr.push_back(frame_functions[i].call_count);
  204. arr.push_back(frame_functions[i].self_time);
  205. arr.push_back(frame_functions[i].total_time);
  206. }
  207. return arr;
  208. }
  209. bool ScriptDebuggerRemote::ProfilerFrame::deserialize(const Array &p_arr) {
  210. CHECK_SIZE(p_arr, 8, "ProfilerFrame");
  211. frame_number = p_arr[0];
  212. frame_time = p_arr[1];
  213. idle_time = p_arr[2];
  214. physics_time = p_arr[3];
  215. physics_frame_time = p_arr[4];
  216. script_time = p_arr[5];
  217. uint32_t frame_data_size = p_arr[6];
  218. int frame_func_size = p_arr[7];
  219. int idx = 8;
  220. while (frame_data_size) {
  221. CHECK_SIZE(p_arr, idx + 2, "ProfilerFrame");
  222. frame_data_size--;
  223. FrameData fd;
  224. fd.name = p_arr[idx];
  225. int sub_data_size = p_arr[idx + 1];
  226. idx += 2;
  227. CHECK_SIZE(p_arr, idx + sub_data_size, "ProfilerFrame");
  228. for (int j = 0; j < sub_data_size / 2; j++) {
  229. fd.data.push_back(p_arr[idx]); // NAME
  230. fd.data.push_back(p_arr[idx + 1]); // TIME
  231. idx += 2;
  232. }
  233. frames_data.push_back(fd);
  234. }
  235. CHECK_SIZE(p_arr, idx + frame_func_size, "ProfilerFrame");
  236. for (int i = 0; i < frame_func_size / 4; i++) {
  237. FrameFunction ff;
  238. ff.sig_id = p_arr[idx];
  239. ff.call_count = p_arr[idx + 1];
  240. ff.self_time = p_arr[idx + 2];
  241. ff.total_time = p_arr[idx + 3];
  242. frame_functions.push_back(ff);
  243. idx += 4;
  244. }
  245. CHECK_END(p_arr, idx, "ProfilerFrame");
  246. return true;
  247. }
  248. Array ScriptDebuggerRemote::NetworkProfilerFrame::serialize() {
  249. Array arr;
  250. arr.push_back(infos.size() * 6);
  251. for (int i = 0; i < infos.size(); ++i) {
  252. arr.push_back(uint64_t(infos[i].node));
  253. arr.push_back(infos[i].node_path);
  254. arr.push_back(infos[i].incoming_rpc);
  255. arr.push_back(infos[i].incoming_rset);
  256. arr.push_back(infos[i].outgoing_rpc);
  257. arr.push_back(infos[i].outgoing_rset);
  258. }
  259. return arr;
  260. }
  261. bool ScriptDebuggerRemote::NetworkProfilerFrame::deserialize(const Array &p_arr) {
  262. CHECK_SIZE(p_arr, 1, "NetworkProfilerFrame");
  263. uint32_t size = p_arr[0];
  264. CHECK_SIZE(p_arr, size, "NetworkProfilerFrame");
  265. infos.resize(size);
  266. int idx = 1;
  267. for (uint32_t i = 0; i < size / 6; ++i) {
  268. infos.write[i].node = uint64_t(p_arr[idx]);
  269. infos.write[i].node_path = p_arr[idx + 1];
  270. infos.write[i].incoming_rpc = p_arr[idx + 2];
  271. infos.write[i].incoming_rset = p_arr[idx + 3];
  272. infos.write[i].outgoing_rpc = p_arr[idx + 4];
  273. infos.write[i].outgoing_rset = p_arr[idx + 5];
  274. }
  275. CHECK_END(p_arr, idx, "NetworkProfilerFrame");
  276. return true;
  277. }
  278. void ScriptDebuggerRemote::_put_msg(String p_message, Array p_data) {
  279. Array msg;
  280. msg.push_back(p_message);
  281. msg.push_back(p_data);
  282. packet_peer_stream->put_var(msg);
  283. }
  284. bool ScriptDebuggerRemote::is_peer_connected() {
  285. return tcp_client->is_connected_to_host() && tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED;
  286. }
  287. void ScriptDebuggerRemote::_send_video_memory() {
  288. ResourceUsage usage;
  289. if (resource_usage_func)
  290. resource_usage_func(&usage);
  291. _put_msg("message:video_mem", usage.serialize());
  292. }
  293. Error ScriptDebuggerRemote::connect_to_host(const String &p_host, uint16_t p_port) {
  294. IP_Address ip;
  295. if (p_host.is_valid_ip_address())
  296. ip = p_host;
  297. else
  298. ip = IP::get_singleton()->resolve_hostname(p_host);
  299. int port = p_port;
  300. const int tries = 6;
  301. int waits[tries] = { 1, 10, 100, 1000, 1000, 1000 };
  302. tcp_client->connect_to_host(ip, port);
  303. for (int i = 0; i < tries; i++) {
  304. if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
  305. print_verbose("Remote Debugger: Connected!");
  306. break;
  307. } else {
  308. const int ms = waits[i];
  309. OS::get_singleton()->delay_usec(ms * 1000);
  310. print_verbose("Remote Debugger: Connection failed with status: '" + String::num(tcp_client->get_status()) + "', retrying in " + String::num(ms) + " msec.");
  311. };
  312. };
  313. if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  314. ERR_PRINT("Remote Debugger: Unable to connect. Status: " + String::num(tcp_client->get_status()) + ".");
  315. return FAILED;
  316. };
  317. packet_peer_stream->set_stream_peer(tcp_client);
  318. Array msg;
  319. msg.push_back(OS::get_singleton()->get_process_id());
  320. send_message("set_pid", msg);
  321. return OK;
  322. }
  323. void ScriptDebuggerRemote::_parse_message(const String p_command, const Array &p_data, ScriptLanguage *p_script) {
  324. if (p_command == "request_video_mem") {
  325. _send_video_memory();
  326. } else if (p_command == "start_profiling") {
  327. ERR_FAIL_COND(p_data.size() < 1);
  328. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  329. ScriptServer::get_language(i)->profiling_start();
  330. }
  331. max_frame_functions = p_data[0];
  332. profiler_function_signature_map.clear();
  333. profiling = true;
  334. frame_time = 0;
  335. idle_time = 0;
  336. physics_time = 0;
  337. physics_frame_time = 0;
  338. print_line("PROFILING ALRIGHT!");
  339. } else if (p_command == "stop_profiling") {
  340. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  341. ScriptServer::get_language(i)->profiling_stop();
  342. }
  343. profiling = false;
  344. _send_profiling_data(false);
  345. print_line("PROFILING END!");
  346. } else if (p_command == "start_visual_profiling") {
  347. visual_profiling = true;
  348. VS::get_singleton()->set_frame_profiling_enabled(true);
  349. } else if (p_command == "stop_visual_profiling") {
  350. visual_profiling = false;
  351. VS::get_singleton()->set_frame_profiling_enabled(false);
  352. } else if (p_command == "start_network_profiling") {
  353. network_profiling = true;
  354. multiplayer->profiling_start();
  355. } else if (p_command == "stop_network_profiling") {
  356. network_profiling = false;
  357. multiplayer->profiling_end();
  358. } else if (p_command == "reload_scripts") {
  359. reload_all_scripts = true;
  360. } else if (p_command == "breakpoint") {
  361. ERR_FAIL_COND(p_data.size() < 3);
  362. bool set = p_data[2];
  363. if (set)
  364. insert_breakpoint(p_data[1], p_data[0]);
  365. else
  366. remove_breakpoint(p_data[1], p_data[0]);
  367. } else if (p_command == "set_skip_breakpoints") {
  368. ERR_FAIL_COND(p_data.size() < 1);
  369. skip_breakpoints = p_data[0];
  370. } else if (p_command == "get_stack_dump") {
  371. ERR_FAIL_COND(!p_script);
  372. ScriptStackDump dump;
  373. int slc = p_script->debug_get_stack_level_count();
  374. for (int i = 0; i < slc; i++) {
  375. ScriptLanguage::StackInfo frame;
  376. frame.file = p_script->debug_get_stack_level_source(i);
  377. frame.line = p_script->debug_get_stack_level_line(i);
  378. frame.func = p_script->debug_get_stack_level_function(i);
  379. dump.frames.push_back(frame);
  380. }
  381. _put_msg("stack_dump", dump.serialize());
  382. } else if (p_command == "get_stack_frame_vars") {
  383. ERR_FAIL_COND(p_data.size() != 1);
  384. ERR_FAIL_COND(!p_script);
  385. int lv = p_data[0];
  386. List<String> members;
  387. List<Variant> member_vals;
  388. if (ScriptInstance *inst = p_script->debug_get_stack_level_instance(lv)) {
  389. members.push_back("self");
  390. member_vals.push_back(inst->get_owner());
  391. }
  392. p_script->debug_get_stack_level_members(lv, &members, &member_vals);
  393. ERR_FAIL_COND(members.size() != member_vals.size());
  394. List<String> locals;
  395. List<Variant> local_vals;
  396. p_script->debug_get_stack_level_locals(lv, &locals, &local_vals);
  397. ERR_FAIL_COND(locals.size() != local_vals.size());
  398. List<String> globals;
  399. List<Variant> globals_vals;
  400. p_script->debug_get_globals(&globals, &globals_vals);
  401. ERR_FAIL_COND(globals.size() != globals_vals.size());
  402. _put_msg("stack_frame_vars", Array());
  403. ScriptStackVariable stvar;
  404. { //locals
  405. List<String>::Element *E = locals.front();
  406. List<Variant>::Element *F = local_vals.front();
  407. while (E) {
  408. stvar.name = E->get();
  409. stvar.value = F->get();
  410. stvar.type = 0;
  411. _put_msg("stack_frame_var", stvar.serialize());
  412. E = E->next();
  413. F = F->next();
  414. }
  415. }
  416. { //members
  417. List<String>::Element *E = members.front();
  418. List<Variant>::Element *F = member_vals.front();
  419. while (E) {
  420. stvar.name = E->get();
  421. stvar.value = F->get();
  422. stvar.type = 1;
  423. _put_msg("stack_frame_var", stvar.serialize());
  424. E = E->next();
  425. F = F->next();
  426. }
  427. }
  428. { //globals
  429. List<String>::Element *E = globals.front();
  430. List<Variant>::Element *F = globals_vals.front();
  431. while (E) {
  432. stvar.name = E->get();
  433. stvar.value = F->get();
  434. stvar.type = 2;
  435. _put_msg("stack_frame_var", stvar.serialize());
  436. E = E->next();
  437. F = F->next();
  438. }
  439. }
  440. } else {
  441. if (scene_tree_parse_func) {
  442. scene_tree_parse_func(p_command, p_data);
  443. }
  444. // Unknown message...
  445. }
  446. }
  447. void ScriptDebuggerRemote::debug(ScriptLanguage *p_script, bool p_can_continue, bool p_is_error_breakpoint) {
  448. //this function is called when there is a debugger break (bug on script)
  449. //or when execution is paused from editor
  450. if (skip_breakpoints && !p_is_error_breakpoint)
  451. return;
  452. ERR_FAIL_COND_MSG(!is_peer_connected(), "Script Debugger failed to connect, but being used anyway.");
  453. Array msg;
  454. msg.push_back(p_can_continue);
  455. msg.push_back(p_script->debug_get_error());
  456. _put_msg("debug_enter", msg);
  457. skip_profile_frame = true; // to avoid super long frame time for the frame
  458. Input::MouseMode mouse_mode = Input::get_singleton()->get_mouse_mode();
  459. if (mouse_mode != Input::MOUSE_MODE_VISIBLE)
  460. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  461. uint64_t loop_begin_usec = 0;
  462. uint64_t loop_time_sec = 0;
  463. while (true) {
  464. loop_begin_usec = OS::get_singleton()->get_ticks_usec();
  465. _get_output();
  466. if (packet_peer_stream->get_available_packet_count() > 0) {
  467. Variant var;
  468. Error err = packet_peer_stream->get_var(var);
  469. ERR_CONTINUE(err != OK);
  470. ERR_CONTINUE(var.get_type() != Variant::ARRAY);
  471. Array cmd = var;
  472. ERR_CONTINUE(cmd.size() != 2);
  473. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  474. ERR_CONTINUE(cmd[1].get_type() != Variant::ARRAY);
  475. String command = cmd[0];
  476. Array data = cmd[1];
  477. if (command == "step") {
  478. set_depth(-1);
  479. set_lines_left(1);
  480. break;
  481. } else if (command == "next") {
  482. set_depth(0);
  483. set_lines_left(1);
  484. break;
  485. } else if (command == "continue") {
  486. set_depth(-1);
  487. set_lines_left(-1);
  488. OS::get_singleton()->move_window_to_foreground();
  489. break;
  490. } else if (command == "break") {
  491. ERR_PRINT("Got break when already broke!");
  492. break;
  493. }
  494. _parse_message(command, data, p_script);
  495. } else {
  496. OS::get_singleton()->delay_usec(10000);
  497. OS::get_singleton()->process_and_drop_events();
  498. }
  499. // This is for the camera override to stay live even when the game is paused from the editor
  500. loop_time_sec = (OS::get_singleton()->get_ticks_usec() - loop_begin_usec) / 1000000.0f;
  501. VisualServer::get_singleton()->sync();
  502. if (VisualServer::get_singleton()->has_changed()) {
  503. VisualServer::get_singleton()->draw(true, loop_time_sec * Engine::get_singleton()->get_time_scale());
  504. }
  505. }
  506. _put_msg("debug_exit", Array());
  507. if (mouse_mode != Input::MOUSE_MODE_VISIBLE)
  508. Input::get_singleton()->set_mouse_mode(mouse_mode);
  509. }
  510. void ScriptDebuggerRemote::_get_output() {
  511. MutexLock lock(mutex);
  512. if (output_strings.size()) {
  513. locking = true;
  514. while (output_strings.size()) {
  515. Array arr;
  516. arr.push_back(output_strings.front()->get());
  517. _put_msg("output", arr);
  518. output_strings.pop_front();
  519. }
  520. locking = false;
  521. }
  522. if (n_messages_dropped > 0) {
  523. Message msg;
  524. msg.message = "Too many messages! " + String::num_int64(n_messages_dropped) + " messages were dropped.";
  525. messages.push_back(msg);
  526. n_messages_dropped = 0;
  527. }
  528. while (messages.size()) {
  529. locking = true;
  530. Message msg = messages.front()->get();
  531. _put_msg("message:" + msg.message, msg.data);
  532. messages.pop_front();
  533. locking = false;
  534. }
  535. if (n_errors_dropped == 1) {
  536. // Only print one message about dropping per second
  537. OutputError oe;
  538. oe.error = "TOO_MANY_ERRORS";
  539. oe.error_descr = "Too many errors! Ignoring errors for up to 1 second.";
  540. oe.warning = false;
  541. uint64_t time = OS::get_singleton()->get_ticks_msec();
  542. oe.hr = time / 3600000;
  543. oe.min = (time / 60000) % 60;
  544. oe.sec = (time / 1000) % 60;
  545. oe.msec = time % 1000;
  546. errors.push_back(oe);
  547. }
  548. if (n_warnings_dropped == 1) {
  549. // Only print one message about dropping per second
  550. OutputError oe;
  551. oe.error = "TOO_MANY_WARNINGS";
  552. oe.error_descr = "Too many warnings! Ignoring warnings for up to 1 second.";
  553. oe.warning = true;
  554. uint64_t time = OS::get_singleton()->get_ticks_msec();
  555. oe.hr = time / 3600000;
  556. oe.min = (time / 60000) % 60;
  557. oe.sec = (time / 1000) % 60;
  558. oe.msec = time % 1000;
  559. errors.push_back(oe);
  560. }
  561. while (errors.size()) {
  562. locking = true;
  563. OutputError oe = errors.front()->get();
  564. _put_msg("error", oe.serialize());
  565. errors.pop_front();
  566. locking = false;
  567. }
  568. }
  569. void ScriptDebuggerRemote::line_poll() {
  570. //the purpose of this is just processing events every now and then when the script might get too busy
  571. //otherwise bugs like infinite loops can't be caught
  572. if (poll_every % 2048 == 0)
  573. _poll_events();
  574. poll_every++;
  575. }
  576. void ScriptDebuggerRemote::_err_handler(void *ud, const char *p_func, const char *p_file, int p_line, const char *p_err, const char *p_descr, ErrorHandlerType p_type) {
  577. if (p_type == ERR_HANDLER_SCRIPT)
  578. return; //ignore script errors, those go through debugger
  579. Vector<ScriptLanguage::StackInfo> si;
  580. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  581. si = ScriptServer::get_language(i)->debug_get_current_stack_info();
  582. if (si.size())
  583. break;
  584. }
  585. ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)ud;
  586. sdr->send_error(p_func, p_file, p_line, p_err, p_descr, p_type, si);
  587. }
  588. void ScriptDebuggerRemote::_poll_events() {
  589. //this si called from ::idle_poll, happens only when running the game,
  590. //does not get called while on debug break
  591. while (packet_peer_stream->get_available_packet_count() > 0) {
  592. _get_output();
  593. //send over output_strings
  594. Variant var;
  595. Error err = packet_peer_stream->get_var(var);
  596. ERR_CONTINUE(err != OK);
  597. ERR_CONTINUE(var.get_type() != Variant::ARRAY);
  598. Array cmd = var;
  599. ERR_CONTINUE(cmd.size() < 2);
  600. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  601. ERR_CONTINUE(cmd[1].get_type() != Variant::ARRAY);
  602. String command = cmd[0];
  603. Array data = cmd[1];
  604. if (command == "break") {
  605. if (get_break_language())
  606. debug(get_break_language());
  607. } else {
  608. _parse_message(command, data);
  609. }
  610. }
  611. }
  612. void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
  613. int ofs = 0;
  614. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  615. if (p_for_frame)
  616. ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info.write[ofs], profile_info.size() - ofs);
  617. else
  618. ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info.write[ofs], profile_info.size() - ofs);
  619. }
  620. for (int i = 0; i < ofs; i++) {
  621. profile_info_ptrs.write[i] = &profile_info.write[i];
  622. }
  623. SortArray<ScriptLanguage::ProfilingInfo *, ProfileInfoSort> sa;
  624. sa.sort(profile_info_ptrs.ptrw(), ofs);
  625. int to_send = MIN(ofs, max_frame_functions);
  626. //check signatures first
  627. uint64_t total_script_time = 0;
  628. for (int i = 0; i < to_send; i++) {
  629. if (!profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
  630. int idx = profiler_function_signature_map.size();
  631. ProfilerSignature sig;
  632. sig.name = profile_info_ptrs[i]->signature;
  633. sig.id = idx;
  634. _put_msg("profile_sig", sig.serialize());
  635. profiler_function_signature_map[profile_info_ptrs[i]->signature] = idx;
  636. }
  637. total_script_time += profile_info_ptrs[i]->self_time;
  638. }
  639. //send frames then
  640. ProfilerFrame metric;
  641. metric.frame_number = Engine::get_singleton()->get_frames_drawn();
  642. metric.frame_time = frame_time;
  643. metric.idle_time = idle_time;
  644. metric.physics_time = physics_time;
  645. metric.physics_frame_time = physics_frame_time;
  646. metric.script_time = total_script_time;
  647. // Add script functions information.
  648. metric.frame_functions.resize(to_send);
  649. FrameFunction *w = metric.frame_functions.ptrw();
  650. for (int i = 0; i < to_send; i++) {
  651. if (profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
  652. w[i].sig_id = profiler_function_signature_map[profile_info_ptrs[i]->signature];
  653. }
  654. w[i].call_count = profile_info_ptrs[i]->call_count;
  655. w[i].total_time = profile_info_ptrs[i]->total_time / 1000000.0;
  656. w[i].self_time = profile_info_ptrs[i]->self_time / 1000000.0;
  657. }
  658. if (p_for_frame) {
  659. // Add profile frame data information.
  660. metric.frames_data.append_array(profile_frame_data);
  661. _put_msg("profile_frame", metric.serialize());
  662. profile_frame_data.clear();
  663. } else {
  664. _put_msg("profile_total", metric.serialize());
  665. }
  666. }
  667. void ScriptDebuggerRemote::idle_poll() {
  668. // this function is called every frame, except when there is a debugger break (::debug() in this class)
  669. // execution stops and remains in the ::debug function
  670. _get_output();
  671. if (requested_quit) {
  672. _put_msg("kill_me", Array());
  673. requested_quit = false;
  674. }
  675. if (performance) {
  676. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  677. if (pt - last_perf_time > 1000) {
  678. last_perf_time = pt;
  679. int max = performance->get("MONITOR_MAX");
  680. Array arr;
  681. arr.resize(max);
  682. for (int i = 0; i < max; i++) {
  683. arr[i] = performance->call("get_monitor", i);
  684. }
  685. _put_msg("performance", arr);
  686. }
  687. }
  688. if (visual_profiling) {
  689. Vector<VS::FrameProfileArea> profile_areas = VS::get_singleton()->get_frame_profile();
  690. if (profile_areas.size()) {
  691. Vector<String> area_names;
  692. Vector<real_t> area_times;
  693. area_names.resize(profile_areas.size());
  694. area_times.resize(profile_areas.size() * 2);
  695. {
  696. String *area_namesw = area_names.ptrw();
  697. real_t *area_timesw = area_times.ptrw();
  698. for (int i = 0; i < profile_areas.size(); i++) {
  699. area_namesw[i] = profile_areas[i].name;
  700. area_timesw[i * 2 + 0] = profile_areas[i].cpu_msec;
  701. area_timesw[i * 2 + 1] = profile_areas[i].gpu_msec;
  702. }
  703. }
  704. Array msg;
  705. msg.push_back(VS::get_singleton()->get_frame_profile_frame());
  706. msg.push_back(area_names);
  707. msg.push_back(area_times);
  708. _put_msg("visual_profile", msg);
  709. }
  710. }
  711. if (profiling) {
  712. if (skip_profile_frame) {
  713. skip_profile_frame = false;
  714. } else {
  715. //send profiling info normally
  716. _send_profiling_data(true);
  717. }
  718. }
  719. if (network_profiling) {
  720. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  721. if (pt - last_net_bandwidth_time > 200) {
  722. last_net_bandwidth_time = pt;
  723. _send_network_bandwidth_usage();
  724. }
  725. if (pt - last_net_prof_time > 100) {
  726. last_net_prof_time = pt;
  727. _send_network_profiling_data();
  728. }
  729. }
  730. if (reload_all_scripts) {
  731. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  732. ScriptServer::get_language(i)->reload_all_scripts();
  733. }
  734. reload_all_scripts = false;
  735. }
  736. _poll_events();
  737. }
  738. void ScriptDebuggerRemote::_send_network_profiling_data() {
  739. ERR_FAIL_COND(multiplayer.is_null());
  740. int n_nodes = multiplayer->get_profiling_frame(&network_profile_info.write[0]);
  741. NetworkProfilerFrame frame;
  742. for (int i = 0; i < n_nodes; i++) {
  743. frame.infos.push_back(network_profile_info[i]);
  744. }
  745. _put_msg("network_profile", frame.serialize());
  746. }
  747. void ScriptDebuggerRemote::_send_network_bandwidth_usage() {
  748. ERR_FAIL_COND(multiplayer.is_null());
  749. int incoming_bandwidth = multiplayer->get_incoming_bandwidth_usage();
  750. int outgoing_bandwidth = multiplayer->get_outgoing_bandwidth_usage();
  751. Array arr;
  752. arr.push_back(incoming_bandwidth);
  753. arr.push_back(outgoing_bandwidth);
  754. _put_msg("network_bandwidth", arr);
  755. }
  756. void ScriptDebuggerRemote::send_message(const String &p_message, const Array &p_args) {
  757. MutexLock lock(mutex);
  758. if (!locking && is_peer_connected()) {
  759. if (messages.size() >= max_messages_per_frame) {
  760. n_messages_dropped++;
  761. } else {
  762. Message msg;
  763. msg.message = p_message;
  764. msg.data = p_args;
  765. messages.push_back(msg);
  766. }
  767. }
  768. }
  769. void ScriptDebuggerRemote::send_error(const String &p_func, const String &p_file, int p_line, const String &p_err, const String &p_descr, ErrorHandlerType p_type, const Vector<ScriptLanguage::StackInfo> &p_stack_info) {
  770. OutputError oe;
  771. oe.error = p_err;
  772. oe.error_descr = p_descr;
  773. oe.source_file = p_file;
  774. oe.source_line = p_line;
  775. oe.source_func = p_func;
  776. oe.warning = p_type == ERR_HANDLER_WARNING;
  777. uint64_t time = OS::get_singleton()->get_ticks_msec();
  778. oe.hr = time / 3600000;
  779. oe.min = (time / 60000) % 60;
  780. oe.sec = (time / 1000) % 60;
  781. oe.msec = time % 1000;
  782. Array cstack;
  783. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  784. msec_count += ticks - last_msec;
  785. last_msec = ticks;
  786. if (msec_count > 1000) {
  787. msec_count = 0;
  788. err_count = 0;
  789. n_errors_dropped = 0;
  790. warn_count = 0;
  791. n_warnings_dropped = 0;
  792. }
  793. cstack.resize(p_stack_info.size() * 3);
  794. for (int i = 0; i < p_stack_info.size(); i++) {
  795. cstack[i * 3 + 0] = p_stack_info[i].file;
  796. cstack[i * 3 + 1] = p_stack_info[i].func;
  797. cstack[i * 3 + 2] = p_stack_info[i].line;
  798. }
  799. //oe.callstack = cstack;
  800. if (oe.warning) {
  801. warn_count++;
  802. } else {
  803. err_count++;
  804. }
  805. MutexLock lock(mutex);
  806. if (!locking && is_peer_connected()) {
  807. if (oe.warning) {
  808. if (warn_count > max_warnings_per_second) {
  809. n_warnings_dropped++;
  810. } else {
  811. errors.push_back(oe);
  812. }
  813. } else {
  814. if (err_count > max_errors_per_second) {
  815. n_errors_dropped++;
  816. } else {
  817. errors.push_back(oe);
  818. }
  819. }
  820. }
  821. }
  822. void ScriptDebuggerRemote::_print_handler(void *p_this, const String &p_string, bool p_error) {
  823. ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)p_this;
  824. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  825. sdr->msec_count += ticks - sdr->last_msec;
  826. sdr->last_msec = ticks;
  827. if (sdr->msec_count > 1000) {
  828. sdr->char_count = 0;
  829. sdr->msec_count = 0;
  830. }
  831. String s = p_string;
  832. int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count, 0), s.length());
  833. if (allowed_chars == 0)
  834. return;
  835. if (allowed_chars < s.length()) {
  836. s = s.substr(0, allowed_chars);
  837. }
  838. sdr->char_count += allowed_chars;
  839. bool overflowed = sdr->char_count >= sdr->max_cps;
  840. {
  841. MutexLock lock(sdr->mutex);
  842. if (!sdr->locking && sdr->is_peer_connected()) {
  843. if (overflowed)
  844. s += "[...]";
  845. sdr->output_strings.push_back(s);
  846. if (overflowed) {
  847. sdr->output_strings.push_back("[output overflow, print less text!]");
  848. }
  849. }
  850. }
  851. }
  852. void ScriptDebuggerRemote::request_quit() {
  853. requested_quit = true;
  854. }
  855. void ScriptDebuggerRemote::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer) {
  856. multiplayer = p_multiplayer;
  857. }
  858. bool ScriptDebuggerRemote::is_profiling() const {
  859. return profiling;
  860. }
  861. void ScriptDebuggerRemote::add_profiling_frame_data(const StringName &p_name, const Array &p_data) {
  862. int idx = -1;
  863. for (int i = 0; i < profile_frame_data.size(); i++) {
  864. if (profile_frame_data[i].name == p_name) {
  865. idx = i;
  866. break;
  867. }
  868. }
  869. FrameData fd;
  870. fd.name = p_name;
  871. fd.data = p_data;
  872. if (idx == -1) {
  873. profile_frame_data.push_back(fd);
  874. } else {
  875. profile_frame_data.write[idx] = fd;
  876. }
  877. }
  878. void ScriptDebuggerRemote::profiling_start() {
  879. //ignores this, uses it via connection
  880. }
  881. void ScriptDebuggerRemote::profiling_end() {
  882. //ignores this, uses it via connection
  883. }
  884. void ScriptDebuggerRemote::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_physics_time, float p_physics_frame_time) {
  885. frame_time = p_frame_time;
  886. idle_time = p_idle_time;
  887. physics_time = p_physics_time;
  888. physics_frame_time = p_physics_frame_time;
  889. }
  890. void ScriptDebuggerRemote::set_skip_breakpoints(bool p_skip_breakpoints) {
  891. skip_breakpoints = p_skip_breakpoints;
  892. }
  893. ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func = NULL;
  894. ScriptDebuggerRemote::ParseMessageFunc ScriptDebuggerRemote::scene_tree_parse_func = NULL;
  895. ScriptDebuggerRemote::ScriptDebuggerRemote() :
  896. profiling(false),
  897. visual_profiling(false),
  898. network_profiling(false),
  899. max_frame_functions(16),
  900. skip_profile_frame(false),
  901. reload_all_scripts(false),
  902. tcp_client(Ref<StreamPeerTCP>(memnew(StreamPeerTCP))),
  903. packet_peer_stream(Ref<PacketPeerStream>(memnew(PacketPeerStream))),
  904. last_perf_time(0),
  905. last_net_prof_time(0),
  906. last_net_bandwidth_time(0),
  907. performance(Engine::get_singleton()->get_singleton_object("Performance")),
  908. requested_quit(false),
  909. max_messages_per_frame(GLOBAL_GET("network/limits/debugger_stdout/max_messages_per_frame")),
  910. n_messages_dropped(0),
  911. max_errors_per_second(GLOBAL_GET("network/limits/debugger_stdout/max_errors_per_second")),
  912. max_warnings_per_second(GLOBAL_GET("network/limits/debugger_stdout/max_warnings_per_second")),
  913. n_errors_dropped(0),
  914. max_cps(GLOBAL_GET("network/limits/debugger_stdout/max_chars_per_second")),
  915. char_count(0),
  916. err_count(0),
  917. warn_count(0),
  918. last_msec(0),
  919. msec_count(0),
  920. locking(false),
  921. poll_every(0) {
  922. packet_peer_stream->set_stream_peer(tcp_client);
  923. packet_peer_stream->set_output_buffer_max_size((1024 * 1024 * 8) - 4); // 8 MiB should be way more than enough, minus 4 bytes for separator.
  924. phl.printfunc = _print_handler;
  925. phl.userdata = this;
  926. add_print_handler(&phl);
  927. eh.errfunc = _err_handler;
  928. eh.userdata = this;
  929. add_error_handler(&eh);
  930. profile_info.resize(GLOBAL_GET("debug/settings/profiler/max_functions"));
  931. network_profile_info.resize(GLOBAL_GET("debug/settings/profiler/max_functions"));
  932. profile_info_ptrs.resize(profile_info.size());
  933. }
  934. ScriptDebuggerRemote::~ScriptDebuggerRemote() {
  935. remove_print_handler(&phl);
  936. remove_error_handler(&eh);
  937. }