script_debugger_remote.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. mutex->lock();
  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. mutex->unlock();
  569. }
  570. void ScriptDebuggerRemote::line_poll() {
  571. //the purpose of this is just processing events every now and then when the script might get too busy
  572. //otherwise bugs like infinite loops can't be caught
  573. if (poll_every % 2048 == 0)
  574. _poll_events();
  575. poll_every++;
  576. }
  577. 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) {
  578. if (p_type == ERR_HANDLER_SCRIPT)
  579. return; //ignore script errors, those go through debugger
  580. Vector<ScriptLanguage::StackInfo> si;
  581. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  582. si = ScriptServer::get_language(i)->debug_get_current_stack_info();
  583. if (si.size())
  584. break;
  585. }
  586. ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)ud;
  587. sdr->send_error(p_func, p_file, p_line, p_err, p_descr, p_type, si);
  588. }
  589. void ScriptDebuggerRemote::_poll_events() {
  590. //this si called from ::idle_poll, happens only when running the game,
  591. //does not get called while on debug break
  592. while (packet_peer_stream->get_available_packet_count() > 0) {
  593. _get_output();
  594. //send over output_strings
  595. Variant var;
  596. Error err = packet_peer_stream->get_var(var);
  597. ERR_CONTINUE(err != OK);
  598. ERR_CONTINUE(var.get_type() != Variant::ARRAY);
  599. Array cmd = var;
  600. ERR_CONTINUE(cmd.size() < 2);
  601. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  602. ERR_CONTINUE(cmd[1].get_type() != Variant::ARRAY);
  603. String command = cmd[0];
  604. Array data = cmd[1];
  605. if (command == "break") {
  606. if (get_break_language())
  607. debug(get_break_language());
  608. } else {
  609. _parse_message(command, data);
  610. }
  611. }
  612. }
  613. void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
  614. int ofs = 0;
  615. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  616. if (p_for_frame)
  617. ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info.write[ofs], profile_info.size() - ofs);
  618. else
  619. ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info.write[ofs], profile_info.size() - ofs);
  620. }
  621. for (int i = 0; i < ofs; i++) {
  622. profile_info_ptrs.write[i] = &profile_info.write[i];
  623. }
  624. SortArray<ScriptLanguage::ProfilingInfo *, ProfileInfoSort> sa;
  625. sa.sort(profile_info_ptrs.ptrw(), ofs);
  626. int to_send = MIN(ofs, max_frame_functions);
  627. //check signatures first
  628. uint64_t total_script_time = 0;
  629. for (int i = 0; i < to_send; i++) {
  630. if (!profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
  631. int idx = profiler_function_signature_map.size();
  632. ProfilerSignature sig;
  633. sig.name = profile_info_ptrs[i]->signature;
  634. sig.id = idx;
  635. _put_msg("profile_sig", sig.serialize());
  636. profiler_function_signature_map[profile_info_ptrs[i]->signature] = idx;
  637. }
  638. total_script_time += profile_info_ptrs[i]->self_time;
  639. }
  640. //send frames then
  641. ProfilerFrame metric;
  642. metric.frame_number = Engine::get_singleton()->get_frames_drawn();
  643. metric.frame_time = frame_time;
  644. metric.idle_time = idle_time;
  645. metric.physics_time = physics_time;
  646. metric.physics_frame_time = physics_frame_time;
  647. metric.script_time = total_script_time;
  648. // Add script functions information.
  649. metric.frame_functions.resize(to_send);
  650. FrameFunction *w = metric.frame_functions.ptrw();
  651. for (int i = 0; i < to_send; i++) {
  652. if (profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
  653. w[i].sig_id = profiler_function_signature_map[profile_info_ptrs[i]->signature];
  654. }
  655. w[i].call_count = profile_info_ptrs[i]->call_count;
  656. w[i].total_time = profile_info_ptrs[i]->total_time / 1000000.0;
  657. w[i].self_time = profile_info_ptrs[i]->self_time / 1000000.0;
  658. }
  659. if (p_for_frame) {
  660. // Add profile frame data information.
  661. metric.frames_data.append_array(profile_frame_data);
  662. _put_msg("profile_frame", metric.serialize());
  663. profile_frame_data.clear();
  664. } else {
  665. _put_msg("profile_total", metric.serialize());
  666. }
  667. }
  668. void ScriptDebuggerRemote::idle_poll() {
  669. // this function is called every frame, except when there is a debugger break (::debug() in this class)
  670. // execution stops and remains in the ::debug function
  671. _get_output();
  672. if (requested_quit) {
  673. _put_msg("kill_me", Array());
  674. requested_quit = false;
  675. }
  676. if (performance) {
  677. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  678. if (pt - last_perf_time > 1000) {
  679. last_perf_time = pt;
  680. int max = performance->get("MONITOR_MAX");
  681. Array arr;
  682. arr.resize(max);
  683. for (int i = 0; i < max; i++) {
  684. arr[i] = performance->call("get_monitor", i);
  685. }
  686. _put_msg("performance", arr);
  687. }
  688. }
  689. if (visual_profiling) {
  690. Vector<VS::FrameProfileArea> profile_areas = VS::get_singleton()->get_frame_profile();
  691. if (profile_areas.size()) {
  692. Vector<String> area_names;
  693. Vector<real_t> area_times;
  694. area_names.resize(profile_areas.size());
  695. area_times.resize(profile_areas.size() * 2);
  696. {
  697. String *area_namesw = area_names.ptrw();
  698. real_t *area_timesw = area_times.ptrw();
  699. for (int i = 0; i < profile_areas.size(); i++) {
  700. area_namesw[i] = profile_areas[i].name;
  701. area_timesw[i * 2 + 0] = profile_areas[i].cpu_msec;
  702. area_timesw[i * 2 + 1] = profile_areas[i].gpu_msec;
  703. }
  704. }
  705. Array msg;
  706. msg.push_back(VS::get_singleton()->get_frame_profile_frame());
  707. msg.push_back(area_names);
  708. msg.push_back(area_times);
  709. _put_msg("visual_profile", msg);
  710. }
  711. }
  712. if (profiling) {
  713. if (skip_profile_frame) {
  714. skip_profile_frame = false;
  715. } else {
  716. //send profiling info normally
  717. _send_profiling_data(true);
  718. }
  719. }
  720. if (network_profiling) {
  721. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  722. if (pt - last_net_bandwidth_time > 200) {
  723. last_net_bandwidth_time = pt;
  724. _send_network_bandwidth_usage();
  725. }
  726. if (pt - last_net_prof_time > 100) {
  727. last_net_prof_time = pt;
  728. _send_network_profiling_data();
  729. }
  730. }
  731. if (reload_all_scripts) {
  732. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  733. ScriptServer::get_language(i)->reload_all_scripts();
  734. }
  735. reload_all_scripts = false;
  736. }
  737. _poll_events();
  738. }
  739. void ScriptDebuggerRemote::_send_network_profiling_data() {
  740. ERR_FAIL_COND(multiplayer.is_null());
  741. int n_nodes = multiplayer->get_profiling_frame(&network_profile_info.write[0]);
  742. NetworkProfilerFrame frame;
  743. for (int i = 0; i < n_nodes; i++) {
  744. frame.infos.push_back(network_profile_info[i]);
  745. }
  746. _put_msg("network_profile", frame.serialize());
  747. }
  748. void ScriptDebuggerRemote::_send_network_bandwidth_usage() {
  749. ERR_FAIL_COND(multiplayer.is_null());
  750. int incoming_bandwidth = multiplayer->get_incoming_bandwidth_usage();
  751. int outgoing_bandwidth = multiplayer->get_outgoing_bandwidth_usage();
  752. Array arr;
  753. arr.push_back(incoming_bandwidth);
  754. arr.push_back(outgoing_bandwidth);
  755. _put_msg("network_bandwidth", arr);
  756. }
  757. void ScriptDebuggerRemote::send_message(const String &p_message, const Array &p_args) {
  758. mutex->lock();
  759. if (!locking && is_peer_connected()) {
  760. if (messages.size() >= max_messages_per_frame) {
  761. n_messages_dropped++;
  762. } else {
  763. Message msg;
  764. msg.message = p_message;
  765. msg.data = p_args;
  766. messages.push_back(msg);
  767. }
  768. }
  769. mutex->unlock();
  770. }
  771. 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) {
  772. OutputError oe;
  773. oe.error = p_err;
  774. oe.error_descr = p_descr;
  775. oe.source_file = p_file;
  776. oe.source_line = p_line;
  777. oe.source_func = p_func;
  778. oe.warning = p_type == ERR_HANDLER_WARNING;
  779. uint64_t time = OS::get_singleton()->get_ticks_msec();
  780. oe.hr = time / 3600000;
  781. oe.min = (time / 60000) % 60;
  782. oe.sec = (time / 1000) % 60;
  783. oe.msec = time % 1000;
  784. Array cstack;
  785. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  786. msec_count += ticks - last_msec;
  787. last_msec = ticks;
  788. if (msec_count > 1000) {
  789. msec_count = 0;
  790. err_count = 0;
  791. n_errors_dropped = 0;
  792. warn_count = 0;
  793. n_warnings_dropped = 0;
  794. }
  795. cstack.resize(p_stack_info.size() * 3);
  796. for (int i = 0; i < p_stack_info.size(); i++) {
  797. cstack[i * 3 + 0] = p_stack_info[i].file;
  798. cstack[i * 3 + 1] = p_stack_info[i].func;
  799. cstack[i * 3 + 2] = p_stack_info[i].line;
  800. }
  801. //oe.callstack = cstack;
  802. if (oe.warning) {
  803. warn_count++;
  804. } else {
  805. err_count++;
  806. }
  807. mutex->lock();
  808. if (!locking && is_peer_connected()) {
  809. if (oe.warning) {
  810. if (warn_count > max_warnings_per_second) {
  811. n_warnings_dropped++;
  812. } else {
  813. errors.push_back(oe);
  814. }
  815. } else {
  816. if (err_count > max_errors_per_second) {
  817. n_errors_dropped++;
  818. } else {
  819. errors.push_back(oe);
  820. }
  821. }
  822. }
  823. mutex->unlock();
  824. }
  825. void ScriptDebuggerRemote::_print_handler(void *p_this, const String &p_string, bool p_error) {
  826. ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)p_this;
  827. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  828. sdr->msec_count += ticks - sdr->last_msec;
  829. sdr->last_msec = ticks;
  830. if (sdr->msec_count > 1000) {
  831. sdr->char_count = 0;
  832. sdr->msec_count = 0;
  833. }
  834. String s = p_string;
  835. int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count, 0), s.length());
  836. if (allowed_chars == 0)
  837. return;
  838. if (allowed_chars < s.length()) {
  839. s = s.substr(0, allowed_chars);
  840. }
  841. sdr->char_count += allowed_chars;
  842. bool overflowed = sdr->char_count >= sdr->max_cps;
  843. sdr->mutex->lock();
  844. if (!sdr->locking && sdr->is_peer_connected()) {
  845. if (overflowed)
  846. s += "[...]";
  847. sdr->output_strings.push_back(s);
  848. if (overflowed) {
  849. sdr->output_strings.push_back("[output overflow, print less text!]");
  850. }
  851. }
  852. sdr->mutex->unlock();
  853. }
  854. void ScriptDebuggerRemote::request_quit() {
  855. requested_quit = true;
  856. }
  857. void ScriptDebuggerRemote::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer) {
  858. multiplayer = p_multiplayer;
  859. }
  860. bool ScriptDebuggerRemote::is_profiling() const {
  861. return profiling;
  862. }
  863. void ScriptDebuggerRemote::add_profiling_frame_data(const StringName &p_name, const Array &p_data) {
  864. int idx = -1;
  865. for (int i = 0; i < profile_frame_data.size(); i++) {
  866. if (profile_frame_data[i].name == p_name) {
  867. idx = i;
  868. break;
  869. }
  870. }
  871. FrameData fd;
  872. fd.name = p_name;
  873. fd.data = p_data;
  874. if (idx == -1) {
  875. profile_frame_data.push_back(fd);
  876. } else {
  877. profile_frame_data.write[idx] = fd;
  878. }
  879. }
  880. void ScriptDebuggerRemote::profiling_start() {
  881. //ignores this, uses it via connection
  882. }
  883. void ScriptDebuggerRemote::profiling_end() {
  884. //ignores this, uses it via connection
  885. }
  886. void ScriptDebuggerRemote::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_physics_time, float p_physics_frame_time) {
  887. frame_time = p_frame_time;
  888. idle_time = p_idle_time;
  889. physics_time = p_physics_time;
  890. physics_frame_time = p_physics_frame_time;
  891. }
  892. void ScriptDebuggerRemote::set_skip_breakpoints(bool p_skip_breakpoints) {
  893. skip_breakpoints = p_skip_breakpoints;
  894. }
  895. ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func = NULL;
  896. ScriptDebuggerRemote::ParseMessageFunc ScriptDebuggerRemote::scene_tree_parse_func = NULL;
  897. ScriptDebuggerRemote::ScriptDebuggerRemote() :
  898. profiling(false),
  899. visual_profiling(false),
  900. network_profiling(false),
  901. max_frame_functions(16),
  902. skip_profile_frame(false),
  903. reload_all_scripts(false),
  904. tcp_client(Ref<StreamPeerTCP>(memnew(StreamPeerTCP))),
  905. packet_peer_stream(Ref<PacketPeerStream>(memnew(PacketPeerStream))),
  906. last_perf_time(0),
  907. last_net_prof_time(0),
  908. last_net_bandwidth_time(0),
  909. performance(Engine::get_singleton()->get_singleton_object("Performance")),
  910. requested_quit(false),
  911. mutex(Mutex::create()),
  912. max_messages_per_frame(GLOBAL_GET("network/limits/debugger_stdout/max_messages_per_frame")),
  913. n_messages_dropped(0),
  914. max_errors_per_second(GLOBAL_GET("network/limits/debugger_stdout/max_errors_per_second")),
  915. max_warnings_per_second(GLOBAL_GET("network/limits/debugger_stdout/max_warnings_per_second")),
  916. n_errors_dropped(0),
  917. max_cps(GLOBAL_GET("network/limits/debugger_stdout/max_chars_per_second")),
  918. char_count(0),
  919. err_count(0),
  920. warn_count(0),
  921. last_msec(0),
  922. msec_count(0),
  923. locking(false),
  924. poll_every(0) {
  925. packet_peer_stream->set_stream_peer(tcp_client);
  926. 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.
  927. phl.printfunc = _print_handler;
  928. phl.userdata = this;
  929. add_print_handler(&phl);
  930. eh.errfunc = _err_handler;
  931. eh.userdata = this;
  932. add_error_handler(&eh);
  933. profile_info.resize(GLOBAL_GET("debug/settings/profiler/max_functions"));
  934. network_profile_info.resize(GLOBAL_GET("debug/settings/profiler/max_functions"));
  935. profile_info_ptrs.resize(profile_info.size());
  936. }
  937. ScriptDebuggerRemote::~ScriptDebuggerRemote() {
  938. remove_print_handler(&phl);
  939. remove_error_handler(&eh);
  940. memdelete(mutex);
  941. }