https://github.com/ashgti created https://github.com/llvm/llvm-project/pull/181930
Reverts llvm/llvm-project#181261 Breaking builds on linux, reverting while I investigate. >From 09addf916714a7405d9bedc07f4d48a7052938b1 Mon Sep 17 00:00:00 2001 From: John Harrison <[email protected]> Date: Tue, 17 Feb 2026 14:48:41 -0800 Subject: [PATCH] Revert "[lldb-dap] Validate utf8 protocol messages. (#181261)" This reverts commit 24c120406ad58fbecb96cdc6afc75cb466515193. --- .../lldb-dap/variables/TestDAP_variables.py | 46 ++---- .../API/tools/lldb-dap/variables/main.cpp | 4 - lldb/tools/lldb-dap/DAP.cpp | 37 ++--- lldb/tools/lldb-dap/DAP.h | 10 +- .../Handler/CompileUnitsRequestHandler.cpp | 2 +- .../tools/lldb-dap/Handler/RequestHandler.cpp | 14 +- lldb/tools/lldb-dap/JSONUtils.cpp | 10 +- lldb/tools/lldb-dap/JSONUtils.h | 6 +- lldb/tools/lldb-dap/LLDBUtils.cpp | 4 +- lldb/tools/lldb-dap/LLDBUtils.h | 5 +- lldb/tools/lldb-dap/Protocol/DAPTypes.h | 8 +- lldb/tools/lldb-dap/Protocol/ProtocolBase.cpp | 55 ++----- lldb/tools/lldb-dap/Protocol/ProtocolBase.h | 108 ++------------ .../lldb-dap/Protocol/ProtocolRequests.cpp | 10 +- .../lldb-dap/Protocol/ProtocolRequests.h | 100 ++++++------- lldb/tools/lldb-dap/Protocol/ProtocolTypes.h | 134 +++++++++--------- lldb/tools/lldb-dap/ProtocolUtils.cpp | 5 +- lldb/tools/lldb-dap/tool/lldb-dap.cpp | 4 +- lldb/unittests/DAP/CMakeLists.txt | 1 - lldb/unittests/DAP/ProtocolBaseTest.cpp | 29 ---- lldb/unittests/DAP/ProtocolTypesTest.cpp | 2 +- lldb/unittests/DAP/TestBase.cpp | 2 +- lldb/unittests/DAP/VariablesTest.cpp | 3 +- 23 files changed, 213 insertions(+), 386 deletions(-) delete mode 100644 lldb/unittests/DAP/ProtocolBaseTest.cpp diff --git a/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py b/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py index 9de3e1af2dd20..10c67a94407e6 100644 --- a/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py +++ b/lldb/test/API/tools/lldb-dap/variables/TestDAP_variables.py @@ -193,8 +193,6 @@ def do_test_scopes_variables_setVariable_evaluate( }, "readOnly": True, }, - "valid_str": {}, - "malformed_str": {}, "x": {"equals": {"type": "int"}}, } @@ -347,9 +345,9 @@ def do_test_scopes_variables_setVariable_evaluate( verify_locals["argc"]["equals"]["value"] = "123" verify_locals["pt"]["children"]["x"]["equals"]["value"] = "111" - verify_locals["x @ main.cpp:23"] = {"equals": {"type": "int", "value": "89"}} - verify_locals["x @ main.cpp:25"] = {"equals": {"type": "int", "value": "42"}} - verify_locals["x @ main.cpp:27"] = {"equals": {"type": "int", "value": "72"}} + verify_locals["x @ main.cpp:19"] = {"equals": {"type": "int", "value": "89"}} + verify_locals["x @ main.cpp:21"] = {"equals": {"type": "int", "value": "42"}} + verify_locals["x @ main.cpp:23"] = {"equals": {"type": "int", "value": "72"}} self.verify_variables(verify_locals, self.dap_server.get_local_variables()) @@ -357,22 +355,22 @@ def do_test_scopes_variables_setVariable_evaluate( self.assertFalse(self.set_local("x2", 9)["success"]) self.assertFalse(self.set_local("x @ main.cpp:0", 9)["success"]) - self.assertTrue(self.set_local("x @ main.cpp:23", 19)["success"]) - self.assertTrue(self.set_local("x @ main.cpp:25", 21)["success"]) - self.assertTrue(self.set_local("x @ main.cpp:27", 23)["success"]) + self.assertTrue(self.set_local("x @ main.cpp:19", 19)["success"]) + self.assertTrue(self.set_local("x @ main.cpp:21", 21)["success"]) + self.assertTrue(self.set_local("x @ main.cpp:23", 23)["success"]) # The following should have no effect - self.assertFalse(self.set_local("x @ main.cpp:27", "invalid")["success"]) + self.assertFalse(self.set_local("x @ main.cpp:23", "invalid")["success"]) - verify_locals["x @ main.cpp:23"]["equals"]["value"] = "19" - verify_locals["x @ main.cpp:25"]["equals"]["value"] = "21" - verify_locals["x @ main.cpp:27"]["equals"]["value"] = "23" + verify_locals["x @ main.cpp:19"]["equals"]["value"] = "19" + verify_locals["x @ main.cpp:21"]["equals"]["value"] = "21" + verify_locals["x @ main.cpp:23"]["equals"]["value"] = "23" self.verify_variables(verify_locals, self.dap_server.get_local_variables()) # The plain x variable shold refer to the innermost x self.assertTrue(self.set_local("x", 22)["success"]) - verify_locals["x @ main.cpp:27"]["equals"]["value"] = "22" + verify_locals["x @ main.cpp:23"]["equals"]["value"] = "22" self.verify_variables(verify_locals, self.dap_server.get_local_variables()) @@ -389,9 +387,9 @@ def do_test_scopes_variables_setVariable_evaluate( names = [var["name"] for var in locals] # The first shadowed x shouldn't have a suffix anymore verify_locals["x"] = {"equals": {"type": "int", "value": "19"}} + self.assertNotIn("x @ main.cpp:19", names) + self.assertNotIn("x @ main.cpp:21", names) self.assertNotIn("x @ main.cpp:23", names) - self.assertNotIn("x @ main.cpp:25", names) - self.assertNotIn("x @ main.cpp:27", names) self.verify_variables(verify_locals, locals) @@ -462,22 +460,6 @@ def do_test_scopes_and_evaluate_expansion(self, enableAutoVariableSummaries: boo }, "readOnly": True, }, - "valid_str": { - "equals": { - "type": "const char *", - }, - "matches": { - "value": r'0x\w+ "πΆπ°LπΎπ CππΌπ΄π"', - }, - }, - "malformed_str": { - "equals": { - "type": "const char *", - }, - "matches": { - "value": r'0x\w+ "lone trailing \\x81\\x82 bytes"', - }, - }, "x": { "equals": {"type": "int"}, "missing": ["indexedVariables"], @@ -718,8 +700,6 @@ def test_return_variables(self): "argc": {}, "argv": {}, "pt": {"readOnly": True}, - "valid_str": {}, - "malformed_str": {}, "x": {}, "return_result": {"equals": {"type": "int"}}, } diff --git a/lldb/test/API/tools/lldb-dap/variables/main.cpp b/lldb/test/API/tools/lldb-dap/variables/main.cpp index 04fc62f02c22f..0e363001f2f42 100644 --- a/lldb/test/API/tools/lldb-dap/variables/main.cpp +++ b/lldb/test/API/tools/lldb-dap/variables/main.cpp @@ -5,7 +5,6 @@ struct PointType { int y; int buffer[BUFFER_SIZE]; }; -#include <cstdio> #include <vector> int g_global = 123; static int s_global = 234; @@ -17,9 +16,6 @@ int main(int argc, char const *argv[]) { PointType pt = {11, 22, {0}}; for (int i = 0; i < BUFFER_SIZE; ++i) pt.buffer[i] = i; - const char *valid_str = "πΆπ°LπΎπ CππΌπ΄π"; - const char *malformed_str = "lone trailing \x81\x82 bytes"; - printf("print malformed utf8 %s %s\n", valid_str, malformed_str); int x = s_global - g_global - pt.y; // breakpoint 1 { int x = 42; diff --git a/lldb/tools/lldb-dap/DAP.cpp b/lldb/tools/lldb-dap/DAP.cpp index fcfd1da3878e8..6d5e175ae29e0 100644 --- a/lldb/tools/lldb-dap/DAP.cpp +++ b/lldb/tools/lldb-dap/DAP.cpp @@ -124,7 +124,7 @@ static std::string capitalize(llvm::StringRef str) { llvm::StringRef DAP::debug_adapter_path = ""; DAP::DAP(Log &log, const ReplMode default_repl_mode, - const std::vector<String> &pre_init_commands, bool no_lldbinit, + std::vector<std::string> pre_init_commands, bool no_lldbinit, llvm::StringRef client_name, DAPTransport &transport, MainLoop &loop) : log(log), transport(transport), reference_storage(log), broadcaster("lldb-dap"), @@ -132,7 +132,7 @@ DAP::DAP(Log &log, const ReplMode default_repl_mode, [&](const ProgressEvent &event) { SendJSON(event.ToJSON()); }), repl_mode(default_repl_mode), no_lldbinit(no_lldbinit), m_client_name(client_name), m_loop(loop) { - configuration.preInitCommands = pre_init_commands; + configuration.preInitCommands = std::move(pre_init_commands); RegisterRequests(); } @@ -413,10 +413,9 @@ void DAP::SendOutput(OutputType o, const llvm::StringRef output) { if (end == llvm::StringRef::npos) end = output.size() - 1; llvm::json::Object event(CreateEventObject("output")); - llvm::json::Object body{ - {"category", category}, - {"output", protocol::String(output.slice(idx, end + 1))}, - }; + llvm::json::Object body; + body.try_emplace("category", category); + EmplaceSafeString(body, "output", output.slice(idx, end + 1).str()); event.try_emplace("body", std::move(body)); SendJSON(llvm::json::Value(std::move(event))); idx = end + 1; @@ -724,7 +723,7 @@ DAP::ResolveAssemblySource(lldb::SBAddress address) { } bool DAP::RunLLDBCommands(llvm::StringRef prefix, - llvm::ArrayRef<String> commands) { + llvm::ArrayRef<std::string> commands) { bool required_command_failed = false; std::string output = ::RunLLDBCommands( debugger, prefix, commands, required_command_failed, @@ -743,13 +742,15 @@ static llvm::Error createRunLLDBCommandsErrorMessage(llvm::StringRef category) { .c_str()); } -llvm::Error DAP::RunAttachCommands(llvm::ArrayRef<String> attach_commands) { +llvm::Error +DAP::RunAttachCommands(llvm::ArrayRef<std::string> attach_commands) { if (!RunLLDBCommands("Running attachCommands:", attach_commands)) return createRunLLDBCommandsErrorMessage("attach"); return llvm::Error::success(); } -llvm::Error DAP::RunLaunchCommands(llvm::ArrayRef<String> launch_commands) { +llvm::Error +DAP::RunLaunchCommands(llvm::ArrayRef<std::string> launch_commands) { if (!RunLLDBCommands("Running launchCommands:", launch_commands)) return createRunLLDBCommandsErrorMessage("launch"); return llvm::Error::success(); @@ -801,9 +802,9 @@ lldb::SBTarget DAP::CreateTarget(lldb::SBError &error) { // omitted at all), so it is good to leave the user an opportunity to specify // those. Any of those three can be left empty. auto target = this->debugger.CreateTarget( - /*filename=*/configuration.program.c_str(), - /*target_triple=*/configuration.targetTriple.c_str(), - /*platform_name=*/configuration.platformName.c_str(), + /*filename=*/configuration.program.data(), + /*target_triple=*/configuration.targetTriple.data(), + /*platform_name=*/configuration.platformName.data(), /*add_dependent_modules=*/true, // Add dependent modules. error); @@ -848,7 +849,8 @@ bool DAP::HandleObject(const Message &M) { }); auto handler_pos = request_handlers.find(req->command); - dispatcher.Set("client_data", "request_command:" + req->command); + dispatcher.Set("client_data", + llvm::Twine("request_command:", req->command).str()); if (handler_pos != request_handlers.end()) { handler_pos->second->Run(*req); } else { @@ -876,13 +878,14 @@ bool DAP::HandleObject(const Message &M) { // Result should be given, use null if not. if (resp->success) { (*response_handler)(resp->body); - dispatcher.Set("client_data", "response_command:" + resp->command); + dispatcher.Set("client_data", + llvm::Twine("response_command:", resp->command).str()); } else { llvm::StringRef message = "Unknown error, response failed"; if (resp->message) { message = std::visit(llvm::makeVisitor( - [](const String &message) -> llvm::StringRef { + [](const std::string &message) -> llvm::StringRef { return message; }, [](const protocol::ResponseMessage &message) @@ -966,7 +969,7 @@ void DAP::ClearCancelRequest(const CancelArguments &args) { template <typename T> static std::optional<T> getArgumentsIfRequest(const Request &req, - const protocol::String &command) { + llvm::StringLiteral command) { if (req.command != command) return std::nullopt; @@ -1264,7 +1267,7 @@ protocol::Capabilities DAP::GetCapabilities() { capabilities.exceptionBreakpointFilters = std::move(filters); // FIXME: This should be registered based on the supported languages? - std::vector<String> completion_characters; + std::vector<std::string> completion_characters; completion_characters.emplace_back("."); // FIXME: I wonder if we should remove this key... its very aggressive // triggering and accepting completions. diff --git a/lldb/tools/lldb-dap/DAP.h b/lldb/tools/lldb-dap/DAP.h index 9457628aa0f42..a164cc484f4be 100644 --- a/lldb/tools/lldb-dap/DAP.h +++ b/lldb/tools/lldb-dap/DAP.h @@ -194,7 +194,7 @@ struct DAP final : public DAPTransport::MessageHandler { /// \param[in] loop /// Main loop associated with this instance. DAP(Log &log, const ReplMode default_repl_mode, - const std::vector<protocol::String> &pre_init_commands, bool no_lldbinit, + std::vector<std::string> pre_init_commands, bool no_lldbinit, llvm::StringRef client_name, DAPTransport &transport, lldb_private::MainLoop &loop); @@ -314,12 +314,10 @@ struct DAP final : public DAPTransport::MessageHandler { /// \b false if a fatal error was found while executing these commands, /// according to the rules of \a LLDBUtils::RunLLDBCommands. bool RunLLDBCommands(llvm::StringRef prefix, - llvm::ArrayRef<protocol::String> commands); + llvm::ArrayRef<std::string> commands); - llvm::Error - RunAttachCommands(llvm::ArrayRef<protocol::String> attach_commands); - llvm::Error - RunLaunchCommands(llvm::ArrayRef<protocol::String> launch_commands); + llvm::Error RunAttachCommands(llvm::ArrayRef<std::string> attach_commands); + llvm::Error RunLaunchCommands(llvm::ArrayRef<std::string> launch_commands); llvm::Error RunPreInitCommands(); llvm::Error RunInitCommands(); llvm::Error RunPreRunCommands(); diff --git a/lldb/tools/lldb-dap/Handler/CompileUnitsRequestHandler.cpp b/lldb/tools/lldb-dap/Handler/CompileUnitsRequestHandler.cpp index d24072c8cc05d..e1a3b15b4697b 100644 --- a/lldb/tools/lldb-dap/Handler/CompileUnitsRequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/CompileUnitsRequestHandler.cpp @@ -30,7 +30,7 @@ llvm::Expected<CompileUnitsResponseBody> CompileUnitsRequestHandler::Run( int num_modules = dap.target.GetNumModules(); for (int i = 0; i < num_modules; i++) { auto curr_module = dap.target.GetModuleAtIndex(i); - if (args->moduleId == curr_module.GetUUIDString()) { + if (args->moduleId == llvm::StringRef(curr_module.GetUUIDString())) { int num_units = curr_module.GetNumCompileUnits(); for (int j = 0; j < num_units; j++) { auto curr_unit = curr_module.GetCompileUnitAtIndex(j); diff --git a/lldb/tools/lldb-dap/Handler/RequestHandler.cpp b/lldb/tools/lldb-dap/Handler/RequestHandler.cpp index 5e8c2163c838f..47ae9a7195a7d 100644 --- a/lldb/tools/lldb-dap/Handler/RequestHandler.cpp +++ b/lldb/tools/lldb-dap/Handler/RequestHandler.cpp @@ -37,7 +37,8 @@ using namespace lldb_dap::protocol; namespace lldb_dap { -static std::vector<const char *> MakeArgv(const llvm::ArrayRef<String> &strs) { +static std::vector<const char *> +MakeArgv(const llvm::ArrayRef<std::string> &strs) { // Create and return an array of "const char *", one for each C string in // "strs" and terminate the list with a NULL. This can be used for argument // vectors (argv) or environment vectors (envp) like those passed to the @@ -59,8 +60,9 @@ static uint32_t SetLaunchFlag(uint32_t flags, bool flag, return flags; } -static void SetupIORedirection(const std::vector<std::optional<String>> &stdio, - lldb::SBLaunchInfo &launch_info) { +static void +SetupIORedirection(const std::vector<std::optional<std::string>> &stdio, + lldb::SBLaunchInfo &launch_info) { for (const auto &[idx, value_opt] : llvm::enumerate(stdio)) { if (!value_opt) continue; @@ -189,7 +191,7 @@ void BaseRequestHandler::Run(const Request &request) { llvm::Error BaseRequestHandler::LaunchProcess( const protocol::LaunchRequestArguments &arguments) const { - const std::vector<String> &launchCommands = arguments.launchCommands; + const std::vector<std::string> &launchCommands = arguments.launchCommands; // Instantiate a launch info instance for the target. auto launch_info = dap.target.GetLaunchInfo(); @@ -338,8 +340,8 @@ void BaseRequestHandler::BuildErrorResponse( error_message.format = err.getMessage(); error_message.showUser = err.getShowUser(); error_message.id = err.convertToErrorCode().value(); - error_message.url = err.getURL().value_or(""); - error_message.urlLabel = err.getURLLabel().value_or(""); + error_message.url = err.getURL(); + error_message.urlLabel = err.getURLLabel(); protocol::ErrorResponseBody body; body.error = error_message; diff --git a/lldb/tools/lldb-dap/JSONUtils.cpp b/lldb/tools/lldb-dap/JSONUtils.cpp index 460d2a46049c6..5bcc2f9c71c2d 100644 --- a/lldb/tools/lldb-dap/JSONUtils.cpp +++ b/lldb/tools/lldb-dap/JSONUtils.cpp @@ -462,10 +462,10 @@ std::pair<int64_t, bool> UnpackLocation(int64_t location_id) { /// See /// https://microsoft.github.io/debug-adapter-protocol/specification#Reverse_Requests_RunInTerminal llvm::json::Object CreateRunInTerminalReverseRequest( - llvm::StringRef program, const std::vector<protocol::String> &args, - const llvm::StringMap<protocol::String> &env, llvm::StringRef cwd, + llvm::StringRef program, const std::vector<std::string> &args, + const llvm::StringMap<std::string> &env, llvm::StringRef cwd, llvm::StringRef comm_file, lldb::pid_t debugger_pid, - const std::vector<std::optional<protocol::String>> &stdio, bool external) { + const std::vector<std::optional<std::string>> &stdio, bool external) { llvm::json::Object run_in_terminal_args; if (external) { // This indicates the IDE to open an external terminal window. @@ -488,10 +488,10 @@ llvm::json::Object CreateRunInTerminalReverseRequest( std::stringstream ss; std::string_view delimiter; - for (const std::optional<protocol::String> &file : stdio) { + for (const std::optional<std::string> &file : stdio) { ss << std::exchange(delimiter, ":"); if (file) - ss << file->str(); + ss << *file; } req_args.push_back(ss.str()); } diff --git a/lldb/tools/lldb-dap/JSONUtils.h b/lldb/tools/lldb-dap/JSONUtils.h index e12fb5b937bac..232b1810a3cf4 100644 --- a/lldb/tools/lldb-dap/JSONUtils.h +++ b/lldb/tools/lldb-dap/JSONUtils.h @@ -322,10 +322,10 @@ std::pair<int64_t, bool> UnpackLocation(int64_t location_id); /// A "runInTerminal" JSON object that follows the specification outlined by /// Microsoft. llvm::json::Object CreateRunInTerminalReverseRequest( - llvm::StringRef program, const std::vector<protocol::String> &args, - const llvm::StringMap<protocol::String> &env, llvm::StringRef cwd, + llvm::StringRef program, const std::vector<std::string> &args, + const llvm::StringMap<std::string> &env, llvm::StringRef cwd, llvm::StringRef comm_file, lldb::pid_t debugger_pid, - const std::vector<std::optional<protocol::String>> &stdio, bool external); + const std::vector<std::optional<std::string>> &stdio, bool external); /// Create a "Terminated" JSON object that contains statistics /// diff --git a/lldb/tools/lldb-dap/LLDBUtils.cpp b/lldb/tools/lldb-dap/LLDBUtils.cpp index 7e69813477b29..e7407e9da9efb 100644 --- a/lldb/tools/lldb-dap/LLDBUtils.cpp +++ b/lldb/tools/lldb-dap/LLDBUtils.cpp @@ -32,7 +32,7 @@ namespace lldb_dap { bool RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix, - const llvm::ArrayRef<protocol::String> &commands, + const llvm::ArrayRef<std::string> &commands, llvm::raw_ostream &strm, bool parse_command_directives, bool echo_commands) { if (commands.empty()) @@ -115,7 +115,7 @@ bool RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix, } std::string RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix, - const llvm::ArrayRef<protocol::String> &commands, + const llvm::ArrayRef<std::string> &commands, bool &required_command_failed, bool parse_command_directives, bool echo_commands) { required_command_failed = false; diff --git a/lldb/tools/lldb-dap/LLDBUtils.h b/lldb/tools/lldb-dap/LLDBUtils.h index 37757ada7ab4d..19174ba59654d 100644 --- a/lldb/tools/lldb-dap/LLDBUtils.h +++ b/lldb/tools/lldb-dap/LLDBUtils.h @@ -10,7 +10,6 @@ #define LLDB_TOOLS_LLDB_DAP_LLDBUTILS_H #include "DAPForward.h" -#include "Protocol/ProtocolBase.h" #include "lldb/API/SBDebugger.h" #include "lldb/API/SBEnvironment.h" #include "lldb/API/SBError.h" @@ -64,7 +63,7 @@ namespace lldb_dap { /// \b true, unless a command prefixed with \b ! fails and parsing of /// command directives is enabled. bool RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix, - const llvm::ArrayRef<protocol::String> &commands, + const llvm::ArrayRef<std::string> &commands, llvm::raw_ostream &strm, bool parse_command_directives, bool echo_commands); @@ -98,7 +97,7 @@ bool RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix, /// A std::string that contains the prefix and all commands and /// command output. std::string RunLLDBCommands(lldb::SBDebugger &debugger, llvm::StringRef prefix, - const llvm::ArrayRef<protocol::String> &commands, + const llvm::ArrayRef<std::string> &commands, bool &required_command_failed, bool parse_command_directives = true, bool echo_commands = false); diff --git a/lldb/tools/lldb-dap/Protocol/DAPTypes.h b/lldb/tools/lldb-dap/Protocol/DAPTypes.h index 5c5d279656d83..4fc0c8db1acc8 100644 --- a/lldb/tools/lldb-dap/Protocol/DAPTypes.h +++ b/lldb/tools/lldb-dap/Protocol/DAPTypes.h @@ -16,12 +16,12 @@ #ifndef LLDB_TOOLS_LLDB_DAP_PROTOCOL_DAP_TYPES_H #define LLDB_TOOLS_LLDB_DAP_PROTOCOL_DAP_TYPES_H -#include "Protocol/ProtocolBase.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" #include "llvm/Support/JSON.h" #include <cstdint> #include <optional> +#include <string> namespace lldb_dap::protocol { @@ -99,10 +99,10 @@ inline llvm::json::Value toJSON(const var_ref_t &var_ref) { /// breakpoints the path and line are the same For each session. struct PersistenceData { /// The source module path. - String module_path; + std::string module_path; /// The symbol name of the Source. - String symbol_name; + std::string symbol_name; }; bool fromJSON(const llvm::json::Value &, PersistenceData &, llvm::json::Path); llvm::json::Value toJSON(const PersistenceData &); @@ -145,7 +145,7 @@ struct Symbol { lldb::addr_t size = 0; /// The symbol name. - String name; + std::string name; }; bool fromJSON(const llvm::json::Value &, Symbol &, llvm::json::Path); llvm::json::Value toJSON(const Symbol &); diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolBase.cpp b/lldb/tools/lldb-dap/Protocol/ProtocolBase.cpp index 9008719ba543d..72359214c8537 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolBase.cpp +++ b/lldb/tools/lldb-dap/Protocol/ProtocolBase.cpp @@ -57,22 +57,6 @@ bool fromJSON(const json::Value &Params, MessageType &M, json::Path P) { return true; } -json::Value toJSON(const String &S) { - if (LLVM_LIKELY(llvm::json::isUTF8(std::string(S)))) - return std::string(S); - return llvm::json::fixUTF8(std::string(S)); -} - -bool fromJSON(const llvm::json::Value &Param, String &Str, - llvm::json::Path Path) { - if (auto s = Param.getAsString()) { - Str = *std::move(s); - return true; - } - Path.report("expected string"); - return false; -} - json::Value toJSON(const Request &R) { assert(R.seq != kCalculateSeq && "invalid seq"); @@ -140,7 +124,8 @@ json::Value toJSON(const Response &R) { Result.insert({"message", "notStopped"}); break; } - } else if (const auto *messageString = std::get_if<String>(&*R.message)) { + } else if (const auto *messageString = + std::get_if<std::string>(&*R.message)) { Result.insert({"message", *messageString}); } } @@ -152,7 +137,8 @@ json::Value toJSON(const Response &R) { } static bool fromJSON(json::Value const &Params, - std::variant<ResponseMessage, String> &M, json::Path P) { + std::variant<ResponseMessage, std::string> &M, + json::Path P) { auto rawMessage = Params.getAsString(); if (!rawMessage) { P.report("expected a string"); @@ -202,46 +188,31 @@ bool operator==(const Response &a, const Response &b) { json::Value toJSON(const ErrorMessage &EM) { json::Object Result{{"id", EM.id}, {"format", EM.format}}; - if (!EM.variables.empty()) { + if (EM.variables) { json::Object variables; - for (auto &var : EM.variables) - variables[var.first.str()] = var.second; + for (auto &var : *EM.variables) + variables[var.first] = var.second; Result.insert({"variables", std::move(variables)}); } if (EM.sendTelemetry) Result.insert({"sendTelemetry", EM.sendTelemetry}); if (EM.showUser) Result.insert({"showUser", EM.showUser}); - if (!EM.url.empty()) + if (EM.url) Result.insert({"url", EM.url}); - if (!EM.urlLabel.empty()) + if (EM.urlLabel) Result.insert({"urlLabel", EM.urlLabel}); return std::move(Result); } -bool fromJSON(json::Value const &Params, std::map<String, String> &M, - json::Path P) { - const auto *const O = Params.getAsObject(); - if (!O) { - P.report("expected object"); - return false; - } - for (auto [k, v] : *O) { - auto str = v.getAsString(); - if (str) - M[k.str()] = *std::move(str); - } - return true; -} - bool fromJSON(json::Value const &Params, ErrorMessage &EM, json::Path P) { json::ObjectMapper O(Params, P); return O && O.map("id", EM.id) && O.map("format", EM.format) && - O.mapOptional("variables", EM.variables) && - O.mapOptional("sendTelemetry", EM.sendTelemetry) && - O.mapOptional("showUser", EM.showUser) && - O.mapOptional("url", EM.url) && O.mapOptional("urlLabel", EM.urlLabel); + O.map("variables", EM.variables) && + O.map("sendTelemetry", EM.sendTelemetry) && + O.map("showUser", EM.showUser) && O.map("url", EM.url) && + O.map("urlLabel", EM.urlLabel); } json::Value toJSON(const Event &E) { diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolBase.h b/lldb/tools/lldb-dap/Protocol/ProtocolBase.h index be4133a40c73d..09ce6802b17c0 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolBase.h +++ b/lldb/tools/lldb-dap/Protocol/ProtocolBase.h @@ -20,10 +20,7 @@ #ifndef LLDB_TOOLS_LLDB_DAP_PROTOCOL_PROTOCOL_BASE_H #define LLDB_TOOLS_LLDB_DAP_PROTOCOL_PROTOCOL_BASE_H -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/Error.h" #include "llvm/Support/JSON.h" -#include "llvm/Support/raw_ostream.h" #include <cstdint> #include <optional> #include <string> @@ -40,98 +37,10 @@ using Id = uint64_t; /// the current session. static constexpr Id kCalculateSeq = UINT64_MAX; -/// A wrapper around a 'std::string' to ensure the contents are valid utf8 -/// during serialization. -class String { -public: - String() = default; - String(const std::string &str) : m_str(str) {} - String(llvm::StringRef str) : m_str(str.str()) {} - String(const char *str) : m_str(str) {} - String(const llvm::formatv_object_base &payload) : m_str(payload.str()) {} - String(const String &) = default; - String(String &&str) : m_str(std::move(str.m_str)) {} - String(std::string &&str) : m_str(std::move(str)) {} - - ~String() = default; - - String &operator=(const String &) = default; - String &operator=(String &&Other) { - m_str = std::move(Other.m_str); - return *this; - } - - /// Conversion Operators - /// @{ - operator std::string &() { return m_str; } - operator llvm::Twine() const { return m_str; } - operator std::string() const { return m_str; } - operator llvm::StringRef() const { return {m_str}; } - /// @} - - void clear() { m_str.clear(); } - bool empty() const { return m_str.empty(); } - const char *c_str() const { return m_str.c_str(); } - const char *data() const { return m_str.data(); } - std::string str() const { return m_str; } - - inline String &operator+=(const String &RHS) { - m_str += RHS.m_str; - return *this; - } - -private: - std::string m_str; -}; -llvm::json::Value toJSON(const String &s); -bool fromJSON(const llvm::json::Value &, String &, llvm::json::Path); - -/// @name String Comparision Operators -/// @{ - -inline bool operator==(const String &LHS, const String &RHS) { - return llvm::StringRef(LHS) == llvm::StringRef(RHS); -} - -inline bool operator!=(const String &LHS, const String &RHS) { - return !(LHS == RHS); -} - -inline bool operator<(const String &LHS, const String &RHS) { - return llvm::StringRef(LHS) < llvm::StringRef(RHS); -} - -inline bool operator<=(const String &LHS, const String &RHS) { - return llvm::StringRef(LHS) <= llvm::StringRef(RHS); -} - -inline bool operator>(const String &LHS, const String &RHS) { - return llvm::StringRef(LHS) > llvm::StringRef(RHS); -} - -inline bool operator>=(const String &LHS, const String &RHS) { - return llvm::StringRef(LHS) >= llvm::StringRef(RHS); -} - -/// @} - -inline String operator+(const char *LHS, const String &RHS) { - return std::string(LHS).append(RHS.str().data(), RHS.str().size()); -} - -inline String operator+(const std::string &LHS, const String &RHS) { - return std::string(LHS).append(RHS.str().data(), RHS.str().size()); -} - -inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const String &S) { - OS << S.str(); - return OS; -} - /// A client or debug adapter initiated request. struct Request { /// The command to execute. - String command; + std::string command; /// Object containing arguments for the command. /// @@ -155,7 +64,7 @@ bool operator==(const Request &, const Request &); /// A debug adapter initiated event. struct Event { /// Type of event. - String event; + std::string event; /// Event-specific information. std::optional<llvm::json::Value> body = std::nullopt; @@ -186,7 +95,7 @@ struct Response { Id request_seq = 0; /// The command requested. - String command; + std::string command; /// Outcome of the request. If true, the request was successful and the `body` /// attribute may contain the result of the request. If the value is false, @@ -199,7 +108,8 @@ struct Response { /// Contains the raw error in short form if `success` is false. This raw error /// might be interpreted by the client and is not shown in the UI. Some /// predefined values exist. - std::optional<std::variant<ResponseMessage, String>> message = std::nullopt; + std::optional<std::variant<ResponseMessage, std::string>> message = + std::nullopt; /// Contains request result if success is true and error details if success is /// false. @@ -234,11 +144,11 @@ struct ErrorMessage { /// `{name}`. If variable name starts with an underscore character, the /// variable does not contain user data (PII) and can be safely used for /// telemetry purposes. - String format; + std::string format; /// An object used as a dictionary for looking up the variables in the format /// string. - std::map<String, String> variables; + std::optional<std::map<std::string, std::string>> variables; /// If true send to telemetry. bool sendTelemetry = false; @@ -247,10 +157,10 @@ struct ErrorMessage { bool showUser = false; /// A url where additional information about this message can be found. - String url; + std::optional<std::string> url; /// A label that is presented to the user as the UI for opening the url. - String urlLabel; + std::optional<std::string> urlLabel; }; bool fromJSON(const llvm::json::Value &, ErrorMessage &, llvm::json::Path); llvm::json::Value toJSON(const ErrorMessage &); diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp index f16d2ffcb7998..faed1f8c4d574 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp +++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.cpp @@ -8,7 +8,6 @@ #include "Protocol/ProtocolRequests.h" #include "JSONUtils.h" -#include "Protocol/ProtocolBase.h" #include "Protocol/ProtocolTypes.h" #include "lldb/lldb-defines.h" #include "llvm/ADT/DenseMap.h" @@ -22,8 +21,8 @@ using namespace llvm; // The 'env' field is either an object as a map of strings or as an array of // strings formatted like 'key=value'. -static bool parseEnv(const json::Value &Params, - StringMap<lldb_dap::protocol::String> &env, json::Path P) { +static bool parseEnv(const json::Value &Params, StringMap<std::string> &env, + json::Path P) { const json::Object *O = Params.getAsObject(); if (!O) { P.report("expected object"); @@ -88,8 +87,7 @@ static bool parseTimeout(const json::Value &Params, std::chrono::seconds &S, static bool parseSourceMap(const json::Value &Params, - std::vector<std::pair<lldb_dap::protocol::String, - lldb_dap::protocol::String>> &sourceMap, + std::vector<std::pair<std::string, std::string>> &sourceMap, json::Path P) { const json::Object *O = Params.getAsObject(); if (!O) { @@ -313,7 +311,7 @@ bool fromJSON(const json::Value &Params, LaunchRequestArguments &LRA, if (!success) return false; - for (std::optional<String> &io_path : LRA.stdio) { + for (std::optional<std::string> &io_path : LRA.stdio) { // set empty paths to null. if (io_path && llvm::StringRef(*io_path).trim().empty()) io_path.reset(); diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h index 83431d028b9fd..9bf04757294d6 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h +++ b/lldb/tools/lldb-dap/Protocol/ProtocolRequests.h @@ -106,16 +106,16 @@ enum PathFormat : unsigned { ePatFormatPath, ePathFormatURI }; /// Arguments for `initialize` request. struct InitializeRequestArguments { /// The ID of the debug adapter. - String adapterID; + std::string adapterID; /// The ID of the client using this adapter. - String clientID; + std::string clientID; /// The human-readable name of the client using this adapter. - String clientName; + std::string clientName; /// The ISO-639 locale of the client using this adapter, e.g. en-US or de-CH. - String locale; + std::string locale; /// Determines in what format paths are specified. The default is `path`, /// which is the native format. @@ -153,7 +153,7 @@ struct Configuration { /// information in your executable contains relative paths, this option can be /// used so that `lldb-dap` can find source files and object files that have /// relative paths. - String debuggerRoot; + std::string debuggerRoot; /// Enable auto generated summaries for variables when no summaries exist for /// a given type. This feature can cause performance delays in large projects @@ -180,7 +180,7 @@ struct Configuration { /// Console, instead of printing variables. Defaults to a backtick. If it's an /// empty string, then all expression in the Debug Console are treated as /// regular LLDB commands. - String commandEscapePrefix = "`"; + std::string commandEscapePrefix = "`"; /// If non-empty, stack frames will have descriptions generated based on the /// provided format. See https://lldb.llvm.org/use/formatting.html for an @@ -189,58 +189,58 @@ struct Configuration { /// default frame names will be used. This might come with a performance cost /// because debug information might need to be processed to generate the /// description. - std::optional<String> customFrameFormat; + std::optional<std::string> customFrameFormat; /// Same as `customFrameFormat`, but for threads instead of stack frames. - std::optional<String> customThreadFormat; + std::optional<std::string> customThreadFormat; /// Specify a source path to remap "./" to allow full paths to be used when /// setting breakpoints in binaries that have relative source paths. - String sourcePath; + std::string sourcePath; /// Specify an array of path re-mappings. Each element in the array must be a /// two element array containing a source and destination pathname. Overrides /// sourcePath. - std::vector<std::pair<String, String>> sourceMap; + std::vector<std::pair<std::string, std::string>> sourceMap; /// LLDB commands executed upon debugger startup prior to creating the LLDB /// target. - std::vector<String> preInitCommands; + std::vector<std::string> preInitCommands; /// LLDB commands executed upon debugger startup prior to creating the LLDB /// target. - std::vector<String> initCommands; + std::vector<std::string> initCommands; /// LLDB commands executed just before launching/attaching, after the LLDB /// target has been created. - std::vector<String> preRunCommands; + std::vector<std::string> preRunCommands; /// LLDB commands executed just after launching/attaching, after the LLDB /// target has been created. - std::vector<String> postRunCommands; + std::vector<std::string> postRunCommands; /// LLDB commands executed just after each stop. - std::vector<String> stopCommands; + std::vector<std::string> stopCommands; /// LLDB commands executed when the program exits. - std::vector<String> exitCommands; + std::vector<std::string> exitCommands; /// LLDB commands executed when the debugging session ends. - std::vector<String> terminateCommands; + std::vector<std::string> terminateCommands; /// Path to the executable. /// /// *NOTE:* When launching, either `launchCommands` or `program` must be /// configured. If both are configured then `launchCommands` takes priority. - String program; + std::string program; /// Target triple for the program (arch-vendor-os). If not set, inferred from /// the binary. - String targetTriple; + std::string targetTriple; /// Specify name of the platform to use for this target, creating the platform /// if necessary. - String platformName; + std::string platformName; }; enum Console : unsigned { @@ -269,19 +269,19 @@ struct LaunchRequestArguments { /// *NOTE:* Either launchCommands or program must be configured. /// /// If set, takes priority over the 'program' when launching the target. - std::vector<String> launchCommands; + std::vector<std::string> launchCommands; /// The program working directory. - String cwd; + std::string cwd; /// An array of command line argument strings to be passed to the program /// being launched. - std::vector<String> args; + std::vector<std::string> args; /// Environment variables to set when launching the program. The format of /// each environment variable string is "VAR=VALUE" for environment variables /// with values or just "VAR" for environment variables with no values. - llvm::StringMap<String> env; + llvm::StringMap<std::string> env; /// If set, then the client stub should detach rather than killing the /// debuggee if it loses connection with lldb. @@ -302,7 +302,7 @@ struct LaunchRequestArguments { Console console = eConsoleInternal; /// An array of file paths for redirecting the program's standard IO streams. - std::vector<std::optional<String>> stdio; + std::vector<std::optional<std::string>> stdio; /// @} }; @@ -341,7 +341,7 @@ struct AttachRequestArguments { /// to a process by name. These commands may optionally create a new target /// and must perform an attach. A valid process must exist after these /// commands complete or the `"attach"` will fail. - std::vector<String> attachCommands; + std::vector<std::string> attachCommands; /// System process ID to attach to. lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; @@ -355,10 +355,10 @@ struct AttachRequestArguments { /// The hostname to connect to a remote system. The default hostname being /// used `localhost`. - String gdbRemoteHostname = "localhost"; + std::string gdbRemoteHostname = "localhost"; /// Path to the core file to debug. - String coreFile; + std::string coreFile; /// An existing session that consist of a target and debugger. std::optional<DAPSession> session; @@ -402,7 +402,7 @@ struct CompletionsArguments { /// One or more source lines. Typically this is the text users have typed into /// the debug console before they asked for completion. - String text; + std::string text; /// The position within `text` for which to determine the completion /// proposals. It is measured in UTF-16 code units and the client capability @@ -438,10 +438,10 @@ struct SetVariableArguments { var_ref_t variablesReference{var_ref_t::k_invalid_var_ref}; /// The name of the variable in the container. - String name; + std::string name; /// The value of the variable. - String value; + std::string value; /// Specifies details on how to format the response value. ValueFormat format; @@ -452,11 +452,11 @@ bool fromJSON(const llvm::json::Value &, SetVariableArguments &, /// Response to `setVariable` request. struct SetVariableResponseBody { /// The new value of the variable. - String value; + std::string value; /// The type of the new value. Typically shown in the UI when hovering over /// the value. - String type; + std::string type; /// If `variablesReference` is > 0, the new value is structured and its /// children can be retrieved by passing `variablesReference` to the @@ -527,10 +527,10 @@ bool fromJSON(const llvm::json::Value &, SourceArguments &, llvm::json::Path); /// Response to `source` request. struct SourceResponseBody { /// Content of the source reference. - String content; + std::string content; /// Content type (MIME type) of the source. - std::optional<String> mimeType; + std::optional<std::string> mimeType; }; llvm::json::Value toJSON(const SourceResponseBody &); @@ -732,7 +732,7 @@ struct DataBreakpointInfoArguments { /// The name of the variable's child to obtain data breakpoint information /// for. If `variablesReference` isn't specified, this can be an expression, /// or an address if `asAddress` is also true. - String name; + std::string name; /// When `name` is an expression, evaluate it in the scope of this stack /// frame. If not specified, the expression is evaluated in the global scope. @@ -755,7 +755,7 @@ struct DataBreakpointInfoArguments { /// The mode of the desired breakpoint. If defined, this must be one of the /// `breakpointModes` the debug adapter advertised in its `Capabilities`. - std::optional<String> mode; + std::optional<std::string> mode; }; bool fromJSON(const llvm::json::Value &, DataBreakpointInfoArguments &, llvm::json::Path); @@ -770,11 +770,11 @@ struct DataBreakpointInfoResponseBody { /// for details. Breakpoints set using the `dataId` in the /// `setDataBreakpoints` request may outlive the lifetime of the associated /// `dataId`. - std::optional<String> dataId; + std::optional<std::string> dataId; /// UI string that describes on what data the breakpoint is set on or why a /// data breakpoint is not available. - String description; + std::string description; /// Attribute lists the available access types for a potential data /// breakpoint. A UI client could surface this information. @@ -808,7 +808,7 @@ struct SetExceptionBreakpointsArguments { /// Set of exception filters specified by their ID. The set of all possible /// exception filters is defined by the `exceptionBreakpointFilters` /// capability. The `filter` and `filterOptions` sets are additive. - std::vector<String> filters; + std::vector<std::string> filters; /// Set of exception filters and their options. The set of all possible /// exception filters is defined by the `exceptionBreakpointFilters` @@ -1015,7 +1015,7 @@ struct WriteMemoryArguments { bool allowPartial = false; /// Bytes to write, encoded using base64. - String data; + std::string data; }; bool fromJSON(const llvm::json::Value &, WriteMemoryArguments &, llvm::json::Path); @@ -1030,10 +1030,10 @@ llvm::json::Value toJSON(const WriteMemoryResponseBody &); struct ModuleSymbolsArguments { /// The module UUID for which to retrieve symbols. - String moduleId; + std::string moduleId; /// The module path. - String moduleName; + std::string moduleName; /// The index of the first symbol to return; if omitted, start at the /// beginning. @@ -1061,10 +1061,10 @@ bool fromJSON(const llvm::json::Value &, ExceptionInfoArguments &, struct ExceptionInfoResponseBody { /// ID of the exception that was thrown. - String exceptionId; + std::string exceptionId; /// Descriptive text for the exception. - String description; + std::string description; /// Mode that caused the exception notification to be raised. ExceptionBreakMode breakMode = eExceptionBreakModeNever; @@ -1097,7 +1097,7 @@ enum EvaluateContext : unsigned { /// Arguments for `evaluate` request. struct EvaluateArguments { /// The expression to evaluate. - String expression; + std::string expression; /// Evaluate the expression in the scope of this stack frame. If not /// specified, the expression is evaluated in the global scope. @@ -1143,12 +1143,12 @@ bool fromJSON(const llvm::json::Value &, EvaluateArguments &, llvm::json::Path); /// Response to 'evaluate' request. struct EvaluateResponseBody { /// The result of the evaluate request. - String result; + std::string result; /// The type of the evaluate result. /// This attribute should only be returned by a debug adapter if the /// corresponding capability `supportsVariableType` is true. - String type; + std::string type; /// Properties of an evaluate result that can be used to determine how to /// render the result in the UI. @@ -1177,7 +1177,7 @@ struct EvaluateResponseBody { /// memory address contained in the pointer. /// This attribute may be returned by a debug adapter if corresponding /// capability `supportsMemoryReferences` is true. - String memoryReference; + std::string memoryReference; /// A reference that allows the client to request the location where the /// returned value is declared. For example, if a function pointer is @@ -1240,7 +1240,7 @@ llvm::json::Value toJSON(const LocationsResponseBody &); /// Arguments for `compileUnits` request. struct CompileUnitsArguments { /// The ID of the module. - String moduleId; + std::string moduleId; }; bool fromJSON(const llvm::json::Value &, CompileUnitsArguments &, llvm::json::Path); diff --git a/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h b/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h index a50f4c85d4fff..2a23871621cca 100644 --- a/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h +++ b/lldb/tools/lldb-dap/Protocol/ProtocolTypes.h @@ -21,13 +21,13 @@ #define LLDB_TOOLS_LLDB_DAP_PROTOCOL_PROTOCOL_TYPES_H #include "Protocol/DAPTypes.h" -#include "Protocol/ProtocolBase.h" #include "lldb/lldb-defines.h" #include "lldb/lldb-types.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/JSON.h" #include <cstdint> #include <optional> +#include <string> #define LLDB_DAP_INVALID_SRC_REF 0 #define LLDB_DAP_INVALID_VALUE_LOC 0 @@ -40,14 +40,14 @@ namespace lldb_dap::protocol { struct ExceptionBreakpointsFilter { /// The internal ID of the filter option. This value is passed to the /// `setExceptionBreakpoints` request. - String filter; + std::string filter; /// The name of the filter option. This is shown in the UI. - String label; + std::string label; /// A help text providing additional information about the exception filter. /// This string is typically shown as a hover and can be translated. - String description; + std::string description; /// Initial value of the filter option. If not specified a value false is /// assumed. @@ -59,7 +59,7 @@ struct ExceptionBreakpointsFilter { /// A help text providing information about the condition. This string is /// shown as the placeholder text for a text box and can be translated. - String conditionDescription; + std::string conditionDescription; }; bool fromJSON(const llvm::json::Value &, ExceptionBreakpointsFilter &, llvm::json::Path); @@ -81,14 +81,14 @@ llvm::json::Value toJSON(const ColumnType &); /// customization. struct ColumnDescriptor { /// Name of the attribute rendered in this column. - String attributeName; + std::string attributeName; /// Header UI label of column. - String label; + std::string label; /// Format to use for the rendered values in this column. TBD how the format /// strings looks like. - std::optional<String> format; + std::optional<std::string> format; /// Datatype of values in this column. Defaults to `string` if not specified. /// Values: 'string', 'number', 'boolean', 'unixTimestampUTC'. @@ -143,19 +143,19 @@ llvm::json::Value toJSON(const CompletionItemType &); struct CompletionItem { /// The label of this completion item. By default this is also the text that /// is inserted when selecting this completion. - String label; + std::string label; /// If text is returned and not an empty string, then it is inserted instead /// of the label. - String text; + std::string text; /// A string that should be used when comparing this item with other items. If /// not returned or an empty string, the `label` is used instead. - String sortText; + std::string sortText; /// A human-readable string with additional information about this item, like /// type or symbol information. - String detail; + std::string detail; /// The item's type. Typically the client uses this information to render the /// item in the UI with an icon. @@ -211,14 +211,14 @@ llvm::json::Value toJSON(const BreakpointModeApplicability &); struct BreakpointMode { /// The internal ID of the mode. This value is passed to the `setBreakpoints` /// request. - String mode; + std::string mode; /// The name of the breakpoint mode. This is shown in the UI. - String label; + std::string label; /// A help text providing additional information about the breakpoint mode. /// This string is typically shown as a hover and can be translated. - std::optional<String> description; + std::optional<std::string> description; /// Describes one or more type of breakpoint this mode applies to. std::vector<BreakpointModeApplicability> appliesTo; @@ -342,7 +342,7 @@ struct Capabilities { /// The set of characters that should trigger completion in a REPL. If not /// specified, the UI should assume the `.` character. - std::vector<String> completionTriggerCharacters; + std::vector<std::string> completionTriggerCharacters; /// The set of additional module information exposed by the debug adapter. std::vector<ColumnDescriptor> additionalModuleColumns; @@ -362,7 +362,7 @@ struct Capabilities { /// @{ /// The version of the adapter. - String lldbExtVersion; + std::string lldbExtVersion; /// @} }; @@ -374,16 +374,16 @@ llvm::json::Value toJSON(const Capabilities &); struct ExceptionFilterOptions { /// ID of an exception filter returned by the `exceptionBreakpointFilters` /// capability. - String filterId; + std::string filterId; /// An expression for conditional exceptions. /// The exception breaks into the debugger if the result of the condition is /// true. - String condition; + std::string condition; /// The mode of this exception breakpoint. If defined, this must be one of the /// `breakpointModes` the debug adapter advertised in its `Capabilities`. - String mode; + std::string mode; }; bool fromJSON(const llvm::json::Value &, ExceptionFilterOptions &, llvm::json::Path); @@ -402,12 +402,12 @@ struct Source { /// The short name of the source. Every source returned from the debug adapter /// has a name. When sending a source to the debug adapter this name is /// optional. - std::optional<String> name; + std::optional<std::string> name; /// The path of the source to be shown in the UI. It is only used to locate /// and load the content of the source if no `sourceReference` is specified /// (or its value is 0). - std::optional<String> path; + std::optional<std::string> path; /// If the value > 0 the contents of the source must be retrieved through the /// `source` request (even if a path is specified). Since a `sourceReference` @@ -445,7 +445,7 @@ struct Scope { /// Name of the scope such as 'Arguments', 'Locals', or 'Registers'. This /// string is shown in the UI as is and can be translated. //// - String name; + std::string name; /// A hint for how to present this scope in the UI. If this attribute is /// missing, the scope is shown with a generic UI. @@ -530,7 +530,7 @@ struct StepInTarget { lldb::addr_t id = LLDB_INVALID_ADDRESS; /// The name of the step-in target (shown in the UI). - String label; + std::string label; /// The line of the step-in target. uint32_t line = LLDB_INVALID_LINE_NUMBER; @@ -556,7 +556,7 @@ struct Thread { /// Unique identifier for the thread. lldb::tid_t id = LLDB_INVALID_THREAD_ID; /// The name of the thread. - String name; + std::string name; }; bool fromJSON(const llvm::json::Value &, Thread &, llvm::json::Path); llvm::json::Value toJSON(const Thread &); @@ -616,7 +616,7 @@ struct Breakpoint { /// A message about the state of the breakpoint. /// This is shown to the user and can be used to explain why a breakpoint /// could not be verified. - std::optional<String> message; + std::optional<std::string> message; /// The source where the breakpoint is located. std::optional<Source> source; @@ -639,7 +639,7 @@ struct Breakpoint { std::optional<uint32_t> endColumn; /// A memory reference to where the breakpoint is set. - std::optional<String> instructionReference; + std::optional<std::string> instructionReference; /// The offset from the instruction reference. /// This can be negative. @@ -667,7 +667,7 @@ struct SourceBreakpoint { /// The expression for conditional breakpoints. /// It is only honored by a debug adapter if the corresponding capability /// `supportsConditionalBreakpoints` is true. - std::optional<String> condition; + std::optional<std::string> condition; /// The expression that controls how many hits of the breakpoint are ignored. /// The debug adapter is expected to interpret the expression as needed. @@ -676,7 +676,7 @@ struct SourceBreakpoint { /// If both this property and `condition` are specified, `hitCondition` should /// be evaluated only if the `condition` is met, and the debug adapter should /// stop only if both conditions are met. - std::optional<String> hitCondition; + std::optional<std::string> hitCondition; /// If this attribute exists and is non-empty, the debug adapter must not /// 'break' (stop) @@ -685,11 +685,11 @@ struct SourceBreakpoint { /// capability `supportsLogPoints` is true. /// If either `hitCondition` or `condition` is specified, then the message /// should only be logged if those conditions are met. - std::optional<String> logMessage; + std::optional<std::string> logMessage; /// The mode of this breakpoint. If defined, this must be one of the /// `breakpointModes` the debug adapter advertised in its `Capabilities`. - std::optional<String> mode; + std::optional<std::string> mode; }; bool fromJSON(const llvm::json::Value &, SourceBreakpoint &, llvm::json::Path); llvm::json::Value toJSON(const SourceBreakpoint &); @@ -697,18 +697,18 @@ llvm::json::Value toJSON(const SourceBreakpoint &); /// Properties of a breakpoint passed to the `setFunctionBreakpoints` request. struct FunctionBreakpoint { /// The name of the function. - String name; + std::string name; /// An expression for conditional breakpoints. /// It is only honored by a debug adapter if the corresponding capability /// `supportsConditionalBreakpoints` is true. - std::optional<String> condition; + std::optional<std::string> condition; /// An expression that controls how many hits of the breakpoint are ignored. /// The debug adapter is expected to interpret the expression as needed. /// The attribute is only honored by a debug adapter if the corresponding /// capability `supportsHitConditionalBreakpoints` is true. - std::optional<String> hitCondition; + std::optional<std::string> hitCondition; }; bool fromJSON(const llvm::json::Value &, FunctionBreakpoint &, llvm::json::Path); @@ -729,17 +729,17 @@ llvm::json::Value toJSON(const DataBreakpointAccessType &); struct DataBreakpoint { /// An id representing the data. This id is returned from the /// `dataBreakpointInfo` request. - String dataId; + std::string dataId; /// The access type of the data. std::optional<DataBreakpointAccessType> accessType; /// An expression for conditional breakpoints. - std::optional<String> condition; + std::optional<std::string> condition; /// An expression that controls how many hits of the breakpoint are ignored. /// The debug adapter is expected to interpret the expression as needed. - std::optional<String> hitCondition; + std::optional<std::string> hitCondition; }; bool fromJSON(const llvm::json::Value &, DataBreakpoint &, llvm::json::Path); llvm::json::Value toJSON(const DataBreakpoint &); @@ -750,7 +750,7 @@ struct InstructionBreakpoint { /// This should be a memory or instruction pointer reference from an /// `EvaluateResponse`, `Variable`, `StackFrame`, `GotoTarget`, or /// `Breakpoint`. - String instructionReference; + std::string instructionReference; /// The offset from the instruction reference in bytes. /// This can be negative. @@ -759,17 +759,17 @@ struct InstructionBreakpoint { /// An expression for conditional breakpoints. /// It is only honored by a debug adapter if the corresponding capability /// `supportsConditionalBreakpoints` is true. - std::optional<String> condition; + std::optional<std::string> condition; /// An expression that controls how many hits of the breakpoint are ignored. /// The debug adapter is expected to interpret the expression as needed. /// The attribute is only honored by a debug adapter if the corresponding /// capability `supportsHitConditionalBreakpoints` is true. - std::optional<String> hitCondition; + std::optional<std::string> hitCondition; /// The mode of this breakpoint. If defined, this must be one of the /// `breakpointModes` the debug adapter advertised in its `Capabilities`. - std::optional<String> mode; + std::optional<std::string> mode; }; bool fromJSON(const llvm::json::Value &, InstructionBreakpoint &, llvm::json::Path); @@ -788,15 +788,15 @@ struct DisassembledInstruction { /// Raw bytes representing the instruction and its operands, in an /// implementation-defined format. - std::optional<String> instructionBytes; + std::optional<std::string> instructionBytes; /// Text representing the instruction and its operands, in an /// implementation-defined format. - String instruction; + std::string instruction; /// Name of the symbol that corresponds with the location of this instruction, /// if any. - std::optional<String> symbol; + std::optional<std::string> symbol; /// Source location that corresponds to this instruction, if any. /// Should always be set (if available) on the first instruction returned, @@ -834,15 +834,15 @@ llvm::json::Value toJSON(const DisassembledInstruction &); struct Module { /// Unique identifier for the module. - String id; + std::string id; /// A name of the module. - String name; + std::string name; /// Logical full path to the module. The exact definition is implementation /// defined, but usually this would be a full path to the on-disk file for the /// module. - String path; + std::string path; /// True if the module is optimized. bool isOptimized = false; @@ -852,21 +852,21 @@ struct Module { bool isUserCode = false; /// Version of Module. - String version; + std::string version; /// User-understandable description of if symbols were found for the module /// (ex: 'Symbols Loaded', 'Symbols not found', etc.) - String symbolStatus; + std::string symbolStatus; /// Logical full path to the symbol file. The exact definition is /// implementation defined. - String symbolFilePath; + std::string symbolFilePath; /// Module created or modified, encoded as an RFC 3339 timestamp. - String dateTimeStamp; + std::string dateTimeStamp; /// Address range covered by this module. - String addressRange; + std::string addressRange; /// Custom fields /// @{ @@ -883,15 +883,15 @@ llvm::json::Value toJSON(const Module &); struct VariablePresentationHint { /// The kind of variable. Before introducing additional values, try to use the /// listed values. - String kind; + std::string kind; /// Set of attributes represented as an array of strings. Before introducing /// additional values, try to use the listed values. - std::vector<String> attributes; + std::vector<std::string> attributes; /// Visibility of variable. Before introducing additional values, try to use /// the listed values. - String visibility; + std::string visibility; /// If true, clients can present the variable with a UI that supports a /// specific gesture to trigger its evaluation. @@ -929,7 +929,7 @@ bool fromJSON(const llvm::json::Value &, VariablePresentationHint &, /// and fetch them in chunks. struct Variable { /// The variable's name. - String name; + std::string name; /// The variable's value. /// @@ -941,14 +941,14 @@ struct Variable { /// its children are not yet visible. /// /// An empty string can be used if no value should be shown in the UI. - String value; + std::string value; /// The type of the variable's value. Typically shown in the UI when hovering /// over the value. /// /// This attribute should only be returned by a debug adapter if the /// corresponding capability `supportsVariableType` is true. - String type; + std::string type; /// Properties of a variable that can be used to determine how to render the /// variable in the UI. @@ -956,7 +956,7 @@ struct Variable { /// The evaluatable name of this variable which can be passed to the /// `evaluate` request to fetch the variable's value. - String evaluateName; + std::string evaluateName; /// If `variablesReference` is > 0, the variable is structured and its /// children can be retrieved by passing `variablesReference` to the @@ -1019,20 +1019,20 @@ llvm::json::Value toJSON(ExceptionBreakMode); struct ExceptionDetails { /// Message contained in the exception. - String message; + std::string message; /// Short type name of the exception object. - String typeName; + std::string typeName; /// Fully-qualified type name of the exception object. - String fullTypeName; + std::string fullTypeName; /// An expression that can be evaluated in the current scope to obtain the /// exception object. - String evaluateName; + std::string evaluateName; /// Stack trace at the time the exception was thrown. - String stackTrace; + std::string stackTrace; /// Details of the exception contained by this exception, if any. std::vector<ExceptionDetails> innerException; @@ -1041,7 +1041,7 @@ llvm::json::Value toJSON(const ExceptionDetails &); struct CompileUnit { /// Path of compile unit. - String compileUnitPath; + std::string compileUnitPath; }; llvm::json::Value toJSON(const CompileUnit &); @@ -1086,7 +1086,7 @@ struct StackFrame { lldb::tid_t id = LLDB_DAP_INVALID_STACK_FRAME_ID; /// The name of the stack frame, typically a method name. - String name; + std::string name; /// The source of the frame. std::optional<Source> source; @@ -1120,7 +1120,7 @@ struct StackFrame { lldb::addr_t instructionPointerReference = LLDB_INVALID_ADDRESS; /// The module associated with this frame, if any. - std::optional<String> moduleId; + std::optional<std::string> moduleId; /// A hint for how to present this frame in the UI. A value of `label` can be /// used to indicate that the frame is an artificial frame that is used as a diff --git a/lldb/tools/lldb-dap/ProtocolUtils.cpp b/lldb/tools/lldb-dap/ProtocolUtils.cpp index 99bd5abf0b756..d18c040b119da 100644 --- a/lldb/tools/lldb-dap/ProtocolUtils.cpp +++ b/lldb/tools/lldb-dap/ProtocolUtils.cpp @@ -203,9 +203,10 @@ protocol::Thread CreateThread(lldb::SBThread &thread, lldb::SBFormat &format) { queue_kind_label = " (concurrent)"; name = llvm::formatv("Thread {0} Queue: {1}{2}", thread.GetIndexID(), - queue_name, queue_kind_label); + queue_name, queue_kind_label) + .str(); } else { - name = llvm::formatv("Thread {0}", thread.GetIndexID()); + name = llvm::formatv("Thread {0}", thread.GetIndexID()).str(); } } return protocol::Thread{thread.GetThreadID(), name}; diff --git a/lldb/tools/lldb-dap/tool/lldb-dap.cpp b/lldb/tools/lldb-dap/tool/lldb-dap.cpp index afbc2c7f4c28c..af5c743a5edf1 100644 --- a/lldb/tools/lldb-dap/tool/lldb-dap.cpp +++ b/lldb/tools/lldb-dap/tool/lldb-dap.cpp @@ -411,7 +411,7 @@ validateConnection(llvm::StringRef conn) { static llvm::Error serveConnection( const Socket::SocketProtocol &protocol, llvm::StringRef name, Log &log, const ReplMode default_repl_mode, - const std::vector<protocol::String> &pre_init_commands, bool no_lldbinit, + const std::vector<std::string> &pre_init_commands, bool no_lldbinit, std::optional<std::chrono::seconds> connection_timeout_seconds) { Status status; static std::unique_ptr<Socket> listener = Socket::Create(protocol, status); @@ -705,7 +705,7 @@ int main(int argc, char *argv[]) { lldb::SBDebugger::Terminate(); }); - std::vector<protocol::String> pre_init_commands; + std::vector<std::string> pre_init_commands; for (const std::string &arg : input_args.getAllArgValues(OPT_pre_init_command)) { pre_init_commands.push_back(arg); diff --git a/lldb/unittests/DAP/CMakeLists.txt b/lldb/unittests/DAP/CMakeLists.txt index 53e0fde5687ec..97f9cad7477ed 100644 --- a/lldb/unittests/DAP/CMakeLists.txt +++ b/lldb/unittests/DAP/CMakeLists.txt @@ -10,7 +10,6 @@ add_lldb_unittest(DAPTests Handler/ContinueTest.cpp JSONUtilsTest.cpp LLDBUtilsTest.cpp - ProtocolBaseTest.cpp ProtocolEventsTest.cpp ProtocolRequestsTest.cpp ProtocolTypesTest.cpp diff --git a/lldb/unittests/DAP/ProtocolBaseTest.cpp b/lldb/unittests/DAP/ProtocolBaseTest.cpp deleted file mode 100644 index b22ef916bc00a..0000000000000 --- a/lldb/unittests/DAP/ProtocolBaseTest.cpp +++ /dev/null @@ -1,29 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#include "Protocol/ProtocolBase.h" -#include "TestingSupport/TestUtilities.h" -#include "llvm/Testing/Support/Error.h" -#include <gtest/gtest.h> - -using namespace llvm; -using namespace lldb_dap::protocol; -using lldb_private::PrettyPrint; -using llvm::json::parse; -using llvm::json::Value; - -TEST(ProtocolBaseTest, SanitizedString) { - for (auto [input, json] : std::vector<std::pair<const char *, const char *>>{ - {"valid str", R"("valid str")"}, - {"lone trailing \x81\x82 bytes", R"("lone trailing οΏ½οΏ½ bytes")"}}) { - String str = input; - Expected<Value> expected_str = parse(json); - ASSERT_THAT_EXPECTED(expected_str, llvm::Succeeded()); - EXPECT_EQ(PrettyPrint(*expected_str), PrettyPrint(str)); - } -} diff --git a/lldb/unittests/DAP/ProtocolTypesTest.cpp b/lldb/unittests/DAP/ProtocolTypesTest.cpp index 56ef6cdbb813f..863fd3c4fe3a3 100644 --- a/lldb/unittests/DAP/ProtocolTypesTest.cpp +++ b/lldb/unittests/DAP/ProtocolTypesTest.cpp @@ -707,7 +707,7 @@ TEST(ProtocolTypesTest, SetExceptionBreakpointsArguments) { /*filterOptions=*/testing::IsEmpty()))); EXPECT_THAT_EXPECTED( parse<SetExceptionBreakpointsArguments>(R"({"filters":["abc"]})"), - HasValue(testing::FieldsAre(/*filters=*/std::vector<String>{"abc"}, + HasValue(testing::FieldsAre(/*filters=*/std::vector<std::string>{"abc"}, /*filterOptions=*/testing::IsEmpty()))); EXPECT_THAT_EXPECTED( parse<SetExceptionBreakpointsArguments>( diff --git a/lldb/unittests/DAP/TestBase.cpp b/lldb/unittests/DAP/TestBase.cpp index 39634593779ad..1afac18833a03 100644 --- a/lldb/unittests/DAP/TestBase.cpp +++ b/lldb/unittests/DAP/TestBase.cpp @@ -41,7 +41,7 @@ void TransportBase::SetUp() { dap = std::make_unique<DAP>( /*log=*/*log, /*default_repl_mode=*/ReplMode::Auto, - /*pre_init_commands=*/std::vector<String>(), + /*pre_init_commands=*/std::vector<std::string>(), /*no_lldbinit=*/false, /*client_name=*/"test_client", /*transport=*/*to_client, /*loop=*/loop); diff --git a/lldb/unittests/DAP/VariablesTest.cpp b/lldb/unittests/DAP/VariablesTest.cpp index 8a1c9ce2c502f..10dd567a4ecca 100644 --- a/lldb/unittests/DAP/VariablesTest.cpp +++ b/lldb/unittests/DAP/VariablesTest.cpp @@ -29,8 +29,7 @@ class VariablesTest : public ::testing::Test { VariableReferenceStorage vars; static const protocol::Scope * - FindScope(const std::vector<protocol::Scope> &scopes, - const protocol::String &name) { + FindScope(const std::vector<protocol::Scope> &scopes, llvm::StringRef name) { for (const auto &scope : scopes) { if (scope.name == name) return &scope; _______________________________________________ lldb-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/lldb-commits
