Path: blob/master/editor/debugger/debug_adapter/debug_adapter_parser.cpp
20931 views
/**************************************************************************/1/* debug_adapter_parser.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "debug_adapter_parser.h"3132#include "editor/debugger/debug_adapter/debug_adapter_protocol.h"33#include "editor/debugger/editor_debugger_node.h"34#include "editor/debugger/script_editor_debugger.h"35#include "editor/export/editor_export.h"36#include "editor/export/editor_export_platform.h"37#include "editor/run/editor_run_bar.h"38#include "editor/script/script_editor_plugin.h"3940void DebugAdapterParser::_bind_methods() {41// Requests42ClassDB::bind_method(D_METHOD("req_initialize", "params"), &DebugAdapterParser::req_initialize);43ClassDB::bind_method(D_METHOD("req_disconnect", "params"), &DebugAdapterParser::req_disconnect);44ClassDB::bind_method(D_METHOD("req_launch", "params"), &DebugAdapterParser::req_launch);45ClassDB::bind_method(D_METHOD("req_attach", "params"), &DebugAdapterParser::req_attach);46ClassDB::bind_method(D_METHOD("req_restart", "params"), &DebugAdapterParser::req_restart);47ClassDB::bind_method(D_METHOD("req_terminate", "params"), &DebugAdapterParser::req_terminate);48ClassDB::bind_method(D_METHOD("req_configurationDone", "params"), &DebugAdapterParser::req_configurationDone);49ClassDB::bind_method(D_METHOD("req_pause", "params"), &DebugAdapterParser::req_pause);50ClassDB::bind_method(D_METHOD("req_continue", "params"), &DebugAdapterParser::req_continue);51ClassDB::bind_method(D_METHOD("req_threads", "params"), &DebugAdapterParser::req_threads);52ClassDB::bind_method(D_METHOD("req_stackTrace", "params"), &DebugAdapterParser::req_stackTrace);53ClassDB::bind_method(D_METHOD("req_setBreakpoints", "params"), &DebugAdapterParser::req_setBreakpoints);54ClassDB::bind_method(D_METHOD("req_breakpointLocations", "params"), &DebugAdapterParser::req_breakpointLocations);55ClassDB::bind_method(D_METHOD("req_scopes", "params"), &DebugAdapterParser::req_scopes);56ClassDB::bind_method(D_METHOD("req_variables", "params"), &DebugAdapterParser::req_variables);57ClassDB::bind_method(D_METHOD("req_next", "params"), &DebugAdapterParser::req_next);58ClassDB::bind_method(D_METHOD("req_stepIn", "params"), &DebugAdapterParser::req_stepIn);59ClassDB::bind_method(D_METHOD("req_evaluate", "params"), &DebugAdapterParser::req_evaluate);60ClassDB::bind_method(D_METHOD("req_godot/put_msg", "params"), &DebugAdapterParser::req_godot_put_msg);61}6263Dictionary DebugAdapterParser::prepare_base_event() const {64Dictionary event;65event["type"] = "event";6667return event;68}6970Dictionary DebugAdapterParser::prepare_success_response(const Dictionary &p_params) const {71Dictionary response;72response["type"] = "response";73response["request_seq"] = p_params["seq"];74response["command"] = p_params["command"];75response["success"] = true;7677return response;78}7980Dictionary DebugAdapterParser::prepare_error_response(const Dictionary &p_params, DAP::ErrorType err_type, const Dictionary &variables) const {81Dictionary response, body;82response["type"] = "response";83response["request_seq"] = p_params["seq"];84response["command"] = p_params["command"];85response["success"] = false;86response["body"] = body;8788DAP::Message message;89String error, error_desc;90switch (err_type) {91case DAP::ErrorType::WRONG_PATH:92error = "wrong_path";93error_desc = "The editor and client are working on different paths; the client is on \"{clientPath}\", but the editor is on \"{editorPath}\"";94break;95case DAP::ErrorType::NOT_RUNNING:96error = "not_running";97error_desc = "Can't attach to a running session since there isn't one.";98break;99case DAP::ErrorType::TIMEOUT:100error = "timeout";101error_desc = "Timeout reached while processing a request.";102break;103case DAP::ErrorType::UNKNOWN_PLATFORM:104error = "unknown_platform";105error_desc = "The specified platform is unknown.";106break;107case DAP::ErrorType::MISSING_DEVICE:108error = "missing_device";109error_desc = "There's no connected device with specified id.";110break;111case DAP::ErrorType::UNKNOWN:112default:113error = "unknown";114error_desc = "An unknown error has occurred when processing the request.";115break;116}117118message.id = err_type;119message.format = error_desc;120message.variables = variables;121response["message"] = error;122body["error"] = message.to_json();123124return response;125}126127Dictionary DebugAdapterParser::req_initialize(const Dictionary &p_params) const {128Dictionary response = prepare_success_response(p_params);129Dictionary args = p_params["arguments"];130131Ref<DAPeer> peer = DebugAdapterProtocol::get_singleton()->get_current_peer();132133peer->linesStartAt1 = args.get("linesStartAt1", false);134peer->columnsStartAt1 = args.get("columnsStartAt1", false);135peer->supportsVariableType = args.get("supportsVariableType", false);136peer->supportsInvalidatedEvent = args.get("supportsInvalidatedEvent", false);137138DAP::Capabilities caps;139response["body"] = caps.to_json();140141DebugAdapterProtocol::get_singleton()->notify_initialized();142143if (DebugAdapterProtocol::get_singleton()->_sync_breakpoints) {144// Send all current breakpoints145List<String> breakpoints;146ScriptEditor::get_singleton()->get_breakpoints(&breakpoints);147for (const String &breakpoint : breakpoints) {148String path = breakpoint.left(breakpoint.find_char(':', 6)); // Skip initial part of path, aka "res://"149int line = breakpoint.substr(path.size()).to_int();150151DebugAdapterProtocol::get_singleton()->on_debug_breakpoint_toggled(path, line, true);152}153} else {154// Remove all current breakpoints155EditorDebuggerNode::get_singleton()->get_default_debugger()->_clear_breakpoints();156}157158return response;159}160161Dictionary DebugAdapterParser::req_disconnect(const Dictionary &p_params) const {162if (!DebugAdapterProtocol::get_singleton()->get_current_peer()->attached) {163EditorRunBar::get_singleton()->stop_playing();164}165166return prepare_success_response(p_params);167}168169Dictionary DebugAdapterParser::req_launch(const Dictionary &p_params) const {170Dictionary args = p_params["arguments"];171if (args.has("project") && !is_valid_path(args["project"])) {172Dictionary variables;173variables["clientPath"] = args["project"];174variables["editorPath"] = ProjectSettings::get_singleton()->get_resource_path();175return prepare_error_response(p_params, DAP::ErrorType::WRONG_PATH, variables);176}177178if (args.has("godot/custom_data")) {179DebugAdapterProtocol::get_singleton()->get_current_peer()->supportsCustomData = args["godot/custom_data"];180}181182DebugAdapterProtocol::get_singleton()->get_current_peer()->pending_launch = p_params;183184return Dictionary();185}186187Vector<String> DebugAdapterParser::_extract_play_arguments(const Dictionary &p_args) const {188Vector<String> play_args;189if (p_args.has("playArgs")) {190Variant v = p_args["playArgs"];191if (v.get_type() == Variant::ARRAY) {192Array arr = v;193for (const Variant &arg : arr) {194play_args.push_back(String(arg));195}196}197}198return play_args;199}200201Dictionary DebugAdapterParser::_launch_process(const Dictionary &p_params) const {202Dictionary args = p_params["arguments"];203ScriptEditorDebugger *dbg = EditorDebuggerNode::get_singleton()->get_default_debugger();204if ((bool)args["noDebug"] != dbg->is_skip_breakpoints()) {205dbg->debug_skip_breakpoints();206}207208String platform_string = args.get("platform", "host");209if (platform_string == "host") {210Vector<String> play_args = _extract_play_arguments(args);211const String scene = args.get("scene", "main");212if (scene == "main") {213EditorRunBar::get_singleton()->play_main_scene(false, play_args);214} else if (scene == "current") {215EditorRunBar::get_singleton()->play_current_scene(false, play_args);216} else {217EditorRunBar::get_singleton()->play_custom_scene(scene, play_args);218}219} else {220// Not limited to Android, iOS, Web.221const int platform_idx = EditorExport::get_singleton()->get_export_platform_index_by_name(platform_string);222if (platform_idx == -1) {223return prepare_error_response(p_params, DAP::ErrorType::UNKNOWN_PLATFORM);224}225226// If it is not passed, would mean first device of this platform.227const int device_idx = args.get("device", 0);228229const EditorRunBar *run_bar = EditorRunBar::get_singleton();230const int encoded_id = EditorExport::encode_platform_device_id(platform_idx, device_idx);231const Error err = run_bar->start_native_device(encoded_id);232if (err) {233if (err == ERR_INVALID_PARAMETER) {234return prepare_error_response(p_params, DAP::ErrorType::MISSING_DEVICE);235} else {236return prepare_error_response(p_params, DAP::ErrorType::UNKNOWN);237}238}239}240241DebugAdapterProtocol::get_singleton()->get_current_peer()->attached = false;242DebugAdapterProtocol::get_singleton()->notify_process();243244return prepare_success_response(p_params);245}246247Dictionary DebugAdapterParser::req_attach(const Dictionary &p_params) const {248ScriptEditorDebugger *dbg = EditorDebuggerNode::get_singleton()->get_default_debugger();249if (!dbg->is_session_active()) {250return prepare_error_response(p_params, DAP::ErrorType::NOT_RUNNING);251}252253DebugAdapterProtocol::get_singleton()->get_current_peer()->attached = true;254DebugAdapterProtocol::get_singleton()->notify_process();255return prepare_success_response(p_params);256}257258Dictionary DebugAdapterParser::req_restart(const Dictionary &p_params) const {259// Extract embedded "arguments" so it can be given to req_launch/req_attach260Dictionary params = p_params, args;261args = params["arguments"];262args = args["arguments"];263params["arguments"] = args;264265Dictionary response = DebugAdapterProtocol::get_singleton()->get_current_peer()->attached ? req_attach(params) : _launch_process(params);266if (!response["success"]) {267response["command"] = p_params["command"];268return response;269}270271return prepare_success_response(p_params);272}273274Dictionary DebugAdapterParser::req_terminate(const Dictionary &p_params) const {275EditorRunBar::get_singleton()->stop_playing();276277return prepare_success_response(p_params);278}279280Dictionary DebugAdapterParser::req_configurationDone(const Dictionary &p_params) const {281Ref<DAPeer> peer = DebugAdapterProtocol::get_singleton()->get_current_peer();282if (!peer->pending_launch.is_empty()) {283peer->res_queue.push_back(_launch_process(peer->pending_launch));284peer->pending_launch.clear();285}286287return prepare_success_response(p_params);288}289290Dictionary DebugAdapterParser::req_pause(const Dictionary &p_params) const {291EditorRunBar::get_singleton()->get_pause_button()->set_pressed(true);292EditorDebuggerNode::get_singleton()->_paused();293294DebugAdapterProtocol::get_singleton()->notify_stopped_paused();295296return prepare_success_response(p_params);297}298299Dictionary DebugAdapterParser::req_continue(const Dictionary &p_params) const {300EditorRunBar::get_singleton()->get_pause_button()->set_pressed(false);301EditorDebuggerNode::get_singleton()->_paused();302303DebugAdapterProtocol::get_singleton()->notify_continued();304305return prepare_success_response(p_params);306}307308Dictionary DebugAdapterParser::req_threads(const Dictionary &p_params) const {309Dictionary response = prepare_success_response(p_params), body;310response["body"] = body;311312DAP::Thread thread;313314thread.id = 1; // Hardcoded because Godot only supports debugging one thread at the moment315thread.name = "Main";316Array arr = { thread.to_json() };317body["threads"] = arr;318319return response;320}321322Dictionary DebugAdapterParser::req_stackTrace(const Dictionary &p_params) const {323if (DebugAdapterProtocol::get_singleton()->_processing_stackdump) {324return Dictionary();325}326327Dictionary response = prepare_success_response(p_params), body;328response["body"] = body;329330bool lines_at_one = DebugAdapterProtocol::get_singleton()->get_current_peer()->linesStartAt1;331bool columns_at_one = DebugAdapterProtocol::get_singleton()->get_current_peer()->columnsStartAt1;332333Array arr;334DebugAdapterProtocol *dap = DebugAdapterProtocol::get_singleton();335for (DAP::StackFrame sf : dap->stackframe_list) {336if (!lines_at_one) {337sf.line--;338}339if (!columns_at_one) {340sf.column--;341}342343arr.push_back(sf.to_json());344}345346body["stackFrames"] = arr;347return response;348}349350Dictionary DebugAdapterParser::req_setBreakpoints(const Dictionary &p_params) const {351Dictionary response = prepare_success_response(p_params), body;352response["body"] = body;353354Dictionary args = p_params["arguments"];355DAP::Source source;356source.from_json(args["source"]);357358bool lines_at_one = DebugAdapterProtocol::get_singleton()->get_current_peer()->linesStartAt1;359360if (!is_valid_path(source.path)) {361Dictionary variables;362variables["clientPath"] = source.path;363variables["editorPath"] = ProjectSettings::get_singleton()->get_resource_path();364return prepare_error_response(p_params, DAP::ErrorType::WRONG_PATH, variables);365}366367// If path contains \, it's a Windows path, so we need to convert it to /, and make the drive letter uppercase368if (source.path.contains_char('\\')) {369source.path = source.path.replace_char('\\', '/');370source.path = source.path.substr(0, 1).to_upper() + source.path.substr(1);371}372373Array breakpoints = args["breakpoints"], lines;374for (int i = 0; i < breakpoints.size(); i++) {375DAP::SourceBreakpoint breakpoint;376breakpoint.from_json(breakpoints[i]);377378lines.push_back(breakpoint.line + !lines_at_one);379}380381// Always update the source checksum for the requested path, as it might have been modified externally.382DebugAdapterProtocol::get_singleton()->update_source(source.path);383Array updated_breakpoints = DebugAdapterProtocol::get_singleton()->update_breakpoints(source.path, lines);384body["breakpoints"] = updated_breakpoints;385386return response;387}388389Dictionary DebugAdapterParser::req_breakpointLocations(const Dictionary &p_params) const {390Dictionary response = prepare_success_response(p_params), body;391response["body"] = body;392Dictionary args = p_params["arguments"];393394DAP::BreakpointLocation location;395location.line = args["line"];396if (args.has("endLine")) {397location.endLine = args["endLine"];398}399Array locations = { location.to_json() };400401body["breakpoints"] = locations;402return response;403}404405Dictionary DebugAdapterParser::req_scopes(const Dictionary &p_params) const {406Dictionary response = prepare_success_response(p_params), body;407response["body"] = body;408409Dictionary args = p_params["arguments"];410int frame_id = args["frameId"];411Array scope_list;412413HashMap<DebugAdapterProtocol::DAPStackFrameID, Vector<int>>::Iterator E = DebugAdapterProtocol::get_singleton()->scope_list.find(frame_id);414if (E) {415const Vector<int> &scope_ids = E->value;416ERR_FAIL_COND_V(scope_ids.size() != 3, prepare_error_response(p_params, DAP::ErrorType::UNKNOWN));417for (int i = 0; i < 3; ++i) {418DAP::Scope scope;419scope.variablesReference = scope_ids[i];420switch (i) {421case 0:422scope.name = "Locals";423scope.presentationHint = "locals";424break;425case 1:426scope.name = "Members";427scope.presentationHint = "members";428break;429case 2:430scope.name = "Globals";431scope.presentationHint = "globals";432}433434scope_list.push_back(scope.to_json());435}436}437438EditorDebuggerNode::get_singleton()->get_default_debugger()->request_stack_dump(frame_id);439DebugAdapterProtocol::get_singleton()->_current_frame = frame_id;440441body["scopes"] = scope_list;442return response;443}444445Dictionary DebugAdapterParser::req_variables(const Dictionary &p_params) const {446// If _remaining_vars > 0, the debuggee is still sending a stack dump to the editor.447if (DebugAdapterProtocol::get_singleton()->_remaining_vars > 0) {448return Dictionary();449}450451Dictionary args = p_params["arguments"];452int variable_id = args["variablesReference"];453454if (HashMap<int, Array>::Iterator E = DebugAdapterProtocol::get_singleton()->variable_list.find(variable_id); E) {455Dictionary response = prepare_success_response(p_params);456Dictionary body;457response["body"] = body;458459if (!DebugAdapterProtocol::get_singleton()->get_current_peer()->supportsVariableType) {460for (int i = 0; i < E->value.size(); i++) {461Dictionary variable = E->value[i];462variable.erase("type");463}464}465466body["variables"] = E ? E->value : Array();467return response;468} else {469// If the requested variable is an object, it needs to be requested from the debuggee.470ObjectID object_id = DebugAdapterProtocol::get_singleton()->search_object_id(variable_id);471472if (object_id.is_null()) {473return prepare_error_response(p_params, DAP::ErrorType::UNKNOWN);474}475476DebugAdapterProtocol::get_singleton()->request_remote_object(object_id);477}478return Dictionary();479}480481Dictionary DebugAdapterParser::req_next(const Dictionary &p_params) const {482EditorDebuggerNode::get_singleton()->get_default_debugger()->debug_next();483DebugAdapterProtocol::get_singleton()->_stepping = true;484485return prepare_success_response(p_params);486}487488Dictionary DebugAdapterParser::req_stepIn(const Dictionary &p_params) const {489EditorDebuggerNode::get_singleton()->get_default_debugger()->debug_step();490DebugAdapterProtocol::get_singleton()->_stepping = true;491492return prepare_success_response(p_params);493}494495Dictionary DebugAdapterParser::req_evaluate(const Dictionary &p_params) const {496Dictionary args = p_params["arguments"];497String expression = args["expression"];498int frame_id = args.has("frameId") ? static_cast<int>(args["frameId"]) : DebugAdapterProtocol::get_singleton()->_current_frame;499500if (HashMap<String, DAP::Variable>::Iterator E = DebugAdapterProtocol::get_singleton()->eval_list.find(expression); E) {501Dictionary response = prepare_success_response(p_params);502Dictionary body;503response["body"] = body;504505DAP::Variable var = E->value;506507body["result"] = var.value;508body["variablesReference"] = var.variablesReference;509510// Since an evaluation can alter the state of the debuggee, they are volatile, and should only be used once511DebugAdapterProtocol::get_singleton()->eval_list.erase(E->key);512return response;513} else {514DebugAdapterProtocol::get_singleton()->request_remote_evaluate(expression, frame_id);515}516return Dictionary();517}518519Dictionary DebugAdapterParser::req_godot_put_msg(const Dictionary &p_params) const {520Dictionary args = p_params["arguments"];521522String msg = args["message"];523Array data = args["data"];524525EditorDebuggerNode::get_singleton()->get_default_debugger()->_put_msg(msg, data);526527return prepare_success_response(p_params);528}529530Dictionary DebugAdapterParser::ev_initialized() const {531Dictionary event = prepare_base_event();532event["event"] = "initialized";533534return event;535}536537Dictionary DebugAdapterParser::ev_process(const String &p_command) const {538Dictionary event = prepare_base_event(), body;539event["event"] = "process";540event["body"] = body;541542body["name"] = OS::get_singleton()->get_executable_path();543body["startMethod"] = p_command;544545return event;546}547548Dictionary DebugAdapterParser::ev_terminated() const {549Dictionary event = prepare_base_event();550event["event"] = "terminated";551552return event;553}554555Dictionary DebugAdapterParser::ev_exited(const int &p_exitcode) const {556Dictionary event = prepare_base_event(), body;557event["event"] = "exited";558event["body"] = body;559560body["exitCode"] = p_exitcode;561562return event;563}564565Dictionary DebugAdapterParser::ev_stopped() const {566Dictionary event = prepare_base_event(), body;567event["event"] = "stopped";568event["body"] = body;569570body["threadId"] = 1;571572return event;573}574575Dictionary DebugAdapterParser::ev_stopped_paused() const {576Dictionary event = ev_stopped();577Dictionary body = event["body"];578579body["reason"] = "paused";580body["description"] = "Paused";581582return event;583}584585Dictionary DebugAdapterParser::ev_stopped_exception(const String &p_error) const {586Dictionary event = ev_stopped();587Dictionary body = event["body"];588589body["reason"] = "exception";590body["description"] = "Exception";591body["text"] = p_error;592593return event;594}595596Dictionary DebugAdapterParser::ev_stopped_breakpoint(const int &p_id) const {597Dictionary event = ev_stopped();598Dictionary body = event["body"];599600body["reason"] = "breakpoint";601body["description"] = "Breakpoint";602603Array breakpoints = { p_id };604body["hitBreakpointIds"] = breakpoints;605606return event;607}608609Dictionary DebugAdapterParser::ev_stopped_step() const {610Dictionary event = ev_stopped();611Dictionary body = event["body"];612613body["reason"] = "step";614body["description"] = "Breakpoint";615616return event;617}618619Dictionary DebugAdapterParser::ev_continued() const {620Dictionary event = prepare_base_event(), body;621event["event"] = "continued";622event["body"] = body;623624body["threadId"] = 1;625626return event;627}628629Dictionary DebugAdapterParser::ev_output(const String &p_message, RemoteDebugger::MessageType p_type) const {630Dictionary event = prepare_base_event(), body;631event["event"] = "output";632event["body"] = body;633634body["category"] = (p_type == RemoteDebugger::MessageType::MESSAGE_TYPE_ERROR) ? "stderr" : "stdout";635body["output"] = p_message + "\r\n";636637return event;638}639640Dictionary DebugAdapterParser::ev_breakpoint(const DAP::Breakpoint &p_breakpoint, const bool &p_enabled) const {641Dictionary event = prepare_base_event(), body;642event["event"] = "breakpoint";643event["body"] = body;644645body["reason"] = p_enabled ? "new" : "removed";646body["breakpoint"] = p_breakpoint.to_json();647648return event;649}650651Dictionary DebugAdapterParser::ev_custom_data(const String &p_msg, const Array &p_data) const {652Dictionary event = prepare_base_event(), body;653event["event"] = "godot/custom_data";654event["body"] = body;655656body["message"] = p_msg;657body["data"] = p_data;658659return event;660}661662663