script_debugger_remote.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "engine.h"
  32. #include "io/ip.h"
  33. #include "io/marshalls.h"
  34. #include "os/input.h"
  35. #include "os/os.h"
  36. #include "project_settings.h"
  37. #include "scene/main/node.h"
  38. #include "scene/resources/packed_scene.h"
  39. void ScriptDebuggerRemote::_send_video_memory() {
  40. List<ResourceUsage> usage;
  41. if (resource_usage_func)
  42. resource_usage_func(&usage);
  43. usage.sort();
  44. packet_peer_stream->put_var("message:video_mem");
  45. packet_peer_stream->put_var(usage.size() * 4);
  46. for (List<ResourceUsage>::Element *E = usage.front(); E; E = E->next()) {
  47. packet_peer_stream->put_var(E->get().path);
  48. packet_peer_stream->put_var(E->get().type);
  49. packet_peer_stream->put_var(E->get().format);
  50. packet_peer_stream->put_var(E->get().vram);
  51. }
  52. }
  53. Error ScriptDebuggerRemote::connect_to_host(const String &p_host, uint16_t p_port) {
  54. IP_Address ip;
  55. if (p_host.is_valid_ip_address())
  56. ip = p_host;
  57. else
  58. ip = IP::get_singleton()->resolve_hostname(p_host);
  59. int port = p_port;
  60. const int tries = 6;
  61. int waits[tries] = { 1, 10, 100, 1000, 1000, 1000 };
  62. tcp_client->connect_to_host(ip, port);
  63. for (int i = 0; i < tries; i++) {
  64. if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
  65. break;
  66. } else {
  67. const int ms = waits[i];
  68. OS::get_singleton()->delay_usec(ms * 1000);
  69. print_line("Remote Debugger: Connection failed with status: '" + String::num(tcp_client->get_status()) + "', retrying in " + String::num(ms) + " msec.");
  70. };
  71. };
  72. if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  73. print_line("Remote Debugger: Unable to connect");
  74. return FAILED;
  75. };
  76. // print_line("Remote Debugger: Connection OK!");
  77. packet_peer_stream->set_stream_peer(tcp_client);
  78. return OK;
  79. }
  80. static int _ScriptDebuggerRemote_found_id = 0;
  81. static Object *_ScriptDebuggerRemote_find = NULL;
  82. static void _ScriptDebuggerRemote_debug_func(Object *p_obj) {
  83. if (_ScriptDebuggerRemote_find == p_obj) {
  84. _ScriptDebuggerRemote_found_id = p_obj->get_instance_id();
  85. }
  86. }
  87. static ObjectID safe_get_instance_id(const Variant &p_v) {
  88. Object *o = p_v;
  89. if (o == NULL)
  90. return 0;
  91. else {
  92. REF r = p_v;
  93. if (r.is_valid()) {
  94. return r->get_instance_id();
  95. } else {
  96. _ScriptDebuggerRemote_found_id = 0;
  97. _ScriptDebuggerRemote_find = NULL;
  98. ObjectDB::debug_objects(_ScriptDebuggerRemote_debug_func);
  99. return _ScriptDebuggerRemote_found_id;
  100. }
  101. }
  102. }
  103. void ScriptDebuggerRemote::_put_variable(const String &p_name, const Variant &p_variable) {
  104. packet_peer_stream->put_var(p_name);
  105. Variant var = p_variable;
  106. if (p_variable.get_type() == Variant::OBJECT && !ObjectDB::instance_validate(p_variable)) {
  107. var = Variant();
  108. }
  109. int len = 0;
  110. Error err = encode_variant(var, NULL, len);
  111. if (err != OK)
  112. ERR_PRINT("Failed to encode variant");
  113. if (len > packet_peer_stream->get_output_buffer_max_size()) { //limit to max size
  114. packet_peer_stream->put_var(Variant());
  115. } else {
  116. packet_peer_stream->put_var(var);
  117. }
  118. }
  119. void ScriptDebuggerRemote::_save_node(ObjectID id, const String &p_path) {
  120. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(id));
  121. ERR_FAIL_COND(!node);
  122. Ref<PackedScene> ps = memnew(PackedScene);
  123. ps->pack(node);
  124. ResourceSaver::save(p_path, ps);
  125. }
  126. void ScriptDebuggerRemote::debug(ScriptLanguage *p_script, bool p_can_continue) {
  127. //this function is called when there is a debugger break (bug on script)
  128. //or when execution is paused from editor
  129. if (!tcp_client->is_connected_to_host()) {
  130. ERR_EXPLAIN("Script Debugger failed to connect, but being used anyway.");
  131. ERR_FAIL();
  132. }
  133. if (allow_focus_steal_pid) {
  134. OS::get_singleton()->enable_for_stealing_focus(allow_focus_steal_pid);
  135. }
  136. packet_peer_stream->put_var("debug_enter");
  137. packet_peer_stream->put_var(2);
  138. packet_peer_stream->put_var(p_can_continue);
  139. packet_peer_stream->put_var(p_script->debug_get_error());
  140. skip_profile_frame = true; // to avoid super long frame time for the frame
  141. Input::MouseMode mouse_mode = Input::get_singleton()->get_mouse_mode();
  142. if (mouse_mode != Input::MOUSE_MODE_VISIBLE)
  143. Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
  144. while (true) {
  145. _get_output();
  146. if (packet_peer_stream->get_available_packet_count() > 0) {
  147. Variant var;
  148. Error err = packet_peer_stream->get_var(var);
  149. ERR_CONTINUE(err != OK);
  150. ERR_CONTINUE(var.get_type() != Variant::ARRAY);
  151. Array cmd = var;
  152. ERR_CONTINUE(cmd.size() == 0);
  153. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  154. String command = cmd[0];
  155. if (command == "get_stack_dump") {
  156. packet_peer_stream->put_var("stack_dump");
  157. int slc = p_script->debug_get_stack_level_count();
  158. packet_peer_stream->put_var(slc);
  159. for (int i = 0; i < slc; i++) {
  160. Dictionary d;
  161. d["file"] = p_script->debug_get_stack_level_source(i);
  162. d["line"] = p_script->debug_get_stack_level_line(i);
  163. d["function"] = p_script->debug_get_stack_level_function(i);
  164. //d["id"]=p_script->debug_get_stack_level_
  165. d["id"] = 0;
  166. packet_peer_stream->put_var(d);
  167. }
  168. } else if (command == "get_stack_frame_vars") {
  169. cmd.remove(0);
  170. ERR_CONTINUE(cmd.size() != 1);
  171. int lv = cmd[0];
  172. List<String> members;
  173. List<Variant> member_vals;
  174. if (ScriptInstance *inst = p_script->debug_get_stack_level_instance(lv)) {
  175. members.push_back("self");
  176. member_vals.push_back(inst->get_owner());
  177. }
  178. p_script->debug_get_stack_level_members(lv, &members, &member_vals);
  179. ERR_CONTINUE(members.size() != member_vals.size());
  180. List<String> locals;
  181. List<Variant> local_vals;
  182. p_script->debug_get_stack_level_locals(lv, &locals, &local_vals);
  183. ERR_CONTINUE(locals.size() != local_vals.size());
  184. List<String> globals;
  185. List<Variant> globals_vals;
  186. p_script->debug_get_globals(&globals, &globals_vals);
  187. ERR_CONTINUE(globals.size() != globals_vals.size());
  188. packet_peer_stream->put_var("stack_frame_vars");
  189. packet_peer_stream->put_var(3 + (locals.size() + members.size() + globals.size()) * 2);
  190. { //locals
  191. packet_peer_stream->put_var(locals.size());
  192. List<String>::Element *E = locals.front();
  193. List<Variant>::Element *F = local_vals.front();
  194. while (E) {
  195. _put_variable(E->get(), F->get());
  196. E = E->next();
  197. F = F->next();
  198. }
  199. }
  200. { //members
  201. packet_peer_stream->put_var(members.size());
  202. List<String>::Element *E = members.front();
  203. List<Variant>::Element *F = member_vals.front();
  204. while (E) {
  205. _put_variable(E->get(), F->get());
  206. E = E->next();
  207. F = F->next();
  208. }
  209. }
  210. { //globals
  211. packet_peer_stream->put_var(globals.size());
  212. List<String>::Element *E = globals.front();
  213. List<Variant>::Element *F = globals_vals.front();
  214. while (E) {
  215. _put_variable(E->get(), F->get());
  216. E = E->next();
  217. F = F->next();
  218. }
  219. }
  220. } else if (command == "step") {
  221. set_depth(-1);
  222. set_lines_left(1);
  223. break;
  224. } else if (command == "next") {
  225. set_depth(0);
  226. set_lines_left(1);
  227. break;
  228. } else if (command == "continue") {
  229. set_depth(-1);
  230. set_lines_left(-1);
  231. OS::get_singleton()->move_window_to_foreground();
  232. break;
  233. } else if (command == "break") {
  234. ERR_PRINT("Got break when already broke!");
  235. break;
  236. } else if (command == "request_scene_tree") {
  237. if (request_scene_tree)
  238. request_scene_tree(request_scene_tree_ud);
  239. } else if (command == "request_video_mem") {
  240. _send_video_memory();
  241. } else if (command == "inspect_object") {
  242. ObjectID id = cmd[1];
  243. _send_object_id(id);
  244. } else if (command == "set_object_property") {
  245. _set_object_property(cmd[1], cmd[2], cmd[3]);
  246. } else if (command == "reload_scripts") {
  247. reload_all_scripts = true;
  248. } else if (command == "breakpoint") {
  249. bool set = cmd[3];
  250. if (set)
  251. insert_breakpoint(cmd[2], cmd[1]);
  252. else
  253. remove_breakpoint(cmd[2], cmd[1]);
  254. } else if (command == "save_node") {
  255. _save_node(cmd[1], cmd[2]);
  256. } else {
  257. _parse_live_edit(cmd);
  258. }
  259. } else {
  260. OS::get_singleton()->delay_usec(10000);
  261. }
  262. }
  263. packet_peer_stream->put_var("debug_exit");
  264. packet_peer_stream->put_var(0);
  265. if (mouse_mode != Input::MOUSE_MODE_VISIBLE)
  266. Input::get_singleton()->set_mouse_mode(mouse_mode);
  267. }
  268. void ScriptDebuggerRemote::_get_output() {
  269. mutex->lock();
  270. if (output_strings.size()) {
  271. locking = true;
  272. packet_peer_stream->put_var("output");
  273. packet_peer_stream->put_var(output_strings.size());
  274. while (output_strings.size()) {
  275. packet_peer_stream->put_var(output_strings.front()->get());
  276. output_strings.pop_front();
  277. }
  278. locking = false;
  279. }
  280. if (n_messages_dropped > 0) {
  281. Message msg;
  282. msg.message = "Too many messages! " + String::num_int64(n_messages_dropped) + " messages were dropped.";
  283. messages.push_back(msg);
  284. n_messages_dropped = 0;
  285. }
  286. while (messages.size()) {
  287. locking = true;
  288. packet_peer_stream->put_var("message:" + messages.front()->get().message);
  289. packet_peer_stream->put_var(messages.front()->get().data.size());
  290. for (int i = 0; i < messages.front()->get().data.size(); i++) {
  291. packet_peer_stream->put_var(messages.front()->get().data[i]);
  292. }
  293. messages.pop_front();
  294. locking = false;
  295. }
  296. if (n_errors_dropped > 0) {
  297. OutputError oe;
  298. oe.error = "TOO_MANY_ERRORS";
  299. oe.error_descr = "Too many errors! " + String::num_int64(n_errors_dropped) + " errors were dropped.";
  300. oe.warning = false;
  301. uint64_t time = OS::get_singleton()->get_ticks_msec();
  302. oe.hr = time / 3600000;
  303. oe.min = (time / 60000) % 60;
  304. oe.sec = (time / 1000) % 60;
  305. oe.msec = time % 1000;
  306. errors.push_back(oe);
  307. n_errors_dropped = 0;
  308. }
  309. while (errors.size()) {
  310. locking = true;
  311. packet_peer_stream->put_var("error");
  312. OutputError oe = errors.front()->get();
  313. packet_peer_stream->put_var(oe.callstack.size() + 2);
  314. Array error_data;
  315. error_data.push_back(oe.hr);
  316. error_data.push_back(oe.min);
  317. error_data.push_back(oe.sec);
  318. error_data.push_back(oe.msec);
  319. error_data.push_back(oe.source_func);
  320. error_data.push_back(oe.source_file);
  321. error_data.push_back(oe.source_line);
  322. error_data.push_back(oe.error);
  323. error_data.push_back(oe.error_descr);
  324. error_data.push_back(oe.warning);
  325. packet_peer_stream->put_var(error_data);
  326. packet_peer_stream->put_var(oe.callstack.size());
  327. for (int i = 0; i < oe.callstack.size(); i++) {
  328. packet_peer_stream->put_var(oe.callstack[i]);
  329. }
  330. errors.pop_front();
  331. locking = false;
  332. }
  333. mutex->unlock();
  334. }
  335. void ScriptDebuggerRemote::line_poll() {
  336. //the purpose of this is just processing events every now and then when the script might get too busy
  337. //otherwise bugs like infinite loops can't be caught
  338. if (poll_every % 2048 == 0)
  339. _poll_events();
  340. poll_every++;
  341. }
  342. 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) {
  343. if (p_type == ERR_HANDLER_SCRIPT)
  344. return; //ignore script errors, those go through debugger
  345. Vector<ScriptLanguage::StackInfo> si;
  346. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  347. si = ScriptServer::get_language(i)->debug_get_current_stack_info();
  348. if (si.size())
  349. break;
  350. }
  351. ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)ud;
  352. sdr->send_error(p_func, p_file, p_line, p_err, p_descr, p_type, si);
  353. }
  354. bool ScriptDebuggerRemote::_parse_live_edit(const Array &p_command) {
  355. String cmdstr = p_command[0];
  356. if (!live_edit_funcs || !cmdstr.begins_with("live_"))
  357. return false;
  358. //print_line(Variant(cmd).get_construct_string());
  359. if (cmdstr == "live_set_root") {
  360. if (!live_edit_funcs->root_func)
  361. return true;
  362. //print_line("root: "+Variant(cmd).get_construct_string());
  363. live_edit_funcs->root_func(live_edit_funcs->udata, p_command[1], p_command[2]);
  364. } else if (cmdstr == "live_node_path") {
  365. if (!live_edit_funcs->node_path_func)
  366. return true;
  367. //print_line("path: "+Variant(cmd).get_construct_string());
  368. live_edit_funcs->node_path_func(live_edit_funcs->udata, p_command[1], p_command[2]);
  369. } else if (cmdstr == "live_res_path") {
  370. if (!live_edit_funcs->res_path_func)
  371. return true;
  372. live_edit_funcs->res_path_func(live_edit_funcs->udata, p_command[1], p_command[2]);
  373. } else if (cmdstr == "live_node_prop_res") {
  374. if (!live_edit_funcs->node_set_res_func)
  375. return true;
  376. live_edit_funcs->node_set_res_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  377. } else if (cmdstr == "live_node_prop") {
  378. if (!live_edit_funcs->node_set_func)
  379. return true;
  380. live_edit_funcs->node_set_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  381. } else if (cmdstr == "live_res_prop_res") {
  382. if (!live_edit_funcs->res_set_res_func)
  383. return true;
  384. live_edit_funcs->res_set_res_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  385. } else if (cmdstr == "live_res_prop") {
  386. if (!live_edit_funcs->res_set_func)
  387. return true;
  388. live_edit_funcs->res_set_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  389. } else if (cmdstr == "live_node_call") {
  390. if (!live_edit_funcs->node_call_func)
  391. return true;
  392. live_edit_funcs->node_call_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3], p_command[4], p_command[5], p_command[6], p_command[7]);
  393. } else if (cmdstr == "live_res_call") {
  394. if (!live_edit_funcs->res_call_func)
  395. return true;
  396. live_edit_funcs->res_call_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3], p_command[4], p_command[5], p_command[6], p_command[7]);
  397. } else if (cmdstr == "live_create_node") {
  398. live_edit_funcs->tree_create_node_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  399. } else if (cmdstr == "live_instance_node") {
  400. live_edit_funcs->tree_instance_node_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  401. } else if (cmdstr == "live_remove_node") {
  402. live_edit_funcs->tree_remove_node_func(live_edit_funcs->udata, p_command[1]);
  403. } else if (cmdstr == "live_remove_and_keep_node") {
  404. live_edit_funcs->tree_remove_and_keep_node_func(live_edit_funcs->udata, p_command[1], p_command[2]);
  405. } else if (cmdstr == "live_restore_node") {
  406. live_edit_funcs->tree_restore_node_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3]);
  407. } else if (cmdstr == "live_duplicate_node") {
  408. live_edit_funcs->tree_duplicate_node_func(live_edit_funcs->udata, p_command[1], p_command[2]);
  409. } else if (cmdstr == "live_reparent_node") {
  410. live_edit_funcs->tree_reparent_node_func(live_edit_funcs->udata, p_command[1], p_command[2], p_command[3], p_command[4]);
  411. } else {
  412. return false;
  413. }
  414. return true;
  415. }
  416. void ScriptDebuggerRemote::_send_object_id(ObjectID p_id) {
  417. Object *obj = ObjectDB::get_instance(p_id);
  418. if (!obj)
  419. return;
  420. typedef Pair<PropertyInfo, Variant> PropertyDesc;
  421. List<PropertyDesc> properties;
  422. if (ScriptInstance *si = obj->get_script_instance()) {
  423. if (!si->get_script().is_null()) {
  424. typedef Map<const Script *, Set<StringName> > ScriptMemberMap;
  425. typedef Map<const Script *, Map<StringName, Variant> > ScriptConstantsMap;
  426. ScriptMemberMap members;
  427. members[si->get_script().ptr()] = Set<StringName>();
  428. si->get_script()->get_members(&(members[si->get_script().ptr()]));
  429. ScriptConstantsMap constants;
  430. constants[si->get_script().ptr()] = Map<StringName, Variant>();
  431. si->get_script()->get_constants(&(constants[si->get_script().ptr()]));
  432. Ref<Script> base = si->get_script()->get_base_script();
  433. while (base.is_valid()) {
  434. members[base.ptr()] = Set<StringName>();
  435. base->get_members(&(members[base.ptr()]));
  436. constants[base.ptr()] = Map<StringName, Variant>();
  437. base->get_constants(&(constants[base.ptr()]));
  438. base = base->get_base_script();
  439. }
  440. for (ScriptMemberMap::Element *sm = members.front(); sm; sm = sm->next()) {
  441. for (Set<StringName>::Element *E = sm->get().front(); E; E = E->next()) {
  442. Variant m;
  443. if (si->get(E->get(), m)) {
  444. String script_path = sm->key() == si->get_script().ptr() ? "" : sm->key()->get_path().get_file() + "/";
  445. PropertyInfo pi(m.get_type(), "Members/" + script_path + E->get());
  446. properties.push_back(PropertyDesc(pi, m));
  447. }
  448. }
  449. }
  450. for (ScriptConstantsMap::Element *sc = constants.front(); sc; sc = sc->next()) {
  451. for (Map<StringName, Variant>::Element *E = sc->get().front(); E; E = E->next()) {
  452. String script_path = sc->key() == si->get_script().ptr() ? "" : sc->key()->get_path().get_file() + "/";
  453. PropertyInfo pi(E->value().get_type(), "Constants/" + script_path + E->key());
  454. properties.push_back(PropertyDesc(pi, E->value()));
  455. }
  456. }
  457. }
  458. }
  459. if (Node *node = Object::cast_to<Node>(obj)) {
  460. PropertyInfo pi(Variant::NODE_PATH, String("Node/path"));
  461. properties.push_front(PropertyDesc(pi, node->get_path()));
  462. } else if (Resource *res = Object::cast_to<Resource>(obj)) {
  463. if (Script *s = Object::cast_to<Script>(res)) {
  464. Map<StringName, Variant> constants;
  465. s->get_constants(&constants);
  466. for (Map<StringName, Variant>::Element *E = constants.front(); E; E = E->next()) {
  467. PropertyInfo pi(E->value().get_type(), String("Constants/") + E->key());
  468. properties.push_front(PropertyDesc(pi, E->value()));
  469. }
  470. }
  471. }
  472. List<PropertyInfo> pinfo;
  473. obj->get_property_list(&pinfo, true);
  474. for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
  475. if (E->get().usage & (PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CATEGORY)) {
  476. properties.push_back(PropertyDesc(E->get(), obj->get(E->get().name)));
  477. }
  478. }
  479. Array send_props;
  480. for (int i = 0; i < properties.size(); i++) {
  481. const PropertyInfo &pi = properties[i].first;
  482. Variant &var = properties[i].second;
  483. WeakRef *ref = Object::cast_to<WeakRef>(var);
  484. if (ref) {
  485. var = ref->get_ref();
  486. }
  487. RES res = var;
  488. Array prop;
  489. prop.push_back(pi.name);
  490. prop.push_back(pi.type);
  491. //only send information that can be sent..
  492. int len = 0; //test how big is this to encode
  493. encode_variant(var, NULL, len);
  494. if (len > packet_peer_stream->get_output_buffer_max_size()) { //limit to max size
  495. prop.push_back(PROPERTY_HINT_OBJECT_TOO_BIG);
  496. prop.push_back("");
  497. prop.push_back(pi.usage);
  498. prop.push_back(Variant());
  499. } else {
  500. prop.push_back(pi.hint);
  501. if (res.is_null())
  502. prop.push_back(pi.hint_string);
  503. else
  504. prop.push_back(String("RES:") + res->get_path());
  505. prop.push_back(pi.usage);
  506. prop.push_back(var);
  507. }
  508. send_props.push_back(prop);
  509. }
  510. packet_peer_stream->put_var("message:inspect_object");
  511. packet_peer_stream->put_var(3);
  512. packet_peer_stream->put_var(p_id);
  513. packet_peer_stream->put_var(obj->get_class());
  514. packet_peer_stream->put_var(send_props);
  515. }
  516. void ScriptDebuggerRemote::_set_object_property(ObjectID p_id, const String &p_property, const Variant &p_value) {
  517. Object *obj = ObjectDB::get_instance(p_id);
  518. if (!obj)
  519. return;
  520. String prop_name = p_property;
  521. if (p_property.begins_with("Members/")) {
  522. Vector<String> ss = p_property.split("/");
  523. prop_name = ss[ss.size() - 1];
  524. }
  525. obj->set(prop_name, p_value);
  526. }
  527. void ScriptDebuggerRemote::_poll_events() {
  528. //this si called from ::idle_poll, happens only when running the game,
  529. //does not get called while on debug break
  530. while (packet_peer_stream->get_available_packet_count() > 0) {
  531. _get_output();
  532. //send over output_strings
  533. Variant var;
  534. Error err = packet_peer_stream->get_var(var);
  535. ERR_CONTINUE(err != OK);
  536. ERR_CONTINUE(var.get_type() != Variant::ARRAY);
  537. Array cmd = var;
  538. ERR_CONTINUE(cmd.size() == 0);
  539. ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
  540. String command = cmd[0];
  541. //cmd.remove(0);
  542. if (command == "break") {
  543. if (get_break_language())
  544. debug(get_break_language());
  545. } else if (command == "request_scene_tree") {
  546. if (request_scene_tree)
  547. request_scene_tree(request_scene_tree_ud);
  548. } else if (command == "request_video_mem") {
  549. _send_video_memory();
  550. } else if (command == "inspect_object") {
  551. ObjectID id = cmd[1];
  552. _send_object_id(id);
  553. } else if (command == "set_object_property") {
  554. _set_object_property(cmd[1], cmd[2], cmd[3]);
  555. } else if (command == "start_profiling") {
  556. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  557. ScriptServer::get_language(i)->profiling_start();
  558. }
  559. max_frame_functions = cmd[1];
  560. profiler_function_signature_map.clear();
  561. profiling = true;
  562. frame_time = 0;
  563. idle_time = 0;
  564. physics_time = 0;
  565. physics_frame_time = 0;
  566. print_line("PROFILING ALRIGHT!");
  567. } else if (command == "stop_profiling") {
  568. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  569. ScriptServer::get_language(i)->profiling_stop();
  570. }
  571. profiling = false;
  572. _send_profiling_data(false);
  573. print_line("PROFILING END!");
  574. } else if (command == "reload_scripts") {
  575. reload_all_scripts = true;
  576. } else if (command == "breakpoint") {
  577. bool set = cmd[3];
  578. if (set)
  579. insert_breakpoint(cmd[2], cmd[1]);
  580. else
  581. remove_breakpoint(cmd[2], cmd[1]);
  582. } else {
  583. _parse_live_edit(cmd);
  584. }
  585. }
  586. }
  587. void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
  588. int ofs = 0;
  589. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  590. if (p_for_frame)
  591. ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info.write[ofs], profile_info.size() - ofs);
  592. else
  593. ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info.write[ofs], profile_info.size() - ofs);
  594. }
  595. for (int i = 0; i < ofs; i++) {
  596. profile_info_ptrs.write[i] = &profile_info.write[i];
  597. }
  598. SortArray<ScriptLanguage::ProfilingInfo *, ProfileInfoSort> sa;
  599. sa.sort(profile_info_ptrs.ptrw(), ofs);
  600. int to_send = MIN(ofs, max_frame_functions);
  601. //check signatures first
  602. uint64_t total_script_time = 0;
  603. for (int i = 0; i < to_send; i++) {
  604. if (!profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
  605. int idx = profiler_function_signature_map.size();
  606. packet_peer_stream->put_var("profile_sig");
  607. packet_peer_stream->put_var(2);
  608. packet_peer_stream->put_var(profile_info_ptrs[i]->signature);
  609. packet_peer_stream->put_var(idx);
  610. profiler_function_signature_map[profile_info_ptrs[i]->signature] = idx;
  611. }
  612. total_script_time += profile_info_ptrs[i]->self_time;
  613. }
  614. //send frames then
  615. if (p_for_frame) {
  616. packet_peer_stream->put_var("profile_frame");
  617. packet_peer_stream->put_var(8 + profile_frame_data.size() * 2 + to_send * 4);
  618. } else {
  619. packet_peer_stream->put_var("profile_total");
  620. packet_peer_stream->put_var(8 + to_send * 4);
  621. }
  622. packet_peer_stream->put_var(Engine::get_singleton()->get_frames_drawn()); //total frame time
  623. packet_peer_stream->put_var(frame_time); //total frame time
  624. packet_peer_stream->put_var(idle_time); //idle frame time
  625. packet_peer_stream->put_var(physics_time); //fixed frame time
  626. packet_peer_stream->put_var(physics_frame_time); //fixed frame time
  627. packet_peer_stream->put_var(USEC_TO_SEC(total_script_time)); //total script execution time
  628. if (p_for_frame) {
  629. packet_peer_stream->put_var(profile_frame_data.size()); //how many profile framedatas to send
  630. packet_peer_stream->put_var(to_send); //how many script functions to send
  631. for (int i = 0; i < profile_frame_data.size(); i++) {
  632. packet_peer_stream->put_var(profile_frame_data[i].name);
  633. packet_peer_stream->put_var(profile_frame_data[i].data);
  634. }
  635. } else {
  636. packet_peer_stream->put_var(0); //how many script functions to send
  637. packet_peer_stream->put_var(to_send); //how many script functions to send
  638. }
  639. for (int i = 0; i < to_send; i++) {
  640. int sig_id = -1;
  641. if (profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
  642. sig_id = profiler_function_signature_map[profile_info_ptrs[i]->signature];
  643. }
  644. packet_peer_stream->put_var(sig_id);
  645. packet_peer_stream->put_var(profile_info_ptrs[i]->call_count);
  646. packet_peer_stream->put_var(profile_info_ptrs[i]->total_time / 1000000.0);
  647. packet_peer_stream->put_var(profile_info_ptrs[i]->self_time / 1000000.0);
  648. }
  649. if (p_for_frame) {
  650. profile_frame_data.clear();
  651. }
  652. }
  653. void ScriptDebuggerRemote::idle_poll() {
  654. // this function is called every frame, except when there is a debugger break (::debug() in this class)
  655. // execution stops and remains in the ::debug function
  656. _get_output();
  657. if (requested_quit) {
  658. packet_peer_stream->put_var("kill_me");
  659. packet_peer_stream->put_var(0);
  660. requested_quit = false;
  661. }
  662. if (performance) {
  663. uint64_t pt = OS::get_singleton()->get_ticks_msec();
  664. if (pt - last_perf_time > 1000) {
  665. last_perf_time = pt;
  666. int max = performance->get("MONITOR_MAX");
  667. Array arr;
  668. arr.resize(max);
  669. for (int i = 0; i < max; i++) {
  670. arr[i] = performance->call("get_monitor", i);
  671. }
  672. packet_peer_stream->put_var("performance");
  673. packet_peer_stream->put_var(1);
  674. packet_peer_stream->put_var(arr);
  675. }
  676. }
  677. if (profiling) {
  678. if (skip_profile_frame) {
  679. skip_profile_frame = false;
  680. } else {
  681. //send profiling info normally
  682. _send_profiling_data(true);
  683. }
  684. }
  685. if (reload_all_scripts) {
  686. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  687. ScriptServer::get_language(i)->reload_all_scripts();
  688. }
  689. reload_all_scripts = false;
  690. }
  691. _poll_events();
  692. }
  693. void ScriptDebuggerRemote::send_message(const String &p_message, const Array &p_args) {
  694. mutex->lock();
  695. if (!locking && tcp_client->is_connected_to_host()) {
  696. if (messages.size() >= max_messages_per_frame) {
  697. n_messages_dropped++;
  698. } else {
  699. Message msg;
  700. msg.message = p_message;
  701. msg.data = p_args;
  702. messages.push_back(msg);
  703. }
  704. }
  705. mutex->unlock();
  706. }
  707. 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) {
  708. OutputError oe;
  709. oe.error = p_err;
  710. oe.error_descr = p_descr;
  711. oe.source_file = p_file;
  712. oe.source_line = p_line;
  713. oe.source_func = p_func;
  714. oe.warning = p_type == ERR_HANDLER_WARNING;
  715. uint64_t time = OS::get_singleton()->get_ticks_msec();
  716. oe.hr = time / 3600000;
  717. oe.min = (time / 60000) % 60;
  718. oe.sec = (time / 1000) % 60;
  719. oe.msec = time % 1000;
  720. Array cstack;
  721. cstack.resize(p_stack_info.size() * 3);
  722. for (int i = 0; i < p_stack_info.size(); i++) {
  723. cstack[i * 3 + 0] = p_stack_info[i].file;
  724. cstack[i * 3 + 1] = p_stack_info[i].func;
  725. cstack[i * 3 + 2] = p_stack_info[i].line;
  726. }
  727. oe.callstack = cstack;
  728. mutex->lock();
  729. if (!locking && tcp_client->is_connected_to_host()) {
  730. if (errors.size() >= max_errors_per_frame) {
  731. n_errors_dropped++;
  732. } else {
  733. errors.push_back(oe);
  734. }
  735. }
  736. mutex->unlock();
  737. }
  738. void ScriptDebuggerRemote::_print_handler(void *p_this, const String &p_string, bool p_error) {
  739. ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)p_this;
  740. uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
  741. sdr->msec_count += ticks - sdr->last_msec;
  742. sdr->last_msec = ticks;
  743. if (sdr->msec_count > 1000) {
  744. sdr->char_count = 0;
  745. sdr->msec_count = 0;
  746. }
  747. String s = p_string;
  748. int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count, 0), s.length());
  749. if (allowed_chars == 0)
  750. return;
  751. if (allowed_chars < s.length()) {
  752. s = s.substr(0, allowed_chars);
  753. }
  754. sdr->char_count += allowed_chars;
  755. bool overflowed = sdr->char_count >= sdr->max_cps;
  756. sdr->mutex->lock();
  757. if (!sdr->locking && sdr->tcp_client->is_connected_to_host()) {
  758. if (overflowed)
  759. s += "[...]";
  760. sdr->output_strings.push_back(s);
  761. if (overflowed) {
  762. sdr->output_strings.push_back("[output overflow, print less text!]");
  763. }
  764. }
  765. sdr->mutex->unlock();
  766. }
  767. void ScriptDebuggerRemote::request_quit() {
  768. requested_quit = true;
  769. }
  770. void ScriptDebuggerRemote::set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata) {
  771. request_scene_tree = p_func;
  772. request_scene_tree_ud = p_udata;
  773. }
  774. void ScriptDebuggerRemote::set_live_edit_funcs(LiveEditFuncs *p_funcs) {
  775. live_edit_funcs = p_funcs;
  776. }
  777. bool ScriptDebuggerRemote::is_profiling() const {
  778. return profiling;
  779. }
  780. void ScriptDebuggerRemote::add_profiling_frame_data(const StringName &p_name, const Array &p_data) {
  781. int idx = -1;
  782. for (int i = 0; i < profile_frame_data.size(); i++) {
  783. if (profile_frame_data[i].name == p_name) {
  784. idx = i;
  785. break;
  786. }
  787. }
  788. FrameData fd;
  789. fd.name = p_name;
  790. fd.data = p_data;
  791. if (idx == -1) {
  792. profile_frame_data.push_back(fd);
  793. } else {
  794. profile_frame_data.write[idx] = fd;
  795. }
  796. }
  797. void ScriptDebuggerRemote::profiling_start() {
  798. //ignores this, uses it via connection
  799. }
  800. void ScriptDebuggerRemote::profiling_end() {
  801. //ignores this, uses it via connection
  802. }
  803. void ScriptDebuggerRemote::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_physics_time, float p_physics_frame_time) {
  804. frame_time = p_frame_time;
  805. idle_time = p_idle_time;
  806. physics_time = p_physics_time;
  807. physics_frame_time = p_physics_frame_time;
  808. }
  809. void ScriptDebuggerRemote::set_allow_focus_steal_pid(OS::ProcessID p_pid) {
  810. allow_focus_steal_pid = p_pid;
  811. }
  812. ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func = NULL;
  813. ScriptDebuggerRemote::ScriptDebuggerRemote() :
  814. profiling(false),
  815. max_frame_functions(16),
  816. skip_profile_frame(false),
  817. reload_all_scripts(false),
  818. tcp_client(StreamPeerTCP::create_ref()),
  819. packet_peer_stream(Ref<PacketPeerStream>(memnew(PacketPeerStream))),
  820. last_perf_time(0),
  821. performance(Engine::get_singleton()->get_singleton_object("Performance")),
  822. requested_quit(false),
  823. mutex(Mutex::create()),
  824. max_cps(GLOBAL_GET("network/limits/debugger_stdout/max_chars_per_second")),
  825. max_messages_per_frame(GLOBAL_GET("network/limits/debugger_stdout/max_messages_per_frame")),
  826. max_errors_per_frame(GLOBAL_GET("network/limits/debugger_stdout/max_errors_per_frame")),
  827. char_count(0),
  828. n_messages_dropped(0),
  829. n_errors_dropped(0),
  830. last_msec(0),
  831. msec_count(0),
  832. allow_focus_steal_pid(0),
  833. locking(false),
  834. poll_every(0),
  835. request_scene_tree(NULL),
  836. live_edit_funcs(NULL) {
  837. packet_peer_stream->set_stream_peer(tcp_client);
  838. packet_peer_stream->set_output_buffer_max_size(1024 * 1024 * 8); //8mb should be way more than enough
  839. phl.printfunc = _print_handler;
  840. phl.userdata = this;
  841. add_print_handler(&phl);
  842. eh.errfunc = _err_handler;
  843. eh.userdata = this;
  844. add_error_handler(&eh);
  845. profile_info.resize(CLAMP(int(ProjectSettings::get_singleton()->get("debug/settings/profiler/max_functions")), 128, 65535));
  846. profile_info_ptrs.resize(profile_info.size());
  847. }
  848. ScriptDebuggerRemote::~ScriptDebuggerRemote() {
  849. remove_print_handler(&phl);
  850. remove_error_handler(&eh);
  851. memdelete(mutex);
  852. }