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