1 //===-- CommandObject.h -----------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLDB_INTERPRETER_COMMANDOBJECT_H 10 #define LLDB_INTERPRETER_COMMANDOBJECT_H 11 12 #include <map> 13 #include <memory> 14 #include <optional> 15 #include <string> 16 #include <vector> 17 18 #include "lldb/Utility/Flags.h" 19 20 #include "lldb/Interpreter/CommandCompletions.h" 21 #include "lldb/Interpreter/Options.h" 22 #include "lldb/Target/ExecutionContext.h" 23 #include "lldb/Utility/Args.h" 24 #include "lldb/Utility/CompletionRequest.h" 25 #include "lldb/Utility/StringList.h" 26 #include "lldb/lldb-private.h" 27 28 namespace lldb_private { 29 30 // This function really deals with CommandObjectLists, but we didn't make a 31 // CommandObjectList class, so I'm sticking it here. But we really should have 32 // such a class. Anyway, it looks up the commands in the map that match the 33 // partial string cmd_str, inserts the matches into matches, and returns the 34 // number added. 35 36 template <typename ValueType> 37 int AddNamesMatchingPartialString( 38 const std::map<std::string, ValueType, std::less<>> &in_map, 39 llvm::StringRef cmd_str, StringList &matches, 40 StringList *descriptions = nullptr) { 41 int number_added = 0; 42 43 const bool add_all = cmd_str.empty(); 44 45 for (auto iter = in_map.begin(), end = in_map.end(); iter != end; iter++) { 46 if (add_all || (iter->first.find(std::string(cmd_str), 0) == 0)) { 47 ++number_added; 48 matches.AppendString(iter->first.c_str()); 49 if (descriptions) 50 descriptions->AppendString(iter->second->GetHelp()); 51 } 52 } 53 54 return number_added; 55 } 56 57 template <typename ValueType> 58 size_t 59 FindLongestCommandWord(std::map<std::string, ValueType, std::less<>> &dict) { 60 auto end = dict.end(); 61 size_t max_len = 0; 62 63 for (auto pos = dict.begin(); pos != end; ++pos) { 64 size_t len = pos->first.size(); 65 if (max_len < len) 66 max_len = len; 67 } 68 return max_len; 69 } 70 71 class CommandObject : public std::enable_shared_from_this<CommandObject> { 72 public: 73 typedef llvm::StringRef(ArgumentHelpCallbackFunction)(); 74 75 struct ArgumentHelpCallback { 76 ArgumentHelpCallbackFunction *help_callback; 77 bool self_formatting; 78 79 llvm::StringRef operator()() const { return (*help_callback)(); } 80 81 explicit operator bool() const { return (help_callback != nullptr); } 82 }; 83 84 /// Entries in the main argument information table. 85 struct ArgumentTableEntry { 86 lldb::CommandArgumentType arg_type; 87 const char *arg_name; 88 lldb::CompletionType completion_type; 89 OptionEnumValues enum_values; 90 ArgumentHelpCallback help_function; 91 const char *help_text; 92 }; 93 94 /// Used to build individual command argument lists. 95 struct CommandArgumentData { 96 lldb::CommandArgumentType arg_type; 97 ArgumentRepetitionType arg_repetition; 98 /// This arg might be associated only with some particular option set(s). By 99 /// default the arg associates to all option sets. 100 uint32_t arg_opt_set_association; 101 102 CommandArgumentData(lldb::CommandArgumentType type = lldb::eArgTypeNone, 103 ArgumentRepetitionType repetition = eArgRepeatPlain, 104 uint32_t opt_set = LLDB_OPT_SET_ALL) 105 : arg_type(type), arg_repetition(repetition), 106 arg_opt_set_association(opt_set) {} 107 }; 108 109 typedef std::vector<CommandArgumentData> 110 CommandArgumentEntry; // Used to build individual command argument lists 111 112 typedef std::map<std::string, lldb::CommandObjectSP, std::less<>> CommandMap; 113 114 CommandObject(CommandInterpreter &interpreter, llvm::StringRef name, 115 llvm::StringRef help = "", llvm::StringRef syntax = "", 116 uint32_t flags = 0); 117 118 virtual ~CommandObject() = default; 119 120 static const char * 121 GetArgumentTypeAsCString(const lldb::CommandArgumentType arg_type); 122 123 static const char * 124 GetArgumentDescriptionAsCString(const lldb::CommandArgumentType arg_type); 125 126 CommandInterpreter &GetCommandInterpreter() { return m_interpreter; } 127 Debugger &GetDebugger(); 128 129 virtual llvm::StringRef GetHelp(); 130 131 virtual llvm::StringRef GetHelpLong(); 132 133 virtual llvm::StringRef GetSyntax(); 134 135 llvm::StringRef GetCommandName() const; 136 137 virtual void SetHelp(llvm::StringRef str); 138 139 virtual void SetHelpLong(llvm::StringRef str); 140 141 void SetSyntax(llvm::StringRef str); 142 143 // override this to return true if you want to enable the user to delete the 144 // Command object from the Command dictionary (aliases have their own 145 // deletion scheme, so they do not need to care about this) 146 virtual bool IsRemovable() const { return false; } 147 148 virtual bool IsMultiwordObject() { return false; } 149 150 bool IsUserCommand() { return m_is_user_command; } 151 152 void SetIsUserCommand(bool is_user) { m_is_user_command = is_user; } 153 154 virtual CommandObjectMultiword *GetAsMultiwordCommand() { return nullptr; } 155 156 virtual bool IsAlias() { return false; } 157 158 // override this to return true if your command is somehow a "dash-dash" form 159 // of some other command (e.g. po is expr -O --); this is a powerful hint to 160 // the help system that one cannot pass options to this command 161 virtual bool IsDashDashCommand() { return false; } 162 163 virtual lldb::CommandObjectSP GetSubcommandSP(llvm::StringRef sub_cmd, 164 StringList *matches = nullptr) { 165 return lldb::CommandObjectSP(); 166 } 167 168 virtual lldb::CommandObjectSP GetSubcommandSPExact(llvm::StringRef sub_cmd) { 169 return lldb::CommandObjectSP(); 170 } 171 172 virtual CommandObject *GetSubcommandObject(llvm::StringRef sub_cmd, 173 StringList *matches = nullptr) { 174 return nullptr; 175 } 176 177 void FormatLongHelpText(Stream &output_strm, llvm::StringRef long_help); 178 179 void GenerateHelpText(CommandReturnObject &result); 180 181 virtual void GenerateHelpText(Stream &result); 182 183 // this is needed in order to allow the SBCommand class to transparently try 184 // and load subcommands - it will fail on anything but a multiword command, 185 // but it avoids us doing type checkings and casts 186 virtual bool LoadSubCommand(llvm::StringRef cmd_name, 187 const lldb::CommandObjectSP &command_obj) { 188 return false; 189 } 190 191 virtual llvm::Error LoadUserSubcommand(llvm::StringRef cmd_name, 192 const lldb::CommandObjectSP &command_obj, 193 bool can_replace) { 194 return llvm::createStringError(llvm::inconvertibleErrorCode(), 195 "can only add commands to container commands"); 196 } 197 198 virtual bool WantsRawCommandString() = 0; 199 200 // By default, WantsCompletion = !WantsRawCommandString. Subclasses who want 201 // raw command string but desire, for example, argument completion should 202 // override this method to return true. 203 virtual bool WantsCompletion() { return !WantsRawCommandString(); } 204 205 virtual Options *GetOptions(); 206 207 static lldb::CommandArgumentType LookupArgumentName(llvm::StringRef arg_name); 208 209 static const ArgumentTableEntry * 210 FindArgumentDataByType(lldb::CommandArgumentType arg_type); 211 212 // Sets the argument list for this command to one homogenous argument type, 213 // with the repeat specified. 214 void AddSimpleArgumentList( 215 lldb::CommandArgumentType arg_type, 216 ArgumentRepetitionType repetition_type = eArgRepeatPlain); 217 218 // Helper function to set BP IDs or ID ranges as the command argument data 219 // for this command. 220 // This used to just populate an entry you could add to, but that was never 221 // used. If we ever need that we can take optional extra args here. 222 // Use this to define a simple argument list: 223 enum IDType { eBreakpointArgs = 0, eWatchpointArgs = 1 }; 224 void AddIDsArgumentData(IDType type); 225 226 int GetNumArgumentEntries(); 227 228 CommandArgumentEntry *GetArgumentEntryAtIndex(int idx); 229 230 static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type, 231 CommandInterpreter &interpreter); 232 233 static const char *GetArgumentName(lldb::CommandArgumentType arg_type); 234 235 // Generates a nicely formatted command args string for help command output. 236 // By default, all possible args are taken into account, for example, '<expr 237 // | variable-name>'. This can be refined by passing a second arg specifying 238 // which option set(s) we are interested, which could then, for example, 239 // produce either '<expr>' or '<variable-name>'. 240 void GetFormattedCommandArguments(Stream &str, 241 uint32_t opt_set_mask = LLDB_OPT_SET_ALL); 242 243 static bool IsPairType(ArgumentRepetitionType arg_repeat_type); 244 245 static std::optional<ArgumentRepetitionType> 246 ArgRepetitionFromString(llvm::StringRef string); 247 248 bool ParseOptions(Args &args, CommandReturnObject &result); 249 250 void SetCommandName(llvm::StringRef name); 251 252 /// This default version handles calling option argument completions and then 253 /// calls HandleArgumentCompletion if the cursor is on an argument, not an 254 /// option. Don't override this method, override HandleArgumentCompletion 255 /// instead unless you have special reasons. 256 /// 257 /// \param[in,out] request 258 /// The completion request that needs to be answered. 259 virtual void HandleCompletion(CompletionRequest &request); 260 261 /// The default version handles argument definitions that have only one 262 /// argument type, and use one of the argument types that have an entry in 263 /// the CommonCompletions. Override this if you have a more complex 264 /// argument setup. 265 /// FIXME: we should be able to extend this to more complex argument 266 /// definitions provided we have completers for all the argument types. 267 /// 268 /// The input array contains a parsed version of the line. 269 /// 270 /// We've constructed the map of options and their arguments as well if that 271 /// is helpful for the completion. 272 /// 273 /// \param[in,out] request 274 /// The completion request that needs to be answered. 275 virtual void 276 HandleArgumentCompletion(CompletionRequest &request, 277 OptionElementVector &opt_element_vector); 278 279 bool HelpTextContainsWord(llvm::StringRef search_word, 280 bool search_short_help = true, 281 bool search_long_help = true, 282 bool search_syntax = true, 283 bool search_options = true); 284 285 /// The flags accessor. 286 /// 287 /// \return 288 /// A reference to the Flags member variable. 289 Flags &GetFlags() { return m_flags; } 290 291 /// The flags const accessor. 292 /// 293 /// \return 294 /// A const reference to the Flags member variable. 295 const Flags &GetFlags() const { return m_flags; } 296 297 /// Get the command that appropriate for a "repeat" of the current command. 298 /// 299 /// \param[in] current_command_args 300 /// The command arguments. 301 /// 302 /// \param[in] index 303 /// This is for internal use - it is how the completion request is tracked 304 /// in CommandObjectMultiword, and should otherwise be ignored. 305 /// 306 /// \return 307 /// std::nullopt if there is no special repeat command - it will use the 308 /// current command line. 309 /// Otherwise a std::string containing the command to be repeated. 310 /// If the string is empty, the command won't be allow repeating. 311 virtual std::optional<std::string> 312 GetRepeatCommand(Args ¤t_command_args, uint32_t index) { 313 return std::nullopt; 314 } 315 316 bool HasOverrideCallback() const { 317 return m_command_override_callback || 318 m_deprecated_command_override_callback; 319 } 320 321 void SetOverrideCallback(lldb::CommandOverrideCallback callback, 322 void *baton) { 323 m_deprecated_command_override_callback = callback; 324 m_command_override_baton = baton; 325 } 326 327 void 328 SetOverrideCallback(lldb_private::CommandOverrideCallbackWithResult callback, 329 void *baton) { 330 m_command_override_callback = callback; 331 m_command_override_baton = baton; 332 } 333 334 bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result) { 335 if (m_command_override_callback) 336 return m_command_override_callback(m_command_override_baton, argv, 337 result); 338 else if (m_deprecated_command_override_callback) 339 return m_deprecated_command_override_callback(m_command_override_baton, 340 argv); 341 else 342 return false; 343 } 344 345 /// Set the command input as it appeared in the terminal. This 346 /// is used to have errors refer directly to the original command. 347 void SetOriginalCommandString(std::string s) { m_original_command = s; } 348 349 /// \param offset_in_command is on what column \c args_string 350 /// appears, if applicable. This enables diagnostics that refer back 351 /// to the user input. 352 virtual void Execute(const char *args_string, 353 CommandReturnObject &result) = 0; 354 355 protected: 356 bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, 357 OptionGroupOptions &group_options, 358 ExecutionContext &exe_ctx); 359 360 virtual const char *GetInvalidTargetDescription() { 361 return "invalid target, create a target using the 'target create' command"; 362 } 363 364 virtual const char *GetInvalidProcessDescription() { 365 return "Command requires a current process."; 366 } 367 368 virtual const char *GetInvalidThreadDescription() { 369 return "Command requires a process which is currently stopped."; 370 } 371 372 virtual const char *GetInvalidFrameDescription() { 373 return "Command requires a process, which is currently stopped."; 374 } 375 376 virtual const char *GetInvalidRegContextDescription() { 377 return "invalid frame, no registers, command requires a process which is " 378 "currently stopped."; 379 } 380 381 Target &GetDummyTarget(); 382 383 // This is for use in the command interpreter, and returns the most relevant 384 // target. In order of priority, that's the target from the command object's 385 // execution context, the target from the interpreter's execution context, the 386 // selected target or the dummy target. 387 Target &GetTarget(); 388 389 // If a command needs to use the "current" thread, use this call. Command 390 // objects will have an ExecutionContext to use, and that may or may not have 391 // a thread in it. If it does, you should use that by default, if not, then 392 // use the ExecutionContext's target's selected thread, etc... This call 393 // insulates you from the details of this calculation. 394 Thread *GetDefaultThread(); 395 396 /// Check the command to make sure anything required by this 397 /// command is available. 398 /// 399 /// \param[out] result 400 /// A command result object, if it is not okay to run the command 401 /// this will be filled in with a suitable error. 402 /// 403 /// \return 404 /// \b true if it is okay to run this command, \b false otherwise. 405 bool CheckRequirements(CommandReturnObject &result); 406 407 void Cleanup(); 408 409 CommandInterpreter &m_interpreter; 410 ExecutionContext m_exe_ctx; 411 std::unique_lock<std::recursive_mutex> m_api_locker; 412 std::string m_cmd_name; 413 std::string m_cmd_help_short; 414 std::string m_cmd_help_long; 415 std::string m_cmd_syntax; 416 std::string m_original_command; 417 Flags m_flags; 418 std::vector<CommandArgumentEntry> m_arguments; 419 lldb::CommandOverrideCallback m_deprecated_command_override_callback; 420 lldb_private::CommandOverrideCallbackWithResult m_command_override_callback; 421 void *m_command_override_baton; 422 bool m_is_user_command = false; 423 }; 424 425 class CommandObjectParsed : public CommandObject { 426 public: 427 CommandObjectParsed(CommandInterpreter &interpreter, const char *name, 428 const char *help = nullptr, const char *syntax = nullptr, 429 uint32_t flags = 0) 430 : CommandObject(interpreter, name, help, syntax, flags) {} 431 432 ~CommandObjectParsed() override = default; 433 434 void Execute(const char *args_string, CommandReturnObject &result) override; 435 436 protected: 437 virtual void DoExecute(Args &command, CommandReturnObject &result) = 0; 438 439 bool WantsRawCommandString() override { return false; } 440 }; 441 442 class CommandObjectRaw : public CommandObject { 443 public: 444 CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, 445 llvm::StringRef help = "", llvm::StringRef syntax = "", 446 uint32_t flags = 0) 447 : CommandObject(interpreter, name, help, syntax, flags) {} 448 449 ~CommandObjectRaw() override = default; 450 451 void Execute(const char *args_string, CommandReturnObject &result) override; 452 453 protected: 454 virtual void DoExecute(llvm::StringRef command, 455 CommandReturnObject &result) = 0; 456 457 bool WantsRawCommandString() override { return true; } 458 }; 459 460 } // namespace lldb_private 461 462 #endif // LLDB_INTERPRETER_COMMANDOBJECT_H 463