1 //===-- CommandObjectWatchpointCommand.cpp ----------------------*- 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 #include <vector> 10 11 #include "CommandObjectWatchpoint.h" 12 #include "CommandObjectWatchpointCommand.h" 13 #include "lldb/Breakpoint/StoppointCallbackContext.h" 14 #include "lldb/Breakpoint/Watchpoint.h" 15 #include "lldb/Core/IOHandler.h" 16 #include "lldb/Host/OptionParser.h" 17 #include "lldb/Interpreter/CommandInterpreter.h" 18 #include "lldb/Interpreter/CommandReturnObject.h" 19 #include "lldb/Interpreter/OptionArgParser.h" 20 #include "lldb/Target/Target.h" 21 #include "lldb/Target/Thread.h" 22 #include "lldb/Utility/State.h" 23 24 using namespace lldb; 25 using namespace lldb_private; 26 27 // FIXME: "script-type" needs to have its contents determined dynamically, so 28 // somebody can add a new scripting language to lldb and have it pickable here 29 // without having to change this enumeration by hand and rebuild lldb proper. 30 static constexpr OptionEnumValueElement g_script_option_enumeration[] = { 31 { 32 eScriptLanguageNone, 33 "command", 34 "Commands are in the lldb command interpreter language", 35 }, 36 { 37 eScriptLanguagePython, 38 "python", 39 "Commands are in the Python language.", 40 }, 41 { 42 eSortOrderByName, 43 "default-script", 44 "Commands are in the default scripting language.", 45 }, 46 }; 47 48 static constexpr OptionEnumValues ScriptOptionEnum() { 49 return OptionEnumValues(g_script_option_enumeration); 50 } 51 52 #define LLDB_OPTIONS_watchpoint_command_add 53 #include "CommandOptions.inc" 54 55 class CommandObjectWatchpointCommandAdd : public CommandObjectParsed, 56 public IOHandlerDelegateMultiline { 57 public: 58 CommandObjectWatchpointCommandAdd(CommandInterpreter &interpreter) 59 : CommandObjectParsed(interpreter, "add", 60 "Add a set of LLDB commands to a watchpoint, to be " 61 "executed whenever the watchpoint is hit.", 62 nullptr, eCommandRequiresTarget), 63 IOHandlerDelegateMultiline("DONE", 64 IOHandlerDelegate::Completion::LLDBCommand), 65 m_options() { 66 SetHelpLong( 67 R"( 68 General information about entering watchpoint commands 69 ------------------------------------------------------ 70 71 )" 72 "This command will prompt for commands to be executed when the specified \ 73 watchpoint is hit. Each command is typed on its own line following the '> ' \ 74 prompt until 'DONE' is entered." 75 R"( 76 77 )" 78 "Syntactic errors may not be detected when initially entered, and many \ 79 malformed commands can silently fail when executed. If your watchpoint commands \ 80 do not appear to be executing, double-check the command syntax." 81 R"( 82 83 )" 84 "Note: You may enter any debugger command exactly as you would at the debugger \ 85 prompt. There is no limit to the number of commands supplied, but do NOT enter \ 86 more than one command per line." 87 R"( 88 89 Special information about PYTHON watchpoint commands 90 ---------------------------------------------------- 91 92 )" 93 "You may enter either one or more lines of Python, including function \ 94 definitions or calls to functions that will have been imported by the time \ 95 the code executes. Single line watchpoint commands will be interpreted 'as is' \ 96 when the watchpoint is hit. Multiple lines of Python will be wrapped in a \ 97 generated function, and a call to the function will be attached to the watchpoint." 98 R"( 99 100 This auto-generated function is passed in three arguments: 101 102 frame: an lldb.SBFrame object for the frame which hit the watchpoint. 103 104 wp: the watchpoint that was hit. 105 106 )" 107 "When specifying a python function with the --python-function option, you need \ 108 to supply the function name prepended by the module name:" 109 R"( 110 111 --python-function myutils.watchpoint_callback 112 113 The function itself must have the following prototype: 114 115 def watchpoint_callback(frame, wp): 116 # Your code goes here 117 118 )" 119 "The arguments are the same as the arguments passed to generated functions as \ 120 described above. Note that the global variable 'lldb.frame' will NOT be updated when \ 121 this function is called, so be sure to use the 'frame' argument. The 'frame' argument \ 122 can get you to the thread via frame.GetThread(), the thread can get you to the \ 123 process via thread.GetProcess(), and the process can get you back to the target \ 124 via process.GetTarget()." 125 R"( 126 127 )" 128 "Important Note: As Python code gets collected into functions, access to global \ 129 variables requires explicit scoping using the 'global' keyword. Be sure to use correct \ 130 Python syntax, including indentation, when entering Python watchpoint commands." 131 R"( 132 133 Example Python one-line watchpoint command: 134 135 (lldb) watchpoint command add -s python 1 136 Enter your Python command(s). Type 'DONE' to end. 137 > print "Hit this watchpoint!" 138 > DONE 139 140 As a convenience, this also works for a short Python one-liner: 141 142 (lldb) watchpoint command add -s python 1 -o 'import time; print time.asctime()' 143 (lldb) run 144 Launching '.../a.out' (x86_64) 145 (lldb) Fri Sep 10 12:17:45 2010 146 Process 21778 Stopped 147 * thread #1: tid = 0x2e03, 0x0000000100000de8 a.out`c + 7 at main.c:39, stop reason = watchpoint 1.1, queue = com.apple.main-thread 148 36 149 37 int c(int val) 150 38 { 151 39 -> return val + 3; 152 40 } 153 41 154 42 int main (int argc, char const *argv[]) 155 156 Example multiple line Python watchpoint command, using function definition: 157 158 (lldb) watchpoint command add -s python 1 159 Enter your Python command(s). Type 'DONE' to end. 160 > def watchpoint_output (wp_no): 161 > out_string = "Hit watchpoint number " + repr (wp_no) 162 > print out_string 163 > return True 164 > watchpoint_output (1) 165 > DONE 166 167 Example multiple line Python watchpoint command, using 'loose' Python: 168 169 (lldb) watchpoint command add -s p 1 170 Enter your Python command(s). Type 'DONE' to end. 171 > global wp_count 172 > wp_count = wp_count + 1 173 > print "Hit this watchpoint " + repr(wp_count) + " times!" 174 > DONE 175 176 )" 177 "In this case, since there is a reference to a global variable, \ 178 'wp_count', you will also need to make sure 'wp_count' exists and is \ 179 initialized:" 180 R"( 181 182 (lldb) script 183 >>> wp_count = 0 184 >>> quit() 185 186 )" 187 "Final Note: A warning that no watchpoint command was generated when there \ 188 are no syntax errors may indicate that a function was declared but never called."); 189 190 CommandArgumentEntry arg; 191 CommandArgumentData wp_id_arg; 192 193 // Define the first (and only) variant of this arg. 194 wp_id_arg.arg_type = eArgTypeWatchpointID; 195 wp_id_arg.arg_repetition = eArgRepeatPlain; 196 197 // There is only one variant this argument could be; put it into the 198 // argument entry. 199 arg.push_back(wp_id_arg); 200 201 // Push the data for the first argument into the m_arguments vector. 202 m_arguments.push_back(arg); 203 } 204 205 ~CommandObjectWatchpointCommandAdd() override = default; 206 207 Options *GetOptions() override { return &m_options; } 208 209 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override { 210 StreamFileSP output_sp(io_handler.GetOutputStreamFileSP()); 211 if (output_sp && interactive) { 212 output_sp->PutCString( 213 "Enter your debugger command(s). Type 'DONE' to end.\n"); 214 output_sp->Flush(); 215 } 216 } 217 218 void IOHandlerInputComplete(IOHandler &io_handler, 219 std::string &line) override { 220 io_handler.SetIsDone(true); 221 222 // The WatchpointOptions object is owned by the watchpoint or watchpoint 223 // location 224 WatchpointOptions *wp_options = 225 (WatchpointOptions *)io_handler.GetUserData(); 226 if (wp_options) { 227 std::unique_ptr<WatchpointOptions::CommandData> data_up( 228 new WatchpointOptions::CommandData()); 229 if (data_up) { 230 data_up->user_source.SplitIntoLines(line); 231 auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>( 232 std::move(data_up)); 233 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp); 234 } 235 } 236 } 237 238 void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, 239 CommandReturnObject &result) { 240 m_interpreter.GetLLDBCommandsFromIOHandler( 241 "> ", // Prompt 242 *this, // IOHandlerDelegate 243 true, // Run IOHandler in async mode 244 wp_options); // Baton for the "io_handler" that will be passed back into 245 // our IOHandlerDelegate functions 246 } 247 248 /// Set a one-liner as the callback for the watchpoint. 249 void SetWatchpointCommandCallback(WatchpointOptions *wp_options, 250 const char *oneliner) { 251 std::unique_ptr<WatchpointOptions::CommandData> data_up( 252 new WatchpointOptions::CommandData()); 253 254 // It's necessary to set both user_source and script_source to the 255 // oneliner. The former is used to generate callback description (as in 256 // watchpoint command list) while the latter is used for Python to 257 // interpret during the actual callback. 258 data_up->user_source.AppendString(oneliner); 259 data_up->script_source.assign(oneliner); 260 data_up->stop_on_error = m_options.m_stop_on_error; 261 262 auto baton_sp = 263 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); 264 wp_options->SetCallback(WatchpointOptionsCallbackFunction, baton_sp); 265 } 266 267 static bool 268 WatchpointOptionsCallbackFunction(void *baton, 269 StoppointCallbackContext *context, 270 lldb::user_id_t watch_id) { 271 bool ret_value = true; 272 if (baton == nullptr) 273 return true; 274 275 WatchpointOptions::CommandData *data = 276 (WatchpointOptions::CommandData *)baton; 277 StringList &commands = data->user_source; 278 279 if (commands.GetSize() > 0) { 280 ExecutionContext exe_ctx(context->exe_ctx_ref); 281 Target *target = exe_ctx.GetTargetPtr(); 282 if (target) { 283 CommandReturnObject result; 284 Debugger &debugger = target->GetDebugger(); 285 // Rig up the results secondary output stream to the debugger's, so the 286 // output will come out synchronously if the debugger is set up that 287 // way. 288 289 StreamSP output_stream(debugger.GetAsyncOutputStream()); 290 StreamSP error_stream(debugger.GetAsyncErrorStream()); 291 result.SetImmediateOutputStream(output_stream); 292 result.SetImmediateErrorStream(error_stream); 293 294 CommandInterpreterRunOptions options; 295 options.SetStopOnContinue(true); 296 options.SetStopOnError(data->stop_on_error); 297 options.SetEchoCommands(false); 298 options.SetPrintResults(true); 299 options.SetPrintErrors(true); 300 options.SetAddToHistory(false); 301 302 debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx, 303 options, result); 304 result.GetImmediateOutputStream()->Flush(); 305 result.GetImmediateErrorStream()->Flush(); 306 } 307 } 308 return ret_value; 309 } 310 311 class CommandOptions : public Options { 312 public: 313 CommandOptions() 314 : Options(), m_use_commands(false), m_use_script_language(false), 315 m_script_language(eScriptLanguageNone), m_use_one_liner(false), 316 m_one_liner(), m_function_name() {} 317 318 ~CommandOptions() override = default; 319 320 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, 321 ExecutionContext *execution_context) override { 322 Status error; 323 const int short_option = m_getopt_table[option_idx].val; 324 325 switch (short_option) { 326 case 'o': 327 m_use_one_liner = true; 328 m_one_liner = option_arg; 329 break; 330 331 case 's': 332 m_script_language = (lldb::ScriptLanguage)OptionArgParser::ToOptionEnum( 333 option_arg, GetDefinitions()[option_idx].enum_values, 334 eScriptLanguageNone, error); 335 336 m_use_script_language = (m_script_language == eScriptLanguagePython || 337 m_script_language == eScriptLanguageDefault); 338 break; 339 340 case 'e': { 341 bool success = false; 342 m_stop_on_error = 343 OptionArgParser::ToBoolean(option_arg, false, &success); 344 if (!success) 345 error.SetErrorStringWithFormat( 346 "invalid value for stop-on-error: \"%s\"", 347 option_arg.str().c_str()); 348 } break; 349 350 case 'F': 351 m_use_one_liner = false; 352 m_use_script_language = true; 353 m_function_name.assign(option_arg); 354 break; 355 356 default: 357 llvm_unreachable("Unimplemented option"); 358 } 359 return error; 360 } 361 362 void OptionParsingStarting(ExecutionContext *execution_context) override { 363 m_use_commands = true; 364 m_use_script_language = false; 365 m_script_language = eScriptLanguageNone; 366 367 m_use_one_liner = false; 368 m_stop_on_error = true; 369 m_one_liner.clear(); 370 m_function_name.clear(); 371 } 372 373 llvm::ArrayRef<OptionDefinition> GetDefinitions() override { 374 return llvm::makeArrayRef(g_watchpoint_command_add_options); 375 } 376 377 // Instance variables to hold the values for command options. 378 379 bool m_use_commands; 380 bool m_use_script_language; 381 lldb::ScriptLanguage m_script_language; 382 383 // Instance variables to hold the values for one_liner options. 384 bool m_use_one_liner; 385 std::string m_one_liner; 386 bool m_stop_on_error; 387 std::string m_function_name; 388 }; 389 390 protected: 391 bool DoExecute(Args &command, CommandReturnObject &result) override { 392 Target *target = &GetSelectedTarget(); 393 394 const WatchpointList &watchpoints = target->GetWatchpointList(); 395 size_t num_watchpoints = watchpoints.GetSize(); 396 397 if (num_watchpoints == 0) { 398 result.AppendError("No watchpoints exist to have commands added"); 399 result.SetStatus(eReturnStatusFailed); 400 return false; 401 } 402 403 if (!m_options.m_use_script_language && 404 !m_options.m_function_name.empty()) { 405 result.AppendError("need to enable scripting to have a function run as a " 406 "watchpoint command"); 407 result.SetStatus(eReturnStatusFailed); 408 return false; 409 } 410 411 std::vector<uint32_t> valid_wp_ids; 412 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, 413 valid_wp_ids)) { 414 result.AppendError("Invalid watchpoints specification."); 415 result.SetStatus(eReturnStatusFailed); 416 return false; 417 } 418 419 result.SetStatus(eReturnStatusSuccessFinishNoResult); 420 const size_t count = valid_wp_ids.size(); 421 for (size_t i = 0; i < count; ++i) { 422 uint32_t cur_wp_id = valid_wp_ids.at(i); 423 if (cur_wp_id != LLDB_INVALID_WATCH_ID) { 424 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get(); 425 // Sanity check wp first. 426 if (wp == nullptr) 427 continue; 428 429 WatchpointOptions *wp_options = wp->GetOptions(); 430 // Skip this watchpoint if wp_options is not good. 431 if (wp_options == nullptr) 432 continue; 433 434 // If we are using script language, get the script interpreter in order 435 // to set or collect command callback. Otherwise, call the methods 436 // associated with this object. 437 if (m_options.m_use_script_language) { 438 // Special handling for one-liner specified inline. 439 if (m_options.m_use_one_liner) { 440 GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback( 441 wp_options, m_options.m_one_liner.c_str()); 442 } 443 // Special handling for using a Python function by name instead of 444 // extending the watchpoint callback data structures, we just 445 // automatize what the user would do manually: make their watchpoint 446 // command be a function call 447 else if (!m_options.m_function_name.empty()) { 448 std::string oneliner(m_options.m_function_name); 449 oneliner += "(frame, wp, internal_dict)"; 450 GetDebugger().GetScriptInterpreter()->SetWatchpointCommandCallback( 451 wp_options, oneliner.c_str()); 452 } else { 453 GetDebugger() 454 .GetScriptInterpreter() 455 ->CollectDataForWatchpointCommandCallback(wp_options, result); 456 } 457 } else { 458 // Special handling for one-liner specified inline. 459 if (m_options.m_use_one_liner) 460 SetWatchpointCommandCallback(wp_options, 461 m_options.m_one_liner.c_str()); 462 else 463 CollectDataForWatchpointCommandCallback(wp_options, result); 464 } 465 } 466 } 467 468 return result.Succeeded(); 469 } 470 471 private: 472 CommandOptions m_options; 473 }; 474 475 // CommandObjectWatchpointCommandDelete 476 477 class CommandObjectWatchpointCommandDelete : public CommandObjectParsed { 478 public: 479 CommandObjectWatchpointCommandDelete(CommandInterpreter &interpreter) 480 : CommandObjectParsed(interpreter, "delete", 481 "Delete the set of commands from a watchpoint.", 482 nullptr, eCommandRequiresTarget) { 483 CommandArgumentEntry arg; 484 CommandArgumentData wp_id_arg; 485 486 // Define the first (and only) variant of this arg. 487 wp_id_arg.arg_type = eArgTypeWatchpointID; 488 wp_id_arg.arg_repetition = eArgRepeatPlain; 489 490 // There is only one variant this argument could be; put it into the 491 // argument entry. 492 arg.push_back(wp_id_arg); 493 494 // Push the data for the first argument into the m_arguments vector. 495 m_arguments.push_back(arg); 496 } 497 498 ~CommandObjectWatchpointCommandDelete() override = default; 499 500 protected: 501 bool DoExecute(Args &command, CommandReturnObject &result) override { 502 Target *target = &GetSelectedTarget(); 503 504 const WatchpointList &watchpoints = target->GetWatchpointList(); 505 size_t num_watchpoints = watchpoints.GetSize(); 506 507 if (num_watchpoints == 0) { 508 result.AppendError("No watchpoints exist to have commands deleted"); 509 result.SetStatus(eReturnStatusFailed); 510 return false; 511 } 512 513 if (command.GetArgumentCount() == 0) { 514 result.AppendError( 515 "No watchpoint specified from which to delete the commands"); 516 result.SetStatus(eReturnStatusFailed); 517 return false; 518 } 519 520 std::vector<uint32_t> valid_wp_ids; 521 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, 522 valid_wp_ids)) { 523 result.AppendError("Invalid watchpoints specification."); 524 result.SetStatus(eReturnStatusFailed); 525 return false; 526 } 527 528 result.SetStatus(eReturnStatusSuccessFinishNoResult); 529 const size_t count = valid_wp_ids.size(); 530 for (size_t i = 0; i < count; ++i) { 531 uint32_t cur_wp_id = valid_wp_ids.at(i); 532 if (cur_wp_id != LLDB_INVALID_WATCH_ID) { 533 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get(); 534 if (wp) 535 wp->ClearCallback(); 536 } else { 537 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", cur_wp_id); 538 result.SetStatus(eReturnStatusFailed); 539 return false; 540 } 541 } 542 return result.Succeeded(); 543 } 544 }; 545 546 // CommandObjectWatchpointCommandList 547 548 class CommandObjectWatchpointCommandList : public CommandObjectParsed { 549 public: 550 CommandObjectWatchpointCommandList(CommandInterpreter &interpreter) 551 : CommandObjectParsed(interpreter, "list", 552 "List the script or set of commands to be executed " 553 "when the watchpoint is hit.", 554 nullptr, eCommandRequiresTarget) { 555 CommandArgumentEntry arg; 556 CommandArgumentData wp_id_arg; 557 558 // Define the first (and only) variant of this arg. 559 wp_id_arg.arg_type = eArgTypeWatchpointID; 560 wp_id_arg.arg_repetition = eArgRepeatPlain; 561 562 // There is only one variant this argument could be; put it into the 563 // argument entry. 564 arg.push_back(wp_id_arg); 565 566 // Push the data for the first argument into the m_arguments vector. 567 m_arguments.push_back(arg); 568 } 569 570 ~CommandObjectWatchpointCommandList() override = default; 571 572 protected: 573 bool DoExecute(Args &command, CommandReturnObject &result) override { 574 Target *target = &GetSelectedTarget(); 575 576 const WatchpointList &watchpoints = target->GetWatchpointList(); 577 size_t num_watchpoints = watchpoints.GetSize(); 578 579 if (num_watchpoints == 0) { 580 result.AppendError("No watchpoints exist for which to list commands"); 581 result.SetStatus(eReturnStatusFailed); 582 return false; 583 } 584 585 if (command.GetArgumentCount() == 0) { 586 result.AppendError( 587 "No watchpoint specified for which to list the commands"); 588 result.SetStatus(eReturnStatusFailed); 589 return false; 590 } 591 592 std::vector<uint32_t> valid_wp_ids; 593 if (!CommandObjectMultiwordWatchpoint::VerifyWatchpointIDs(target, command, 594 valid_wp_ids)) { 595 result.AppendError("Invalid watchpoints specification."); 596 result.SetStatus(eReturnStatusFailed); 597 return false; 598 } 599 600 result.SetStatus(eReturnStatusSuccessFinishNoResult); 601 const size_t count = valid_wp_ids.size(); 602 for (size_t i = 0; i < count; ++i) { 603 uint32_t cur_wp_id = valid_wp_ids.at(i); 604 if (cur_wp_id != LLDB_INVALID_WATCH_ID) { 605 Watchpoint *wp = target->GetWatchpointList().FindByID(cur_wp_id).get(); 606 607 if (wp) { 608 const WatchpointOptions *wp_options = wp->GetOptions(); 609 if (wp_options) { 610 // Get the callback baton associated with the current watchpoint. 611 const Baton *baton = wp_options->GetBaton(); 612 if (baton) { 613 result.GetOutputStream().Printf("Watchpoint %u:\n", cur_wp_id); 614 result.GetOutputStream().IndentMore(); 615 baton->GetDescription(&result.GetOutputStream(), 616 eDescriptionLevelFull); 617 result.GetOutputStream().IndentLess(); 618 } else { 619 result.AppendMessageWithFormat( 620 "Watchpoint %u does not have an associated command.\n", 621 cur_wp_id); 622 } 623 } 624 result.SetStatus(eReturnStatusSuccessFinishResult); 625 } else { 626 result.AppendErrorWithFormat("Invalid watchpoint ID: %u.\n", 627 cur_wp_id); 628 result.SetStatus(eReturnStatusFailed); 629 } 630 } 631 } 632 633 return result.Succeeded(); 634 } 635 }; 636 637 // CommandObjectWatchpointCommand 638 639 CommandObjectWatchpointCommand::CommandObjectWatchpointCommand( 640 CommandInterpreter &interpreter) 641 : CommandObjectMultiword( 642 interpreter, "command", 643 "Commands for adding, removing and examining LLDB commands " 644 "executed when the watchpoint is hit (watchpoint 'commands').", 645 "command <sub-command> [<sub-command-options>] <watchpoint-id>") { 646 CommandObjectSP add_command_object( 647 new CommandObjectWatchpointCommandAdd(interpreter)); 648 CommandObjectSP delete_command_object( 649 new CommandObjectWatchpointCommandDelete(interpreter)); 650 CommandObjectSP list_command_object( 651 new CommandObjectWatchpointCommandList(interpreter)); 652 653 add_command_object->SetCommandName("watchpoint command add"); 654 delete_command_object->SetCommandName("watchpoint command delete"); 655 list_command_object->SetCommandName("watchpoint command list"); 656 657 LoadSubCommand("add", add_command_object); 658 LoadSubCommand("delete", delete_command_object); 659 LoadSubCommand("list", list_command_object); 660 } 661 662 CommandObjectWatchpointCommand::~CommandObjectWatchpointCommand() = default; 663