1 //===-- Process.cpp ---------------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/Target/Process.h" 11 12 #include "lldb/lldb-private-log.h" 13 14 #include "lldb/Breakpoint/StoppointCallbackContext.h" 15 #include "lldb/Breakpoint/BreakpointLocation.h" 16 #include "lldb/Core/Event.h" 17 #include "lldb/Core/ConnectionFileDescriptor.h" 18 #include "lldb/Core/Debugger.h" 19 #include "lldb/Core/InputReader.h" 20 #include "lldb/Core/Log.h" 21 #include "lldb/Core/PluginManager.h" 22 #include "lldb/Core/State.h" 23 #include "lldb/Expression/ClangUserExpression.h" 24 #include "lldb/Interpreter/CommandInterpreter.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Target/ABI.h" 27 #include "lldb/Target/DynamicLoader.h" 28 #include "lldb/Target/OperatingSystem.h" 29 #include "lldb/Target/LanguageRuntime.h" 30 #include "lldb/Target/CPPLanguageRuntime.h" 31 #include "lldb/Target/ObjCLanguageRuntime.h" 32 #include "lldb/Target/Platform.h" 33 #include "lldb/Target/RegisterContext.h" 34 #include "lldb/Target/StopInfo.h" 35 #include "lldb/Target/Target.h" 36 #include "lldb/Target/TargetList.h" 37 #include "lldb/Target/Thread.h" 38 #include "lldb/Target/ThreadPlan.h" 39 40 using namespace lldb; 41 using namespace lldb_private; 42 43 void 44 ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const 45 { 46 const char *cstr; 47 if (m_pid != LLDB_INVALID_PROCESS_ID) 48 s.Printf (" pid = %llu\n", m_pid); 49 50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID) 51 s.Printf (" parent = %llu\n", m_parent_pid); 52 53 if (m_executable) 54 { 55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString()); 56 s.PutCString (" file = "); 57 m_executable.Dump(&s); 58 s.EOL(); 59 } 60 const uint32_t argc = m_arguments.GetArgumentCount(); 61 if (argc > 0) 62 { 63 for (uint32_t i=0; i<argc; i++) 64 { 65 const char *arg = m_arguments.GetArgumentAtIndex(i); 66 if (i < 10) 67 s.Printf (" arg[%u] = %s\n", i, arg); 68 else 69 s.Printf ("arg[%u] = %s\n", i, arg); 70 } 71 } 72 73 const uint32_t envc = m_environment.GetArgumentCount(); 74 if (envc > 0) 75 { 76 for (uint32_t i=0; i<envc; i++) 77 { 78 const char *env = m_environment.GetArgumentAtIndex(i); 79 if (i < 10) 80 s.Printf (" env[%u] = %s\n", i, env); 81 else 82 s.Printf ("env[%u] = %s\n", i, env); 83 } 84 } 85 86 if (m_arch.IsValid()) 87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str()); 88 89 if (m_uid != UINT32_MAX) 90 { 91 cstr = platform->GetUserName (m_uid); 92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : ""); 93 } 94 if (m_gid != UINT32_MAX) 95 { 96 cstr = platform->GetGroupName (m_gid); 97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : ""); 98 } 99 if (m_euid != UINT32_MAX) 100 { 101 cstr = platform->GetUserName (m_euid); 102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : ""); 103 } 104 if (m_egid != UINT32_MAX) 105 { 106 cstr = platform->GetGroupName (m_egid); 107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : ""); 108 } 109 } 110 111 void 112 ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose) 113 { 114 const char *label; 115 if (show_args || verbose) 116 label = "ARGUMENTS"; 117 else 118 label = "NAME"; 119 120 if (verbose) 121 { 122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label); 123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n"); 124 } 125 else 126 { 127 s.Printf ("PID PARENT USER ARCH %s\n", label); 128 s.PutCString ("====== ====== ========== ======= ============================\n"); 129 } 130 } 131 132 void 133 ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const 134 { 135 if (m_pid != LLDB_INVALID_PROCESS_ID) 136 { 137 const char *cstr; 138 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid); 139 140 141 if (verbose) 142 { 143 cstr = platform->GetUserName (m_uid); 144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 145 s.Printf ("%-10s ", cstr); 146 else 147 s.Printf ("%-10u ", m_uid); 148 149 cstr = platform->GetGroupName (m_gid); 150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 151 s.Printf ("%-10s ", cstr); 152 else 153 s.Printf ("%-10u ", m_gid); 154 155 cstr = platform->GetUserName (m_euid); 156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 157 s.Printf ("%-10s ", cstr); 158 else 159 s.Printf ("%-10u ", m_euid); 160 161 cstr = platform->GetGroupName (m_egid); 162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed 163 s.Printf ("%-10s ", cstr); 164 else 165 s.Printf ("%-10u ", m_egid); 166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : ""); 167 } 168 else 169 { 170 s.Printf ("%-10s %-7d %s ", 171 platform->GetUserName (m_euid), 172 (int)m_arch.GetTriple().getArchName().size(), 173 m_arch.GetTriple().getArchName().data()); 174 } 175 176 if (verbose || show_args) 177 { 178 const uint32_t argc = m_arguments.GetArgumentCount(); 179 if (argc > 0) 180 { 181 for (uint32_t i=0; i<argc; i++) 182 { 183 if (i > 0) 184 s.PutChar (' '); 185 s.PutCString (m_arguments.GetArgumentAtIndex(i)); 186 } 187 } 188 } 189 else 190 { 191 s.PutCString (GetName()); 192 } 193 194 s.EOL(); 195 } 196 } 197 198 199 void 200 ProcessInfo::SetArguments (char const **argv, 201 bool first_arg_is_executable, 202 bool first_arg_is_executable_and_argument) 203 { 204 m_arguments.SetArguments (argv); 205 206 // Is the first argument the executable? 207 if (first_arg_is_executable) 208 { 209 const char *first_arg = m_arguments.GetArgumentAtIndex (0); 210 if (first_arg) 211 { 212 // Yes the first argument is an executable, set it as the executable 213 // in the launch options. Don't resolve the file path as the path 214 // could be a remote platform path 215 const bool resolve = false; 216 m_executable.SetFile(first_arg, resolve); 217 218 // If argument zero is an executable and shouldn't be included 219 // in the arguments, remove it from the front of the arguments 220 if (first_arg_is_executable_and_argument == false) 221 m_arguments.DeleteArgumentAtIndex (0); 222 } 223 } 224 } 225 void 226 ProcessInfo::SetArguments (const Args& args, 227 bool first_arg_is_executable, 228 bool first_arg_is_executable_and_argument) 229 { 230 // Copy all arguments 231 m_arguments = args; 232 233 // Is the first argument the executable? 234 if (first_arg_is_executable) 235 { 236 const char *first_arg = m_arguments.GetArgumentAtIndex (0); 237 if (first_arg) 238 { 239 // Yes the first argument is an executable, set it as the executable 240 // in the launch options. Don't resolve the file path as the path 241 // could be a remote platform path 242 const bool resolve = false; 243 m_executable.SetFile(first_arg, resolve); 244 245 // If argument zero is an executable and shouldn't be included 246 // in the arguments, remove it from the front of the arguments 247 if (first_arg_is_executable_and_argument == false) 248 m_arguments.DeleteArgumentAtIndex (0); 249 } 250 } 251 } 252 253 void 254 ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty) 255 { 256 // If notthing was specified, then check the process for any default 257 // settings that were set with "settings set" 258 if (m_file_actions.empty()) 259 { 260 if (m_flags.Test(eLaunchFlagDisableSTDIO)) 261 { 262 AppendSuppressFileAction (STDIN_FILENO , true, false); 263 AppendSuppressFileAction (STDOUT_FILENO, false, true); 264 AppendSuppressFileAction (STDERR_FILENO, false, true); 265 } 266 else 267 { 268 // Check for any values that might have gotten set with any of: 269 // (lldb) settings set target.input-path 270 // (lldb) settings set target.output-path 271 // (lldb) settings set target.error-path 272 const char *in_path = NULL; 273 const char *out_path = NULL; 274 const char *err_path = NULL; 275 if (target) 276 { 277 in_path = target->GetStandardInputPath(); 278 out_path = target->GetStandardOutputPath(); 279 err_path = target->GetStandardErrorPath(); 280 } 281 282 if (default_to_use_pty && (!in_path && !out_path && !err_path)) 283 { 284 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0)) 285 { 286 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0); 287 } 288 } 289 290 if (in_path) 291 AppendOpenFileAction(STDIN_FILENO, in_path, true, false); 292 293 if (out_path) 294 AppendOpenFileAction(STDOUT_FILENO, out_path, false, true); 295 296 if (err_path) 297 AppendOpenFileAction(STDERR_FILENO, err_path, false, true); 298 299 } 300 } 301 } 302 303 304 bool 305 ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost) 306 { 307 error.Clear(); 308 309 if (GetFlags().Test (eLaunchFlagLaunchInShell)) 310 { 311 const char *shell_executable = GetShell(); 312 if (shell_executable) 313 { 314 char shell_resolved_path[PATH_MAX]; 315 316 if (localhost) 317 { 318 FileSpec shell_filespec (shell_executable, true); 319 320 if (!shell_filespec.Exists()) 321 { 322 // Resolve the path in case we just got "bash", "sh" or "tcsh" 323 if (!shell_filespec.ResolveExecutableLocation ()) 324 { 325 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable); 326 return false; 327 } 328 } 329 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path)); 330 shell_executable = shell_resolved_path; 331 } 332 333 Args shell_arguments; 334 std::string safe_arg; 335 shell_arguments.AppendArgument (shell_executable); 336 StreamString shell_command; 337 shell_arguments.AppendArgument ("-c"); 338 shell_command.PutCString ("exec"); 339 if (GetArchitecture().IsValid()) 340 { 341 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName()); 342 // Set the resume count to 2: 343 // 1 - stop in shell 344 // 2 - stop in /usr/bin/arch 345 // 3 - then we will stop in our program 346 SetResumeCount(2); 347 } 348 else 349 { 350 // Set the resume count to 1: 351 // 1 - stop in shell 352 // 2 - then we will stop in our program 353 SetResumeCount(1); 354 } 355 356 const char **argv = GetArguments().GetConstArgumentVector (); 357 if (argv) 358 { 359 for (size_t i=0; argv[i] != NULL; ++i) 360 { 361 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg); 362 shell_command.Printf(" %s", arg); 363 } 364 } 365 shell_arguments.AppendArgument (shell_command.GetString().c_str()); 366 367 m_executable.SetFile(shell_executable, false); 368 m_arguments = shell_arguments; 369 return true; 370 } 371 else 372 { 373 error.SetErrorString ("invalid shell path"); 374 } 375 } 376 else 377 { 378 error.SetErrorString ("not launching in shell"); 379 } 380 return false; 381 } 382 383 384 bool 385 ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write) 386 { 387 if ((read || write) && fd >= 0 && path && path[0]) 388 { 389 m_action = eFileActionOpen; 390 m_fd = fd; 391 if (read && write) 392 m_arg = O_NOCTTY | O_CREAT | O_RDWR; 393 else if (read) 394 m_arg = O_NOCTTY | O_RDONLY; 395 else 396 m_arg = O_NOCTTY | O_CREAT | O_WRONLY; 397 m_path.assign (path); 398 return true; 399 } 400 else 401 { 402 Clear(); 403 } 404 return false; 405 } 406 407 bool 408 ProcessLaunchInfo::FileAction::Close (int fd) 409 { 410 Clear(); 411 if (fd >= 0) 412 { 413 m_action = eFileActionClose; 414 m_fd = fd; 415 } 416 return m_fd >= 0; 417 } 418 419 420 bool 421 ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd) 422 { 423 Clear(); 424 if (fd >= 0 && dup_fd >= 0) 425 { 426 m_action = eFileActionDuplicate; 427 m_fd = fd; 428 m_arg = dup_fd; 429 } 430 return m_fd >= 0; 431 } 432 433 434 435 bool 436 ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions, 437 const FileAction *info, 438 Log *log, 439 Error& error) 440 { 441 if (info == NULL) 442 return false; 443 444 switch (info->m_action) 445 { 446 case eFileActionNone: 447 error.Clear(); 448 break; 449 450 case eFileActionClose: 451 if (info->m_fd == -1) 452 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)"); 453 else 454 { 455 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd), 456 eErrorTypePOSIX); 457 if (log && (error.Fail() || log)) 458 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)", 459 file_actions, info->m_fd); 460 } 461 break; 462 463 case eFileActionDuplicate: 464 if (info->m_fd == -1) 465 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)"); 466 else if (info->m_arg == -1) 467 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)"); 468 else 469 { 470 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg), 471 eErrorTypePOSIX); 472 if (log && (error.Fail() || log)) 473 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)", 474 file_actions, info->m_fd, info->m_arg); 475 } 476 break; 477 478 case eFileActionOpen: 479 if (info->m_fd == -1) 480 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)"); 481 else 482 { 483 int oflag = info->m_arg; 484 485 mode_t mode = 0; 486 487 if (oflag & O_CREAT) 488 mode = 0640; 489 490 error.SetError (::posix_spawn_file_actions_addopen (file_actions, 491 info->m_fd, 492 info->m_path.c_str(), 493 oflag, 494 mode), 495 eErrorTypePOSIX); 496 if (error.Fail() || log) 497 error.PutToLog(log, 498 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)", 499 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode); 500 } 501 break; 502 503 default: 504 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action); 505 break; 506 } 507 return error.Success(); 508 } 509 510 Error 511 ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg) 512 { 513 Error error; 514 char short_option = (char) m_getopt_table[option_idx].val; 515 516 switch (short_option) 517 { 518 case 's': // Stop at program entry point 519 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry); 520 break; 521 522 case 'i': // STDIN for read only 523 { 524 ProcessLaunchInfo::FileAction action; 525 if (action.Open (STDIN_FILENO, option_arg, true, false)) 526 launch_info.AppendFileAction (action); 527 } 528 break; 529 530 case 'o': // Open STDOUT for write only 531 { 532 ProcessLaunchInfo::FileAction action; 533 if (action.Open (STDOUT_FILENO, option_arg, false, true)) 534 launch_info.AppendFileAction (action); 535 } 536 break; 537 538 case 'e': // STDERR for write only 539 { 540 ProcessLaunchInfo::FileAction action; 541 if (action.Open (STDERR_FILENO, option_arg, false, true)) 542 launch_info.AppendFileAction (action); 543 } 544 break; 545 546 547 case 'p': // Process plug-in name 548 launch_info.SetProcessPluginName (option_arg); 549 break; 550 551 case 'n': // Disable STDIO 552 { 553 ProcessLaunchInfo::FileAction action; 554 if (action.Open (STDIN_FILENO, "/dev/null", true, false)) 555 launch_info.AppendFileAction (action); 556 if (action.Open (STDOUT_FILENO, "/dev/null", false, true)) 557 launch_info.AppendFileAction (action); 558 if (action.Open (STDERR_FILENO, "/dev/null", false, true)) 559 launch_info.AppendFileAction (action); 560 } 561 break; 562 563 case 'w': 564 launch_info.SetWorkingDirectory (option_arg); 565 break; 566 567 case 't': // Open process in new terminal window 568 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY); 569 break; 570 571 case 'a': 572 launch_info.GetArchitecture().SetTriple (option_arg, 573 m_interpreter.GetPlatform(true).get()); 574 break; 575 576 case 'A': 577 launch_info.GetFlags().Set (eLaunchFlagDisableASLR); 578 break; 579 580 case 'c': 581 if (option_arg && option_arg[0]) 582 launch_info.SetShell (option_arg); 583 else 584 launch_info.SetShell ("/bin/bash"); 585 break; 586 587 case 'v': 588 launch_info.GetEnvironmentEntries().AppendArgument(option_arg); 589 break; 590 591 default: 592 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option); 593 break; 594 595 } 596 return error; 597 } 598 599 OptionDefinition 600 ProcessLaunchCommandOptions::g_option_table[] = 601 { 602 { LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."}, 603 { LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."}, 604 { LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."}, 605 { LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."}, 606 { LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."}, 607 { LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."}, 608 { LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."}, 609 610 { LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."}, 611 { LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."}, 612 { LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."}, 613 614 { LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."}, 615 616 { LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."}, 617 618 { 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } 619 }; 620 621 622 623 bool 624 ProcessInstanceInfoMatch::NameMatches (const char *process_name) const 625 { 626 if (m_name_match_type == eNameMatchIgnore || process_name == NULL) 627 return true; 628 const char *match_name = m_match_info.GetName(); 629 if (!match_name) 630 return true; 631 632 return lldb_private::NameMatches (process_name, m_name_match_type, match_name); 633 } 634 635 bool 636 ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const 637 { 638 if (!NameMatches (proc_info.GetName())) 639 return false; 640 641 if (m_match_info.ProcessIDIsValid() && 642 m_match_info.GetProcessID() != proc_info.GetProcessID()) 643 return false; 644 645 if (m_match_info.ParentProcessIDIsValid() && 646 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID()) 647 return false; 648 649 if (m_match_info.UserIDIsValid () && 650 m_match_info.GetUserID() != proc_info.GetUserID()) 651 return false; 652 653 if (m_match_info.GroupIDIsValid () && 654 m_match_info.GetGroupID() != proc_info.GetGroupID()) 655 return false; 656 657 if (m_match_info.EffectiveUserIDIsValid () && 658 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID()) 659 return false; 660 661 if (m_match_info.EffectiveGroupIDIsValid () && 662 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID()) 663 return false; 664 665 if (m_match_info.GetArchitecture().IsValid() && 666 m_match_info.GetArchitecture() != proc_info.GetArchitecture()) 667 return false; 668 return true; 669 } 670 671 bool 672 ProcessInstanceInfoMatch::MatchAllProcesses () const 673 { 674 if (m_name_match_type != eNameMatchIgnore) 675 return false; 676 677 if (m_match_info.ProcessIDIsValid()) 678 return false; 679 680 if (m_match_info.ParentProcessIDIsValid()) 681 return false; 682 683 if (m_match_info.UserIDIsValid ()) 684 return false; 685 686 if (m_match_info.GroupIDIsValid ()) 687 return false; 688 689 if (m_match_info.EffectiveUserIDIsValid ()) 690 return false; 691 692 if (m_match_info.EffectiveGroupIDIsValid ()) 693 return false; 694 695 if (m_match_info.GetArchitecture().IsValid()) 696 return false; 697 698 if (m_match_all_users) 699 return false; 700 701 return true; 702 703 } 704 705 void 706 ProcessInstanceInfoMatch::Clear() 707 { 708 m_match_info.Clear(); 709 m_name_match_type = eNameMatchIgnore; 710 m_match_all_users = false; 711 } 712 713 ProcessSP 714 Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path) 715 { 716 ProcessSP process_sp; 717 ProcessCreateInstance create_callback = NULL; 718 if (plugin_name) 719 { 720 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name); 721 if (create_callback) 722 { 723 process_sp = create_callback(target, listener, crash_file_path); 724 if (process_sp) 725 { 726 if (!process_sp->CanDebug(target, true)) 727 process_sp.reset(); 728 } 729 } 730 } 731 else 732 { 733 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx) 734 { 735 process_sp = create_callback(target, listener, crash_file_path); 736 if (process_sp) 737 { 738 if (!process_sp->CanDebug(target, false)) 739 process_sp.reset(); 740 else 741 break; 742 } 743 } 744 } 745 return process_sp; 746 } 747 748 ConstString & 749 Process::GetStaticBroadcasterClass () 750 { 751 static ConstString class_name ("lldb.process"); 752 return class_name; 753 } 754 755 //---------------------------------------------------------------------- 756 // Process constructor 757 //---------------------------------------------------------------------- 758 Process::Process(Target &target, Listener &listener) : 759 UserID (LLDB_INVALID_PROCESS_ID), 760 Broadcaster (&(target.GetDebugger()), "lldb.process"), 761 ProcessInstanceSettings (GetSettingsController()), 762 m_target (target), 763 m_public_state (eStateUnloaded), 764 m_private_state (eStateUnloaded), 765 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"), 766 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"), 767 m_private_state_listener ("lldb.process.internal_state_listener"), 768 m_private_state_control_wait(), 769 m_private_state_thread (LLDB_INVALID_HOST_THREAD), 770 m_mod_id (), 771 m_thread_index_id (0), 772 m_exit_status (-1), 773 m_exit_string (), 774 m_thread_list (this), 775 m_notifications (), 776 m_image_tokens (), 777 m_listener (listener), 778 m_breakpoint_site_list (), 779 m_dynamic_checkers_ap (), 780 m_unix_signals (), 781 m_abi_sp (), 782 m_process_input_reader (), 783 m_stdio_communication ("process.stdio"), 784 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive), 785 m_stdout_data (), 786 m_stderr_data (), 787 m_memory_cache (*this), 788 m_allocated_memory_cache (*this), 789 m_should_detach (false), 790 m_next_event_action_ap(), 791 m_can_jit(eCanJITDontKnow) 792 { 793 UpdateInstanceName(); 794 795 CheckInWithManager (); 796 797 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 798 if (log) 799 log->Printf ("%p Process::Process()", this); 800 801 SetEventName (eBroadcastBitStateChanged, "state-changed"); 802 SetEventName (eBroadcastBitInterrupt, "interrupt"); 803 SetEventName (eBroadcastBitSTDOUT, "stdout-available"); 804 SetEventName (eBroadcastBitSTDERR, "stderr-available"); 805 806 listener.StartListeningForEvents (this, 807 eBroadcastBitStateChanged | 808 eBroadcastBitInterrupt | 809 eBroadcastBitSTDOUT | 810 eBroadcastBitSTDERR); 811 812 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster, 813 eBroadcastBitStateChanged); 814 815 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster, 816 eBroadcastInternalStateControlStop | 817 eBroadcastInternalStateControlPause | 818 eBroadcastInternalStateControlResume); 819 } 820 821 //---------------------------------------------------------------------- 822 // Destructor 823 //---------------------------------------------------------------------- 824 Process::~Process() 825 { 826 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 827 if (log) 828 log->Printf ("%p Process::~Process()", this); 829 StopPrivateStateThread(); 830 } 831 832 void 833 Process::Finalize() 834 { 835 switch (GetPrivateState()) 836 { 837 case eStateConnected: 838 case eStateAttaching: 839 case eStateLaunching: 840 case eStateStopped: 841 case eStateRunning: 842 case eStateStepping: 843 case eStateCrashed: 844 case eStateSuspended: 845 if (GetShouldDetach()) 846 Detach(); 847 else 848 Destroy(); 849 break; 850 851 case eStateInvalid: 852 case eStateUnloaded: 853 case eStateDetached: 854 case eStateExited: 855 break; 856 } 857 858 // Clear our broadcaster before we proceed with destroying 859 Broadcaster::Clear(); 860 861 // Do any cleanup needed prior to being destructed... Subclasses 862 // that override this method should call this superclass method as well. 863 864 // We need to destroy the loader before the derived Process class gets destroyed 865 // since it is very likely that undoing the loader will require access to the real process. 866 m_dynamic_checkers_ap.reset(); 867 m_abi_sp.reset(); 868 m_os_ap.reset(); 869 m_dyld_ap.reset(); 870 m_thread_list.Destroy(); 871 std::vector<Notifications> empty_notifications; 872 m_notifications.swap(empty_notifications); 873 m_image_tokens.clear(); 874 m_memory_cache.Clear(); 875 m_allocated_memory_cache.Clear(); 876 m_language_runtimes.clear(); 877 m_next_event_action_ap.reset(); 878 } 879 880 void 881 Process::RegisterNotificationCallbacks (const Notifications& callbacks) 882 { 883 m_notifications.push_back(callbacks); 884 if (callbacks.initialize != NULL) 885 callbacks.initialize (callbacks.baton, this); 886 } 887 888 bool 889 Process::UnregisterNotificationCallbacks(const Notifications& callbacks) 890 { 891 std::vector<Notifications>::iterator pos, end = m_notifications.end(); 892 for (pos = m_notifications.begin(); pos != end; ++pos) 893 { 894 if (pos->baton == callbacks.baton && 895 pos->initialize == callbacks.initialize && 896 pos->process_state_changed == callbacks.process_state_changed) 897 { 898 m_notifications.erase(pos); 899 return true; 900 } 901 } 902 return false; 903 } 904 905 void 906 Process::SynchronouslyNotifyStateChanged (StateType state) 907 { 908 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end(); 909 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos) 910 { 911 if (notification_pos->process_state_changed) 912 notification_pos->process_state_changed (notification_pos->baton, this, state); 913 } 914 } 915 916 // FIXME: We need to do some work on events before the general Listener sees them. 917 // For instance if we are continuing from a breakpoint, we need to ensure that we do 918 // the little "insert real insn, step & stop" trick. But we can't do that when the 919 // event is delivered by the broadcaster - since that is done on the thread that is 920 // waiting for new events, so if we needed more than one event for our handling, we would 921 // stall. So instead we do it when we fetch the event off of the queue. 922 // 923 924 StateType 925 Process::GetNextEvent (EventSP &event_sp) 926 { 927 StateType state = eStateInvalid; 928 929 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp) 930 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 931 932 return state; 933 } 934 935 936 StateType 937 Process::WaitForProcessToStop (const TimeValue *timeout) 938 { 939 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target. 940 // We have to actually check each event, and in the case of a stopped event check the restarted flag 941 // on the event. 942 EventSP event_sp; 943 StateType state = GetState(); 944 // If we are exited or detached, we won't ever get back to any 945 // other valid state... 946 if (state == eStateDetached || state == eStateExited) 947 return state; 948 949 while (state != eStateInvalid) 950 { 951 state = WaitForStateChangedEvents (timeout, event_sp); 952 switch (state) 953 { 954 case eStateCrashed: 955 case eStateDetached: 956 case eStateExited: 957 case eStateUnloaded: 958 return state; 959 case eStateStopped: 960 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) 961 continue; 962 else 963 return state; 964 default: 965 continue; 966 } 967 } 968 return state; 969 } 970 971 972 StateType 973 Process::WaitForState 974 ( 975 const TimeValue *timeout, 976 const StateType *match_states, const uint32_t num_match_states 977 ) 978 { 979 EventSP event_sp; 980 uint32_t i; 981 StateType state = GetState(); 982 while (state != eStateInvalid) 983 { 984 // If we are exited or detached, we won't ever get back to any 985 // other valid state... 986 if (state == eStateDetached || state == eStateExited) 987 return state; 988 989 state = WaitForStateChangedEvents (timeout, event_sp); 990 991 for (i=0; i<num_match_states; ++i) 992 { 993 if (match_states[i] == state) 994 return state; 995 } 996 } 997 return state; 998 } 999 1000 bool 1001 Process::HijackProcessEvents (Listener *listener) 1002 { 1003 if (listener != NULL) 1004 { 1005 return HijackBroadcaster(listener, eBroadcastBitStateChanged); 1006 } 1007 else 1008 return false; 1009 } 1010 1011 void 1012 Process::RestoreProcessEvents () 1013 { 1014 RestoreBroadcaster(); 1015 } 1016 1017 bool 1018 Process::HijackPrivateProcessEvents (Listener *listener) 1019 { 1020 if (listener != NULL) 1021 { 1022 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged); 1023 } 1024 else 1025 return false; 1026 } 1027 1028 void 1029 Process::RestorePrivateProcessEvents () 1030 { 1031 m_private_state_broadcaster.RestoreBroadcaster(); 1032 } 1033 1034 StateType 1035 Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp) 1036 { 1037 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1038 1039 if (log) 1040 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1041 1042 StateType state = eStateInvalid; 1043 if (m_listener.WaitForEventForBroadcasterWithType (timeout, 1044 this, 1045 eBroadcastBitStateChanged, 1046 event_sp)) 1047 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1048 1049 if (log) 1050 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", 1051 __FUNCTION__, 1052 timeout, 1053 StateAsCString(state)); 1054 return state; 1055 } 1056 1057 Event * 1058 Process::PeekAtStateChangedEvents () 1059 { 1060 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1061 1062 if (log) 1063 log->Printf ("Process::%s...", __FUNCTION__); 1064 1065 Event *event_ptr; 1066 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this, 1067 eBroadcastBitStateChanged); 1068 if (log) 1069 { 1070 if (event_ptr) 1071 { 1072 log->Printf ("Process::%s (event_ptr) => %s", 1073 __FUNCTION__, 1074 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr))); 1075 } 1076 else 1077 { 1078 log->Printf ("Process::%s no events found", 1079 __FUNCTION__); 1080 } 1081 } 1082 return event_ptr; 1083 } 1084 1085 StateType 1086 Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp) 1087 { 1088 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1089 1090 if (log) 1091 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1092 1093 StateType state = eStateInvalid; 1094 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout, 1095 &m_private_state_broadcaster, 1096 eBroadcastBitStateChanged, 1097 event_sp)) 1098 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1099 1100 // This is a bit of a hack, but when we wait here we could very well return 1101 // to the command-line, and that could disable the log, which would render the 1102 // log we got above invalid. 1103 if (log) 1104 { 1105 if (state == eStateInvalid) 1106 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout); 1107 else 1108 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state)); 1109 } 1110 return state; 1111 } 1112 1113 bool 1114 Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only) 1115 { 1116 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1117 1118 if (log) 1119 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout); 1120 1121 if (control_only) 1122 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp); 1123 else 1124 return m_private_state_listener.WaitForEvent(timeout, event_sp); 1125 } 1126 1127 bool 1128 Process::IsRunning () const 1129 { 1130 return StateIsRunningState (m_public_state.GetValue()); 1131 } 1132 1133 int 1134 Process::GetExitStatus () 1135 { 1136 if (m_public_state.GetValue() == eStateExited) 1137 return m_exit_status; 1138 return -1; 1139 } 1140 1141 1142 const char * 1143 Process::GetExitDescription () 1144 { 1145 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) 1146 return m_exit_string.c_str(); 1147 return NULL; 1148 } 1149 1150 bool 1151 Process::SetExitStatus (int status, const char *cstr) 1152 { 1153 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1154 if (log) 1155 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", 1156 status, status, 1157 cstr ? "\"" : "", 1158 cstr ? cstr : "NULL", 1159 cstr ? "\"" : ""); 1160 1161 // We were already in the exited state 1162 if (m_private_state.GetValue() == eStateExited) 1163 { 1164 if (log) 1165 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited"); 1166 return false; 1167 } 1168 1169 m_exit_status = status; 1170 if (cstr) 1171 m_exit_string = cstr; 1172 else 1173 m_exit_string.clear(); 1174 1175 DidExit (); 1176 1177 SetPrivateState (eStateExited); 1178 return true; 1179 } 1180 1181 // This static callback can be used to watch for local child processes on 1182 // the current host. The the child process exits, the process will be 1183 // found in the global target list (we want to be completely sure that the 1184 // lldb_private::Process doesn't go away before we can deliver the signal. 1185 bool 1186 Process::SetProcessExitStatus (void *callback_baton, 1187 lldb::pid_t pid, 1188 bool exited, 1189 int signo, // Zero for no signal 1190 int exit_status // Exit value of process if signal is zero 1191 ) 1192 { 1193 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 1194 if (log) 1195 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n", 1196 callback_baton, 1197 pid, 1198 exited, 1199 signo, 1200 exit_status); 1201 1202 if (exited) 1203 { 1204 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid)); 1205 if (target_sp) 1206 { 1207 ProcessSP process_sp (target_sp->GetProcessSP()); 1208 if (process_sp) 1209 { 1210 const char *signal_cstr = NULL; 1211 if (signo) 1212 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo); 1213 1214 process_sp->SetExitStatus (exit_status, signal_cstr); 1215 } 1216 } 1217 return true; 1218 } 1219 return false; 1220 } 1221 1222 1223 void 1224 Process::UpdateThreadListIfNeeded () 1225 { 1226 const uint32_t stop_id = GetStopID(); 1227 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID()) 1228 { 1229 const StateType state = GetPrivateState(); 1230 if (StateIsStoppedState (state, true)) 1231 { 1232 Mutex::Locker locker (m_thread_list.GetMutex ()); 1233 // m_thread_list does have its own mutex, but we need to 1234 // hold onto the mutex between the call to UpdateThreadList(...) 1235 // and the os->UpdateThreadList(...) so it doesn't change on us 1236 ThreadList new_thread_list(this); 1237 // Always update the thread list with the protocol specific 1238 // thread list 1239 UpdateThreadList (m_thread_list, new_thread_list); 1240 OperatingSystem *os = GetOperatingSystem (); 1241 if (os) 1242 os->UpdateThreadList (m_thread_list, new_thread_list); 1243 m_thread_list.Update (new_thread_list); 1244 m_thread_list.SetStopID (stop_id); 1245 } 1246 } 1247 } 1248 1249 uint32_t 1250 Process::GetNextThreadIndexID () 1251 { 1252 return ++m_thread_index_id; 1253 } 1254 1255 StateType 1256 Process::GetState() 1257 { 1258 // If any other threads access this we will need a mutex for it 1259 return m_public_state.GetValue (); 1260 } 1261 1262 void 1263 Process::SetPublicState (StateType new_state) 1264 { 1265 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1266 if (log) 1267 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state)); 1268 m_public_state.SetValue (new_state); 1269 } 1270 1271 StateType 1272 Process::GetPrivateState () 1273 { 1274 return m_private_state.GetValue(); 1275 } 1276 1277 void 1278 Process::SetPrivateState (StateType new_state) 1279 { 1280 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS)); 1281 bool state_changed = false; 1282 1283 if (log) 1284 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state)); 1285 1286 Mutex::Locker locker(m_private_state.GetMutex()); 1287 1288 const StateType old_state = m_private_state.GetValueNoLock (); 1289 state_changed = old_state != new_state; 1290 if (state_changed) 1291 { 1292 m_private_state.SetValueNoLock (new_state); 1293 if (StateIsStoppedState(new_state, false)) 1294 { 1295 m_mod_id.BumpStopID(); 1296 m_memory_cache.Clear(); 1297 if (log) 1298 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID()); 1299 } 1300 // Use our target to get a shared pointer to ourselves... 1301 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state)); 1302 } 1303 else 1304 { 1305 if (log) 1306 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state)); 1307 } 1308 } 1309 1310 void 1311 Process::SetRunningUserExpression (bool on) 1312 { 1313 m_mod_id.SetRunningUserExpression (on); 1314 } 1315 1316 addr_t 1317 Process::GetImageInfoAddress() 1318 { 1319 return LLDB_INVALID_ADDRESS; 1320 } 1321 1322 //---------------------------------------------------------------------- 1323 // LoadImage 1324 // 1325 // This function provides a default implementation that works for most 1326 // unix variants. Any Process subclasses that need to do shared library 1327 // loading differently should override LoadImage and UnloadImage and 1328 // do what is needed. 1329 //---------------------------------------------------------------------- 1330 uint32_t 1331 Process::LoadImage (const FileSpec &image_spec, Error &error) 1332 { 1333 DynamicLoader *loader = GetDynamicLoader(); 1334 if (loader) 1335 { 1336 error = loader->CanLoadImage(); 1337 if (error.Fail()) 1338 return LLDB_INVALID_IMAGE_TOKEN; 1339 } 1340 1341 if (error.Success()) 1342 { 1343 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1344 1345 if (thread_sp) 1346 { 1347 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1348 1349 if (frame_sp) 1350 { 1351 ExecutionContext exe_ctx; 1352 frame_sp->CalculateExecutionContext (exe_ctx); 1353 bool unwind_on_error = true; 1354 StreamString expr; 1355 char path[PATH_MAX]; 1356 image_spec.GetPath(path, sizeof(path)); 1357 expr.Printf("dlopen (\"%s\", 2)", path); 1358 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n"; 1359 lldb::ValueObjectSP result_valobj_sp; 1360 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp); 1361 error = result_valobj_sp->GetError(); 1362 if (error.Success()) 1363 { 1364 Scalar scalar; 1365 if (result_valobj_sp->ResolveValue (scalar)) 1366 { 1367 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS); 1368 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS) 1369 { 1370 uint32_t image_token = m_image_tokens.size(); 1371 m_image_tokens.push_back (image_ptr); 1372 return image_token; 1373 } 1374 } 1375 } 1376 } 1377 } 1378 } 1379 return LLDB_INVALID_IMAGE_TOKEN; 1380 } 1381 1382 //---------------------------------------------------------------------- 1383 // UnloadImage 1384 // 1385 // This function provides a default implementation that works for most 1386 // unix variants. Any Process subclasses that need to do shared library 1387 // loading differently should override LoadImage and UnloadImage and 1388 // do what is needed. 1389 //---------------------------------------------------------------------- 1390 Error 1391 Process::UnloadImage (uint32_t image_token) 1392 { 1393 Error error; 1394 if (image_token < m_image_tokens.size()) 1395 { 1396 const addr_t image_addr = m_image_tokens[image_token]; 1397 if (image_addr == LLDB_INVALID_ADDRESS) 1398 { 1399 error.SetErrorString("image already unloaded"); 1400 } 1401 else 1402 { 1403 DynamicLoader *loader = GetDynamicLoader(); 1404 if (loader) 1405 error = loader->CanLoadImage(); 1406 1407 if (error.Success()) 1408 { 1409 ThreadSP thread_sp(GetThreadList ().GetSelectedThread()); 1410 1411 if (thread_sp) 1412 { 1413 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0)); 1414 1415 if (frame_sp) 1416 { 1417 ExecutionContext exe_ctx; 1418 frame_sp->CalculateExecutionContext (exe_ctx); 1419 bool unwind_on_error = true; 1420 StreamString expr; 1421 expr.Printf("dlclose ((void *)0x%llx)", image_addr); 1422 const char *prefix = "extern \"C\" int dlclose(void* handle);\n"; 1423 lldb::ValueObjectSP result_valobj_sp; 1424 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp); 1425 if (result_valobj_sp->GetError().Success()) 1426 { 1427 Scalar scalar; 1428 if (result_valobj_sp->ResolveValue (scalar)) 1429 { 1430 if (scalar.UInt(1)) 1431 { 1432 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData()); 1433 } 1434 else 1435 { 1436 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS; 1437 } 1438 } 1439 } 1440 else 1441 { 1442 error = result_valobj_sp->GetError(); 1443 } 1444 } 1445 } 1446 } 1447 } 1448 } 1449 else 1450 { 1451 error.SetErrorString("invalid image token"); 1452 } 1453 return error; 1454 } 1455 1456 const lldb::ABISP & 1457 Process::GetABI() 1458 { 1459 if (!m_abi_sp) 1460 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture()); 1461 return m_abi_sp; 1462 } 1463 1464 LanguageRuntime * 1465 Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null) 1466 { 1467 LanguageRuntimeCollection::iterator pos; 1468 pos = m_language_runtimes.find (language); 1469 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) 1470 { 1471 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language)); 1472 1473 m_language_runtimes[language] = runtime_sp; 1474 return runtime_sp.get(); 1475 } 1476 else 1477 return (*pos).second.get(); 1478 } 1479 1480 CPPLanguageRuntime * 1481 Process::GetCPPLanguageRuntime (bool retry_if_null) 1482 { 1483 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null); 1484 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus) 1485 return static_cast<CPPLanguageRuntime *> (runtime); 1486 return NULL; 1487 } 1488 1489 ObjCLanguageRuntime * 1490 Process::GetObjCLanguageRuntime (bool retry_if_null) 1491 { 1492 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null); 1493 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC) 1494 return static_cast<ObjCLanguageRuntime *> (runtime); 1495 return NULL; 1496 } 1497 1498 BreakpointSiteList & 1499 Process::GetBreakpointSiteList() 1500 { 1501 return m_breakpoint_site_list; 1502 } 1503 1504 const BreakpointSiteList & 1505 Process::GetBreakpointSiteList() const 1506 { 1507 return m_breakpoint_site_list; 1508 } 1509 1510 1511 void 1512 Process::DisableAllBreakpointSites () 1513 { 1514 m_breakpoint_site_list.SetEnabledForAll (false); 1515 } 1516 1517 Error 1518 Process::ClearBreakpointSiteByID (lldb::user_id_t break_id) 1519 { 1520 Error error (DisableBreakpointSiteByID (break_id)); 1521 1522 if (error.Success()) 1523 m_breakpoint_site_list.Remove(break_id); 1524 1525 return error; 1526 } 1527 1528 Error 1529 Process::DisableBreakpointSiteByID (lldb::user_id_t break_id) 1530 { 1531 Error error; 1532 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 1533 if (bp_site_sp) 1534 { 1535 if (bp_site_sp->IsEnabled()) 1536 error = DisableBreakpoint (bp_site_sp.get()); 1537 } 1538 else 1539 { 1540 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id); 1541 } 1542 1543 return error; 1544 } 1545 1546 Error 1547 Process::EnableBreakpointSiteByID (lldb::user_id_t break_id) 1548 { 1549 Error error; 1550 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id); 1551 if (bp_site_sp) 1552 { 1553 if (!bp_site_sp->IsEnabled()) 1554 error = EnableBreakpoint (bp_site_sp.get()); 1555 } 1556 else 1557 { 1558 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id); 1559 } 1560 return error; 1561 } 1562 1563 lldb::break_id_t 1564 Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware) 1565 { 1566 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target); 1567 if (load_addr != LLDB_INVALID_ADDRESS) 1568 { 1569 BreakpointSiteSP bp_site_sp; 1570 1571 // Look up this breakpoint site. If it exists, then add this new owner, otherwise 1572 // create a new breakpoint site and add it. 1573 1574 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr); 1575 1576 if (bp_site_sp) 1577 { 1578 bp_site_sp->AddOwner (owner); 1579 owner->SetBreakpointSite (bp_site_sp); 1580 return bp_site_sp->GetID(); 1581 } 1582 else 1583 { 1584 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware)); 1585 if (bp_site_sp) 1586 { 1587 if (EnableBreakpoint (bp_site_sp.get()).Success()) 1588 { 1589 owner->SetBreakpointSite (bp_site_sp); 1590 return m_breakpoint_site_list.Add (bp_site_sp); 1591 } 1592 } 1593 } 1594 } 1595 // We failed to enable the breakpoint 1596 return LLDB_INVALID_BREAK_ID; 1597 1598 } 1599 1600 void 1601 Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp) 1602 { 1603 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id); 1604 if (num_owners == 0) 1605 { 1606 DisableBreakpoint(bp_site_sp.get()); 1607 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); 1608 } 1609 } 1610 1611 1612 size_t 1613 Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const 1614 { 1615 size_t bytes_removed = 0; 1616 addr_t intersect_addr; 1617 size_t intersect_size; 1618 size_t opcode_offset; 1619 size_t idx; 1620 BreakpointSiteSP bp_sp; 1621 BreakpointSiteList bp_sites_in_range; 1622 1623 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range)) 1624 { 1625 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx) 1626 { 1627 if (bp_sp->GetType() == BreakpointSite::eSoftware) 1628 { 1629 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset)) 1630 { 1631 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); 1632 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size); 1633 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize()); 1634 size_t buf_offset = intersect_addr - bp_addr; 1635 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size); 1636 } 1637 } 1638 } 1639 } 1640 return bytes_removed; 1641 } 1642 1643 1644 1645 size_t 1646 Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site) 1647 { 1648 PlatformSP platform_sp (m_target.GetPlatform()); 1649 if (platform_sp) 1650 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site); 1651 return 0; 1652 } 1653 1654 Error 1655 Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site) 1656 { 1657 Error error; 1658 assert (bp_site != NULL); 1659 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1660 const addr_t bp_addr = bp_site->GetLoadAddress(); 1661 if (log) 1662 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr); 1663 if (bp_site->IsEnabled()) 1664 { 1665 if (log) 1666 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr); 1667 return error; 1668 } 1669 1670 if (bp_addr == LLDB_INVALID_ADDRESS) 1671 { 1672 error.SetErrorString("BreakpointSite contains an invalid load address."); 1673 return error; 1674 } 1675 // Ask the lldb::Process subclass to fill in the correct software breakpoint 1676 // trap for the breakpoint site 1677 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); 1678 1679 if (bp_opcode_size == 0) 1680 { 1681 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr); 1682 } 1683 else 1684 { 1685 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); 1686 1687 if (bp_opcode_bytes == NULL) 1688 { 1689 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode."); 1690 return error; 1691 } 1692 1693 // Save the original opcode by reading it 1694 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size) 1695 { 1696 // Write a software breakpoint in place of the original opcode 1697 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 1698 { 1699 uint8_t verify_bp_opcode_bytes[64]; 1700 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size) 1701 { 1702 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0) 1703 { 1704 bp_site->SetEnabled(true); 1705 bp_site->SetType (BreakpointSite::eSoftware); 1706 if (log) 1707 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", 1708 bp_site->GetID(), 1709 (uint64_t)bp_addr); 1710 } 1711 else 1712 error.SetErrorString("failed to verify the breakpoint trap in memory."); 1713 } 1714 else 1715 error.SetErrorString("Unable to read memory to verify breakpoint trap."); 1716 } 1717 else 1718 error.SetErrorString("Unable to write breakpoint trap to memory."); 1719 } 1720 else 1721 error.SetErrorString("Unable to read memory at breakpoint address."); 1722 } 1723 if (log && error.Fail()) 1724 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 1725 bp_site->GetID(), 1726 (uint64_t)bp_addr, 1727 error.AsCString()); 1728 return error; 1729 } 1730 1731 Error 1732 Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site) 1733 { 1734 Error error; 1735 assert (bp_site != NULL); 1736 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 1737 addr_t bp_addr = bp_site->GetLoadAddress(); 1738 lldb::user_id_t breakID = bp_site->GetID(); 1739 if (log) 1740 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr); 1741 1742 if (bp_site->IsHardware()) 1743 { 1744 error.SetErrorString("Breakpoint site is a hardware breakpoint."); 1745 } 1746 else if (bp_site->IsEnabled()) 1747 { 1748 const size_t break_op_size = bp_site->GetByteSize(); 1749 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes(); 1750 if (break_op_size > 0) 1751 { 1752 // Clear a software breakoint instruction 1753 uint8_t curr_break_op[8]; 1754 assert (break_op_size <= sizeof(curr_break_op)); 1755 bool break_op_found = false; 1756 1757 // Read the breakpoint opcode 1758 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size) 1759 { 1760 bool verify = false; 1761 // Make sure we have the a breakpoint opcode exists at this address 1762 if (::memcmp (curr_break_op, break_op, break_op_size) == 0) 1763 { 1764 break_op_found = true; 1765 // We found a valid breakpoint opcode at this address, now restore 1766 // the saved opcode. 1767 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size) 1768 { 1769 verify = true; 1770 } 1771 else 1772 error.SetErrorString("Memory write failed when restoring original opcode."); 1773 } 1774 else 1775 { 1776 error.SetErrorString("Original breakpoint trap is no longer in memory."); 1777 // Set verify to true and so we can check if the original opcode has already been restored 1778 verify = true; 1779 } 1780 1781 if (verify) 1782 { 1783 uint8_t verify_opcode[8]; 1784 assert (break_op_size < sizeof(verify_opcode)); 1785 // Verify that our original opcode made it back to the inferior 1786 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size) 1787 { 1788 // compare the memory we just read with the original opcode 1789 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0) 1790 { 1791 // SUCCESS 1792 bp_site->SetEnabled(false); 1793 if (log) 1794 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr); 1795 return error; 1796 } 1797 else 1798 { 1799 if (break_op_found) 1800 error.SetErrorString("Failed to restore original opcode."); 1801 } 1802 } 1803 else 1804 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored."); 1805 } 1806 } 1807 else 1808 error.SetErrorString("Unable to read memory that should contain the breakpoint trap."); 1809 } 1810 } 1811 else 1812 { 1813 if (log) 1814 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr); 1815 return error; 1816 } 1817 1818 if (log) 1819 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s", 1820 bp_site->GetID(), 1821 (uint64_t)bp_addr, 1822 error.AsCString()); 1823 return error; 1824 1825 } 1826 1827 // Comment out line below to disable memory caching 1828 #define ENABLE_MEMORY_CACHING 1829 // Uncomment to verify memory caching works after making changes to caching code 1830 //#define VERIFY_MEMORY_READS 1831 1832 #if defined (ENABLE_MEMORY_CACHING) 1833 1834 #if defined (VERIFY_MEMORY_READS) 1835 1836 size_t 1837 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1838 { 1839 // Memory caching is enabled, with debug verification 1840 if (buf && size) 1841 { 1842 // Uncomment the line below to make sure memory caching is working. 1843 // I ran this through the test suite and got no assertions, so I am 1844 // pretty confident this is working well. If any changes are made to 1845 // memory caching, uncomment the line below and test your changes! 1846 1847 // Verify all memory reads by using the cache first, then redundantly 1848 // reading the same memory from the inferior and comparing to make sure 1849 // everything is exactly the same. 1850 std::string verify_buf (size, '\0'); 1851 assert (verify_buf.size() == size); 1852 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error); 1853 Error verify_error; 1854 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error); 1855 assert (cache_bytes_read == verify_bytes_read); 1856 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); 1857 assert (verify_error.Success() == error.Success()); 1858 return cache_bytes_read; 1859 } 1860 return 0; 1861 } 1862 1863 #else // #if defined (VERIFY_MEMORY_READS) 1864 1865 size_t 1866 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1867 { 1868 // Memory caching enabled, no verification 1869 return m_memory_cache.Read (addr, buf, size, error); 1870 } 1871 1872 #endif // #else for #if defined (VERIFY_MEMORY_READS) 1873 1874 #else // #if defined (ENABLE_MEMORY_CACHING) 1875 1876 size_t 1877 Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error) 1878 { 1879 // Memory caching is disabled 1880 return ReadMemoryFromInferior (addr, buf, size, error); 1881 } 1882 1883 #endif // #else for #if defined (ENABLE_MEMORY_CACHING) 1884 1885 1886 size_t 1887 Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error) 1888 { 1889 size_t total_cstr_len = 0; 1890 if (dst && dst_max_len) 1891 { 1892 result_error.Clear(); 1893 // NULL out everything just to be safe 1894 memset (dst, 0, dst_max_len); 1895 Error error; 1896 addr_t curr_addr = addr; 1897 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); 1898 size_t bytes_left = dst_max_len - 1; 1899 char *curr_dst = dst; 1900 1901 while (bytes_left > 0) 1902 { 1903 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size); 1904 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left); 1905 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error); 1906 1907 if (bytes_read == 0) 1908 { 1909 result_error = error; 1910 dst[total_cstr_len] = '\0'; 1911 break; 1912 } 1913 const size_t len = strlen(curr_dst); 1914 1915 total_cstr_len += len; 1916 1917 if (len < bytes_to_read) 1918 break; 1919 1920 curr_dst += bytes_read; 1921 curr_addr += bytes_read; 1922 bytes_left -= bytes_read; 1923 } 1924 } 1925 else 1926 { 1927 if (dst == NULL) 1928 result_error.SetErrorString("invalid arguments"); 1929 else 1930 result_error.Clear(); 1931 } 1932 return total_cstr_len; 1933 } 1934 1935 size_t 1936 Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error) 1937 { 1938 if (buf == NULL || size == 0) 1939 return 0; 1940 1941 size_t bytes_read = 0; 1942 uint8_t *bytes = (uint8_t *)buf; 1943 1944 while (bytes_read < size) 1945 { 1946 const size_t curr_size = size - bytes_read; 1947 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read, 1948 bytes + bytes_read, 1949 curr_size, 1950 error); 1951 bytes_read += curr_bytes_read; 1952 if (curr_bytes_read == curr_size || curr_bytes_read == 0) 1953 break; 1954 } 1955 1956 // Replace any software breakpoint opcodes that fall into this range back 1957 // into "buf" before we return 1958 if (bytes_read > 0) 1959 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf); 1960 return bytes_read; 1961 } 1962 1963 uint64_t 1964 Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error) 1965 { 1966 Scalar scalar; 1967 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error)) 1968 return scalar.ULongLong(fail_value); 1969 return fail_value; 1970 } 1971 1972 addr_t 1973 Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error) 1974 { 1975 Scalar scalar; 1976 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error)) 1977 return scalar.ULongLong(LLDB_INVALID_ADDRESS); 1978 return LLDB_INVALID_ADDRESS; 1979 } 1980 1981 1982 bool 1983 Process::WritePointerToMemory (lldb::addr_t vm_addr, 1984 lldb::addr_t ptr_value, 1985 Error &error) 1986 { 1987 Scalar scalar; 1988 const uint32_t addr_byte_size = GetAddressByteSize(); 1989 if (addr_byte_size <= 4) 1990 scalar = (uint32_t)ptr_value; 1991 else 1992 scalar = ptr_value; 1993 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size; 1994 } 1995 1996 size_t 1997 Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error) 1998 { 1999 size_t bytes_written = 0; 2000 const uint8_t *bytes = (const uint8_t *)buf; 2001 2002 while (bytes_written < size) 2003 { 2004 const size_t curr_size = size - bytes_written; 2005 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written, 2006 bytes + bytes_written, 2007 curr_size, 2008 error); 2009 bytes_written += curr_bytes_written; 2010 if (curr_bytes_written == curr_size || curr_bytes_written == 0) 2011 break; 2012 } 2013 return bytes_written; 2014 } 2015 2016 size_t 2017 Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2018 { 2019 #if defined (ENABLE_MEMORY_CACHING) 2020 m_memory_cache.Flush (addr, size); 2021 #endif 2022 2023 if (buf == NULL || size == 0) 2024 return 0; 2025 2026 m_mod_id.BumpMemoryID(); 2027 2028 // We need to write any data that would go where any current software traps 2029 // (enabled software breakpoints) any software traps (breakpoints) that we 2030 // may have placed in our tasks memory. 2031 2032 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr); 2033 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end(); 2034 2035 if (iter == end || iter->second->GetLoadAddress() > addr + size) 2036 return WriteMemoryPrivate (addr, buf, size, error); 2037 2038 BreakpointSiteList::collection::const_iterator pos; 2039 size_t bytes_written = 0; 2040 addr_t intersect_addr = 0; 2041 size_t intersect_size = 0; 2042 size_t opcode_offset = 0; 2043 const uint8_t *ubuf = (const uint8_t *)buf; 2044 2045 for (pos = iter; pos != end; ++pos) 2046 { 2047 BreakpointSiteSP bp; 2048 bp = pos->second; 2049 2050 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset)); 2051 assert(addr <= intersect_addr && intersect_addr < addr + size); 2052 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); 2053 assert(opcode_offset + intersect_size <= bp->GetByteSize()); 2054 2055 // Check for bytes before this breakpoint 2056 const addr_t curr_addr = addr + bytes_written; 2057 if (intersect_addr > curr_addr) 2058 { 2059 // There are some bytes before this breakpoint that we need to 2060 // just write to memory 2061 size_t curr_size = intersect_addr - curr_addr; 2062 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr, 2063 ubuf + bytes_written, 2064 curr_size, 2065 error); 2066 bytes_written += curr_bytes_written; 2067 if (curr_bytes_written != curr_size) 2068 { 2069 // We weren't able to write all of the requested bytes, we 2070 // are done looping and will return the number of bytes that 2071 // we have written so far. 2072 break; 2073 } 2074 } 2075 2076 // Now write any bytes that would cover up any software breakpoints 2077 // directly into the breakpoint opcode buffer 2078 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); 2079 bytes_written += intersect_size; 2080 } 2081 2082 // Write any remaining bytes after the last breakpoint if we have any left 2083 if (bytes_written < size) 2084 bytes_written += WriteMemoryPrivate (addr + bytes_written, 2085 ubuf + bytes_written, 2086 size - bytes_written, 2087 error); 2088 2089 return bytes_written; 2090 } 2091 2092 size_t 2093 Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error) 2094 { 2095 if (byte_size == UINT32_MAX) 2096 byte_size = scalar.GetByteSize(); 2097 if (byte_size > 0) 2098 { 2099 uint8_t buf[32]; 2100 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error); 2101 if (mem_size > 0) 2102 return WriteMemory(addr, buf, mem_size, error); 2103 else 2104 error.SetErrorString ("failed to get scalar as memory data"); 2105 } 2106 else 2107 { 2108 error.SetErrorString ("invalid scalar value"); 2109 } 2110 return 0; 2111 } 2112 2113 size_t 2114 Process::ReadScalarIntegerFromMemory (addr_t addr, 2115 uint32_t byte_size, 2116 bool is_signed, 2117 Scalar &scalar, 2118 Error &error) 2119 { 2120 uint64_t uval; 2121 2122 if (byte_size <= sizeof(uval)) 2123 { 2124 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error); 2125 if (bytes_read == byte_size) 2126 { 2127 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize()); 2128 uint32_t offset = 0; 2129 if (byte_size <= 4) 2130 scalar = data.GetMaxU32 (&offset, byte_size); 2131 else 2132 scalar = data.GetMaxU64 (&offset, byte_size); 2133 2134 if (is_signed) 2135 scalar.SignExtend(byte_size * 8); 2136 return bytes_read; 2137 } 2138 } 2139 else 2140 { 2141 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size); 2142 } 2143 return 0; 2144 } 2145 2146 #define USE_ALLOCATE_MEMORY_CACHE 1 2147 addr_t 2148 Process::AllocateMemory(size_t size, uint32_t permissions, Error &error) 2149 { 2150 if (GetPrivateState() != eStateStopped) 2151 return LLDB_INVALID_ADDRESS; 2152 2153 #if defined (USE_ALLOCATE_MEMORY_CACHE) 2154 return m_allocated_memory_cache.AllocateMemory(size, permissions, error); 2155 #else 2156 addr_t allocated_addr = DoAllocateMemory (size, permissions, error); 2157 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2158 if (log) 2159 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)", 2160 size, 2161 GetPermissionsAsCString (permissions), 2162 (uint64_t)allocated_addr, 2163 m_mod_id.GetStopID(), 2164 m_mod_id.GetMemoryID()); 2165 return allocated_addr; 2166 #endif 2167 } 2168 2169 bool 2170 Process::CanJIT () 2171 { 2172 if (m_can_jit == eCanJITDontKnow) 2173 { 2174 Error err; 2175 2176 uint64_t allocated_memory = AllocateMemory(8, 2177 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, 2178 err); 2179 2180 if (err.Success()) 2181 m_can_jit = eCanJITYes; 2182 else 2183 m_can_jit = eCanJITNo; 2184 2185 DeallocateMemory (allocated_memory); 2186 } 2187 2188 return m_can_jit == eCanJITYes; 2189 } 2190 2191 void 2192 Process::SetCanJIT (bool can_jit) 2193 { 2194 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); 2195 } 2196 2197 Error 2198 Process::DeallocateMemory (addr_t ptr) 2199 { 2200 Error error; 2201 #if defined (USE_ALLOCATE_MEMORY_CACHE) 2202 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) 2203 { 2204 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr); 2205 } 2206 #else 2207 error = DoDeallocateMemory (ptr); 2208 2209 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2210 if (log) 2211 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)", 2212 ptr, 2213 error.AsCString("SUCCESS"), 2214 m_mod_id.GetStopID(), 2215 m_mod_id.GetMemoryID()); 2216 #endif 2217 return error; 2218 } 2219 2220 ModuleSP 2221 Process::ReadModuleFromMemory (const FileSpec& file_spec, 2222 lldb::addr_t header_addr, 2223 bool add_image_to_target, 2224 bool load_sections_in_target) 2225 { 2226 ModuleSP module_sp (new Module (file_spec, ArchSpec())); 2227 if (module_sp) 2228 { 2229 Error error; 2230 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error); 2231 if (objfile) 2232 { 2233 if (add_image_to_target) 2234 { 2235 m_target.GetImages().Append(module_sp); 2236 if (load_sections_in_target) 2237 { 2238 bool changed = false; 2239 module_sp->SetLoadAddress (m_target, 0, changed); 2240 } 2241 } 2242 return module_sp; 2243 } 2244 } 2245 return ModuleSP(); 2246 } 2247 2248 Error 2249 Process::EnableWatchpoint (Watchpoint *watchpoint) 2250 { 2251 Error error; 2252 error.SetErrorString("watchpoints are not supported"); 2253 return error; 2254 } 2255 2256 Error 2257 Process::DisableWatchpoint (Watchpoint *watchpoint) 2258 { 2259 Error error; 2260 error.SetErrorString("watchpoints are not supported"); 2261 return error; 2262 } 2263 2264 StateType 2265 Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp) 2266 { 2267 StateType state; 2268 // Now wait for the process to launch and return control to us, and then 2269 // call DidLaunch: 2270 while (1) 2271 { 2272 event_sp.reset(); 2273 state = WaitForStateChangedEventsPrivate (timeout, event_sp); 2274 2275 if (StateIsStoppedState(state, false)) 2276 break; 2277 2278 // If state is invalid, then we timed out 2279 if (state == eStateInvalid) 2280 break; 2281 2282 if (event_sp) 2283 HandlePrivateEvent (event_sp); 2284 } 2285 return state; 2286 } 2287 2288 Error 2289 Process::Launch (const ProcessLaunchInfo &launch_info) 2290 { 2291 Error error; 2292 m_abi_sp.reset(); 2293 m_dyld_ap.reset(); 2294 m_os_ap.reset(); 2295 m_process_input_reader.reset(); 2296 2297 Module *exe_module = m_target.GetExecutableModulePointer(); 2298 if (exe_module) 2299 { 2300 char local_exec_file_path[PATH_MAX]; 2301 char platform_exec_file_path[PATH_MAX]; 2302 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path)); 2303 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path)); 2304 if (exe_module->GetFileSpec().Exists()) 2305 { 2306 if (PrivateStateThreadIsValid ()) 2307 PausePrivateStateThread (); 2308 2309 error = WillLaunch (exe_module); 2310 if (error.Success()) 2311 { 2312 SetPublicState (eStateLaunching); 2313 m_should_detach = false; 2314 2315 // Now launch using these arguments. 2316 error = DoLaunch (exe_module, launch_info); 2317 2318 if (error.Fail()) 2319 { 2320 if (GetID() != LLDB_INVALID_PROCESS_ID) 2321 { 2322 SetID (LLDB_INVALID_PROCESS_ID); 2323 const char *error_string = error.AsCString(); 2324 if (error_string == NULL) 2325 error_string = "launch failed"; 2326 SetExitStatus (-1, error_string); 2327 } 2328 } 2329 else 2330 { 2331 EventSP event_sp; 2332 TimeValue timeout_time; 2333 timeout_time = TimeValue::Now(); 2334 timeout_time.OffsetWithSeconds(10); 2335 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp); 2336 2337 if (state == eStateInvalid || event_sp.get() == NULL) 2338 { 2339 // We were able to launch the process, but we failed to 2340 // catch the initial stop. 2341 SetExitStatus (0, "failed to catch stop after launch"); 2342 Destroy(); 2343 } 2344 else if (state == eStateStopped || state == eStateCrashed) 2345 { 2346 2347 DidLaunch (); 2348 2349 DynamicLoader *dyld = GetDynamicLoader (); 2350 if (dyld) 2351 dyld->DidLaunch(); 2352 2353 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2354 // This delays passing the stopped event to listeners till DidLaunch gets 2355 // a chance to complete... 2356 HandlePrivateEvent (event_sp); 2357 2358 if (PrivateStateThreadIsValid ()) 2359 ResumePrivateStateThread (); 2360 else 2361 StartPrivateStateThread (); 2362 } 2363 else if (state == eStateExited) 2364 { 2365 // We exited while trying to launch somehow. Don't call DidLaunch as that's 2366 // not likely to work, and return an invalid pid. 2367 HandlePrivateEvent (event_sp); 2368 } 2369 } 2370 } 2371 } 2372 else 2373 { 2374 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path); 2375 } 2376 } 2377 return error; 2378 } 2379 2380 2381 Error 2382 Process::LoadCore () 2383 { 2384 Error error = DoLoadCore(); 2385 if (error.Success()) 2386 { 2387 if (PrivateStateThreadIsValid ()) 2388 ResumePrivateStateThread (); 2389 else 2390 StartPrivateStateThread (); 2391 2392 DynamicLoader *dyld = GetDynamicLoader (); 2393 if (dyld) 2394 dyld->DidAttach(); 2395 2396 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2397 // We successfully loaded a core file, now pretend we stopped so we can 2398 // show all of the threads in the core file and explore the crashed 2399 // state. 2400 SetPrivateState (eStateStopped); 2401 2402 } 2403 return error; 2404 } 2405 2406 DynamicLoader * 2407 Process::GetDynamicLoader () 2408 { 2409 if (m_dyld_ap.get() == NULL) 2410 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 2411 return m_dyld_ap.get(); 2412 } 2413 2414 2415 Process::NextEventAction::EventActionResult 2416 Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp) 2417 { 2418 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get()); 2419 switch (state) 2420 { 2421 case eStateRunning: 2422 case eStateConnected: 2423 return eEventActionRetry; 2424 2425 case eStateStopped: 2426 case eStateCrashed: 2427 { 2428 // During attach, prior to sending the eStateStopped event, 2429 // lldb_private::Process subclasses must set the process must set 2430 // the new process ID. 2431 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID); 2432 if (m_exec_count > 0) 2433 { 2434 --m_exec_count; 2435 m_process->Resume(); 2436 return eEventActionRetry; 2437 } 2438 else 2439 { 2440 m_process->CompleteAttach (); 2441 return eEventActionSuccess; 2442 } 2443 } 2444 break; 2445 2446 default: 2447 case eStateExited: 2448 case eStateInvalid: 2449 break; 2450 } 2451 2452 m_exit_string.assign ("No valid Process"); 2453 return eEventActionExit; 2454 } 2455 2456 Process::NextEventAction::EventActionResult 2457 Process::AttachCompletionHandler::HandleBeingInterrupted() 2458 { 2459 return eEventActionSuccess; 2460 } 2461 2462 const char * 2463 Process::AttachCompletionHandler::GetExitString () 2464 { 2465 return m_exit_string.c_str(); 2466 } 2467 2468 Error 2469 Process::Attach (ProcessAttachInfo &attach_info) 2470 { 2471 m_abi_sp.reset(); 2472 m_process_input_reader.reset(); 2473 m_dyld_ap.reset(); 2474 m_os_ap.reset(); 2475 2476 lldb::pid_t attach_pid = attach_info.GetProcessID(); 2477 Error error; 2478 if (attach_pid == LLDB_INVALID_PROCESS_ID) 2479 { 2480 char process_name[PATH_MAX]; 2481 2482 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name))) 2483 { 2484 const bool wait_for_launch = attach_info.GetWaitForLaunch(); 2485 2486 if (wait_for_launch) 2487 { 2488 error = WillAttachToProcessWithName(process_name, wait_for_launch); 2489 if (error.Success()) 2490 { 2491 m_should_detach = true; 2492 2493 SetPublicState (eStateAttaching); 2494 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info); 2495 if (error.Fail()) 2496 { 2497 if (GetID() != LLDB_INVALID_PROCESS_ID) 2498 { 2499 SetID (LLDB_INVALID_PROCESS_ID); 2500 if (error.AsCString() == NULL) 2501 error.SetErrorString("attach failed"); 2502 2503 SetExitStatus(-1, error.AsCString()); 2504 } 2505 } 2506 else 2507 { 2508 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 2509 StartPrivateStateThread(); 2510 } 2511 return error; 2512 } 2513 } 2514 else 2515 { 2516 ProcessInstanceInfoList process_infos; 2517 PlatformSP platform_sp (m_target.GetPlatform ()); 2518 2519 if (platform_sp) 2520 { 2521 ProcessInstanceInfoMatch match_info; 2522 match_info.GetProcessInfo() = attach_info; 2523 match_info.SetNameMatchType (eNameMatchEquals); 2524 platform_sp->FindProcesses (match_info, process_infos); 2525 const uint32_t num_matches = process_infos.GetSize(); 2526 if (num_matches == 1) 2527 { 2528 attach_pid = process_infos.GetProcessIDAtIndex(0); 2529 // Fall through and attach using the above process ID 2530 } 2531 else 2532 { 2533 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name)); 2534 if (num_matches > 1) 2535 error.SetErrorStringWithFormat ("more than one process named %s", process_name); 2536 else 2537 error.SetErrorStringWithFormat ("could not find a process named %s", process_name); 2538 } 2539 } 2540 else 2541 { 2542 error.SetErrorString ("invalid platform, can't find processes by name"); 2543 return error; 2544 } 2545 } 2546 } 2547 else 2548 { 2549 error.SetErrorString ("invalid process name"); 2550 } 2551 } 2552 2553 if (attach_pid != LLDB_INVALID_PROCESS_ID) 2554 { 2555 error = WillAttachToProcessWithID(attach_pid); 2556 if (error.Success()) 2557 { 2558 m_should_detach = true; 2559 SetPublicState (eStateAttaching); 2560 2561 error = DoAttachToProcessWithID (attach_pid, attach_info); 2562 if (error.Success()) 2563 { 2564 2565 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount())); 2566 StartPrivateStateThread(); 2567 } 2568 else 2569 { 2570 if (GetID() != LLDB_INVALID_PROCESS_ID) 2571 { 2572 SetID (LLDB_INVALID_PROCESS_ID); 2573 const char *error_string = error.AsCString(); 2574 if (error_string == NULL) 2575 error_string = "attach failed"; 2576 2577 SetExitStatus(-1, error_string); 2578 } 2579 } 2580 } 2581 } 2582 return error; 2583 } 2584 2585 //Error 2586 //Process::Attach (const char *process_name, bool wait_for_launch) 2587 //{ 2588 // m_abi_sp.reset(); 2589 // m_process_input_reader.reset(); 2590 // 2591 // // Find the process and its architecture. Make sure it matches the architecture 2592 // // of the current Target, and if not adjust it. 2593 // Error error; 2594 // 2595 // if (!wait_for_launch) 2596 // { 2597 // ProcessInstanceInfoList process_infos; 2598 // PlatformSP platform_sp (m_target.GetPlatform ()); 2599 // assert (platform_sp.get()); 2600 // 2601 // if (platform_sp) 2602 // { 2603 // ProcessInstanceInfoMatch match_info; 2604 // match_info.GetProcessInfo().SetName(process_name); 2605 // match_info.SetNameMatchType (eNameMatchEquals); 2606 // platform_sp->FindProcesses (match_info, process_infos); 2607 // if (process_infos.GetSize() > 1) 2608 // { 2609 // error.SetErrorStringWithFormat ("more than one process named %s", process_name); 2610 // } 2611 // else if (process_infos.GetSize() == 0) 2612 // { 2613 // error.SetErrorStringWithFormat ("could not find a process named %s", process_name); 2614 // } 2615 // } 2616 // else 2617 // { 2618 // error.SetErrorString ("invalid platform"); 2619 // } 2620 // } 2621 // 2622 // if (error.Success()) 2623 // { 2624 // m_dyld_ap.reset(); 2625 // m_os_ap.reset(); 2626 // 2627 // error = WillAttachToProcessWithName(process_name, wait_for_launch); 2628 // if (error.Success()) 2629 // { 2630 // SetPublicState (eStateAttaching); 2631 // error = DoAttachToProcessWithName (process_name, wait_for_launch); 2632 // if (error.Fail()) 2633 // { 2634 // if (GetID() != LLDB_INVALID_PROCESS_ID) 2635 // { 2636 // SetID (LLDB_INVALID_PROCESS_ID); 2637 // const char *error_string = error.AsCString(); 2638 // if (error_string == NULL) 2639 // error_string = "attach failed"; 2640 // 2641 // SetExitStatus(-1, error_string); 2642 // } 2643 // } 2644 // else 2645 // { 2646 // SetNextEventAction(new Process::AttachCompletionHandler(this, 0)); 2647 // StartPrivateStateThread(); 2648 // } 2649 // } 2650 // } 2651 // return error; 2652 //} 2653 2654 void 2655 Process::CompleteAttach () 2656 { 2657 // Let the process subclass figure out at much as it can about the process 2658 // before we go looking for a dynamic loader plug-in. 2659 DidAttach(); 2660 2661 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't 2662 // the same as the one we've already set, switch architectures. 2663 PlatformSP platform_sp (m_target.GetPlatform ()); 2664 assert (platform_sp.get()); 2665 if (platform_sp) 2666 { 2667 ProcessInstanceInfo process_info; 2668 platform_sp->GetProcessInfo (GetID(), process_info); 2669 const ArchSpec &process_arch = process_info.GetArchitecture(); 2670 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch) 2671 m_target.SetArchitecture (process_arch); 2672 } 2673 2674 // We have completed the attach, now it is time to find the dynamic loader 2675 // plug-in 2676 DynamicLoader *dyld = GetDynamicLoader (); 2677 if (dyld) 2678 dyld->DidAttach(); 2679 2680 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL)); 2681 // Figure out which one is the executable, and set that in our target: 2682 ModuleList &modules = m_target.GetImages(); 2683 2684 size_t num_modules = modules.GetSize(); 2685 for (int i = 0; i < num_modules; i++) 2686 { 2687 ModuleSP module_sp (modules.GetModuleAtIndex(i)); 2688 if (module_sp && module_sp->IsExecutable()) 2689 { 2690 if (m_target.GetExecutableModulePointer() != module_sp.get()) 2691 m_target.SetExecutableModule (module_sp, false); 2692 break; 2693 } 2694 } 2695 } 2696 2697 Error 2698 Process::ConnectRemote (const char *remote_url) 2699 { 2700 m_abi_sp.reset(); 2701 m_process_input_reader.reset(); 2702 2703 // Find the process and its architecture. Make sure it matches the architecture 2704 // of the current Target, and if not adjust it. 2705 2706 Error error (DoConnectRemote (remote_url)); 2707 if (error.Success()) 2708 { 2709 if (GetID() != LLDB_INVALID_PROCESS_ID) 2710 { 2711 EventSP event_sp; 2712 StateType state = WaitForProcessStopPrivate(NULL, event_sp); 2713 2714 if (state == eStateStopped || state == eStateCrashed) 2715 { 2716 // If we attached and actually have a process on the other end, then 2717 // this ended up being the equivalent of an attach. 2718 CompleteAttach (); 2719 2720 // This delays passing the stopped event to listeners till 2721 // CompleteAttach gets a chance to complete... 2722 HandlePrivateEvent (event_sp); 2723 2724 } 2725 } 2726 2727 if (PrivateStateThreadIsValid ()) 2728 ResumePrivateStateThread (); 2729 else 2730 StartPrivateStateThread (); 2731 } 2732 return error; 2733 } 2734 2735 2736 Error 2737 Process::Resume () 2738 { 2739 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2740 if (log) 2741 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s", 2742 m_mod_id.GetStopID(), 2743 StateAsCString(m_public_state.GetValue()), 2744 StateAsCString(m_private_state.GetValue())); 2745 2746 Error error (WillResume()); 2747 // Tell the process it is about to resume before the thread list 2748 if (error.Success()) 2749 { 2750 // Now let the thread list know we are about to resume so it 2751 // can let all of our threads know that they are about to be 2752 // resumed. Threads will each be called with 2753 // Thread::WillResume(StateType) where StateType contains the state 2754 // that they are supposed to have when the process is resumed 2755 // (suspended/running/stepping). Threads should also check 2756 // their resume signal in lldb::Thread::GetResumeSignal() 2757 // to see if they are suppoed to start back up with a signal. 2758 if (m_thread_list.WillResume()) 2759 { 2760 m_mod_id.BumpResumeID(); 2761 error = DoResume(); 2762 if (error.Success()) 2763 { 2764 DidResume(); 2765 m_thread_list.DidResume(); 2766 if (log) 2767 log->Printf ("Process thinks the process has resumed."); 2768 } 2769 } 2770 else 2771 { 2772 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume"); 2773 } 2774 } 2775 else if (log) 2776 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>")); 2777 return error; 2778 } 2779 2780 Error 2781 Process::Halt () 2782 { 2783 // Pause our private state thread so we can ensure no one else eats 2784 // the stop event out from under us. 2785 Listener halt_listener ("lldb.process.halt_listener"); 2786 HijackPrivateProcessEvents(&halt_listener); 2787 2788 EventSP event_sp; 2789 Error error (WillHalt()); 2790 2791 if (error.Success()) 2792 { 2793 2794 bool caused_stop = false; 2795 2796 // Ask the process subclass to actually halt our process 2797 error = DoHalt(caused_stop); 2798 if (error.Success()) 2799 { 2800 if (m_public_state.GetValue() == eStateAttaching) 2801 { 2802 SetExitStatus(SIGKILL, "Cancelled async attach."); 2803 Destroy (); 2804 } 2805 else 2806 { 2807 // If "caused_stop" is true, then DoHalt stopped the process. If 2808 // "caused_stop" is false, the process was already stopped. 2809 // If the DoHalt caused the process to stop, then we want to catch 2810 // this event and set the interrupted bool to true before we pass 2811 // this along so clients know that the process was interrupted by 2812 // a halt command. 2813 if (caused_stop) 2814 { 2815 // Wait for 1 second for the process to stop. 2816 TimeValue timeout_time; 2817 timeout_time = TimeValue::Now(); 2818 timeout_time.OffsetWithSeconds(1); 2819 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp); 2820 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); 2821 2822 if (!got_event || state == eStateInvalid) 2823 { 2824 // We timeout out and didn't get a stop event... 2825 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState())); 2826 } 2827 else 2828 { 2829 if (StateIsStoppedState (state, false)) 2830 { 2831 // We caused the process to interrupt itself, so mark this 2832 // as such in the stop event so clients can tell an interrupted 2833 // process from a natural stop 2834 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true); 2835 } 2836 else 2837 { 2838 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2839 if (log) 2840 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state)); 2841 error.SetErrorString ("Did not get stopped event after halt."); 2842 } 2843 } 2844 } 2845 DidHalt(); 2846 } 2847 } 2848 } 2849 // Resume our private state thread before we post the event (if any) 2850 RestorePrivateProcessEvents(); 2851 2852 // Post any event we might have consumed. If all goes well, we will have 2853 // stopped the process, intercepted the event and set the interrupted 2854 // bool in the event. Post it to the private event queue and that will end up 2855 // correctly setting the state. 2856 if (event_sp) 2857 m_private_state_broadcaster.BroadcastEvent(event_sp); 2858 2859 return error; 2860 } 2861 2862 Error 2863 Process::Detach () 2864 { 2865 Error error (WillDetach()); 2866 2867 if (error.Success()) 2868 { 2869 DisableAllBreakpointSites(); 2870 error = DoDetach(); 2871 if (error.Success()) 2872 { 2873 DidDetach(); 2874 StopPrivateStateThread(); 2875 } 2876 } 2877 return error; 2878 } 2879 2880 Error 2881 Process::Destroy () 2882 { 2883 Error error (WillDestroy()); 2884 if (error.Success()) 2885 { 2886 DisableAllBreakpointSites(); 2887 error = DoDestroy(); 2888 if (error.Success()) 2889 { 2890 DidDestroy(); 2891 StopPrivateStateThread(); 2892 } 2893 m_stdio_communication.StopReadThread(); 2894 m_stdio_communication.Disconnect(); 2895 if (m_process_input_reader && m_process_input_reader->IsActive()) 2896 m_target.GetDebugger().PopInputReader (m_process_input_reader); 2897 if (m_process_input_reader) 2898 m_process_input_reader.reset(); 2899 } 2900 return error; 2901 } 2902 2903 Error 2904 Process::Signal (int signal) 2905 { 2906 Error error (WillSignal()); 2907 if (error.Success()) 2908 { 2909 error = DoSignal(signal); 2910 if (error.Success()) 2911 DidSignal(); 2912 } 2913 return error; 2914 } 2915 2916 lldb::ByteOrder 2917 Process::GetByteOrder () const 2918 { 2919 return m_target.GetArchitecture().GetByteOrder(); 2920 } 2921 2922 uint32_t 2923 Process::GetAddressByteSize () const 2924 { 2925 return m_target.GetArchitecture().GetAddressByteSize(); 2926 } 2927 2928 2929 bool 2930 Process::ShouldBroadcastEvent (Event *event_ptr) 2931 { 2932 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr); 2933 bool return_value = true; 2934 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 2935 2936 switch (state) 2937 { 2938 case eStateConnected: 2939 case eStateAttaching: 2940 case eStateLaunching: 2941 case eStateDetached: 2942 case eStateExited: 2943 case eStateUnloaded: 2944 // These events indicate changes in the state of the debugging session, always report them. 2945 return_value = true; 2946 break; 2947 case eStateInvalid: 2948 // We stopped for no apparent reason, don't report it. 2949 return_value = false; 2950 break; 2951 case eStateRunning: 2952 case eStateStepping: 2953 // If we've started the target running, we handle the cases where we 2954 // are already running and where there is a transition from stopped to 2955 // running differently. 2956 // running -> running: Automatically suppress extra running events 2957 // stopped -> running: Report except when there is one or more no votes 2958 // and no yes votes. 2959 SynchronouslyNotifyStateChanged (state); 2960 switch (m_public_state.GetValue()) 2961 { 2962 case eStateRunning: 2963 case eStateStepping: 2964 // We always suppress multiple runnings with no PUBLIC stop in between. 2965 return_value = false; 2966 break; 2967 default: 2968 // TODO: make this work correctly. For now always report 2969 // run if we aren't running so we don't miss any runnning 2970 // events. If I run the lldb/test/thread/a.out file and 2971 // break at main.cpp:58, run and hit the breakpoints on 2972 // multiple threads, then somehow during the stepping over 2973 // of all breakpoints no run gets reported. 2974 return_value = true; 2975 2976 // This is a transition from stop to run. 2977 switch (m_thread_list.ShouldReportRun (event_ptr)) 2978 { 2979 case eVoteYes: 2980 case eVoteNoOpinion: 2981 return_value = true; 2982 break; 2983 case eVoteNo: 2984 return_value = false; 2985 break; 2986 } 2987 break; 2988 } 2989 break; 2990 case eStateStopped: 2991 case eStateCrashed: 2992 case eStateSuspended: 2993 { 2994 // We've stopped. First see if we're going to restart the target. 2995 // If we are going to stop, then we always broadcast the event. 2996 // If we aren't going to stop, let the thread plans decide if we're going to report this event. 2997 // If no thread has an opinion, we don't report it. 2998 if (ProcessEventData::GetInterruptedFromEvent (event_ptr)) 2999 { 3000 if (log) 3001 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state)); 3002 return true; 3003 } 3004 else 3005 { 3006 RefreshStateAfterStop (); 3007 3008 if (m_thread_list.ShouldStop (event_ptr) == false) 3009 { 3010 switch (m_thread_list.ShouldReportStop (event_ptr)) 3011 { 3012 case eVoteYes: 3013 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true); 3014 // Intentional fall-through here. 3015 case eVoteNoOpinion: 3016 case eVoteNo: 3017 return_value = false; 3018 break; 3019 } 3020 3021 if (log) 3022 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state)); 3023 Resume (); 3024 } 3025 else 3026 { 3027 return_value = true; 3028 SynchronouslyNotifyStateChanged (state); 3029 } 3030 } 3031 } 3032 } 3033 3034 if (log) 3035 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO"); 3036 return return_value; 3037 } 3038 3039 3040 bool 3041 Process::StartPrivateStateThread () 3042 { 3043 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3044 3045 bool already_running = PrivateStateThreadIsValid (); 3046 if (log) 3047 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread"); 3048 3049 if (already_running) 3050 return true; 3051 3052 // Create a thread that watches our internal state and controls which 3053 // events make it to clients (into the DCProcess event queue). 3054 char thread_name[1024]; 3055 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID()); 3056 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL); 3057 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread); 3058 } 3059 3060 void 3061 Process::PausePrivateStateThread () 3062 { 3063 ControlPrivateStateThread (eBroadcastInternalStateControlPause); 3064 } 3065 3066 void 3067 Process::ResumePrivateStateThread () 3068 { 3069 ControlPrivateStateThread (eBroadcastInternalStateControlResume); 3070 } 3071 3072 void 3073 Process::StopPrivateStateThread () 3074 { 3075 if (PrivateStateThreadIsValid ()) 3076 ControlPrivateStateThread (eBroadcastInternalStateControlStop); 3077 } 3078 3079 void 3080 Process::ControlPrivateStateThread (uint32_t signal) 3081 { 3082 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS)); 3083 3084 assert (signal == eBroadcastInternalStateControlStop || 3085 signal == eBroadcastInternalStateControlPause || 3086 signal == eBroadcastInternalStateControlResume); 3087 3088 if (log) 3089 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal); 3090 3091 // Signal the private state thread. First we should copy this is case the 3092 // thread starts exiting since the private state thread will NULL this out 3093 // when it exits 3094 const lldb::thread_t private_state_thread = m_private_state_thread; 3095 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread)) 3096 { 3097 TimeValue timeout_time; 3098 bool timed_out; 3099 3100 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL); 3101 3102 timeout_time = TimeValue::Now(); 3103 timeout_time.OffsetWithSeconds(2); 3104 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out); 3105 m_private_state_control_wait.SetValue (false, eBroadcastNever); 3106 3107 if (signal == eBroadcastInternalStateControlStop) 3108 { 3109 if (timed_out) 3110 Host::ThreadCancel (private_state_thread, NULL); 3111 3112 thread_result_t result = NULL; 3113 Host::ThreadJoin (private_state_thread, &result, NULL); 3114 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 3115 } 3116 } 3117 } 3118 3119 void 3120 Process::HandlePrivateEvent (EventSP &event_sp) 3121 { 3122 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3123 3124 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3125 3126 // First check to see if anybody wants a shot at this event: 3127 if (m_next_event_action_ap.get() != NULL) 3128 { 3129 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp); 3130 switch (action_result) 3131 { 3132 case NextEventAction::eEventActionSuccess: 3133 SetNextEventAction(NULL); 3134 break; 3135 3136 case NextEventAction::eEventActionRetry: 3137 break; 3138 3139 case NextEventAction::eEventActionExit: 3140 // Handle Exiting Here. If we already got an exited event, 3141 // we should just propagate it. Otherwise, swallow this event, 3142 // and set our state to exit so the next event will kill us. 3143 if (new_state != eStateExited) 3144 { 3145 // FIXME: should cons up an exited event, and discard this one. 3146 SetExitStatus(0, m_next_event_action_ap->GetExitString()); 3147 SetNextEventAction(NULL); 3148 return; 3149 } 3150 SetNextEventAction(NULL); 3151 break; 3152 } 3153 } 3154 3155 // See if we should broadcast this state to external clients? 3156 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get()); 3157 3158 if (should_broadcast) 3159 { 3160 if (log) 3161 { 3162 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s", 3163 __FUNCTION__, 3164 GetID(), 3165 StateAsCString(new_state), 3166 StateAsCString (GetState ()), 3167 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public"); 3168 } 3169 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get()); 3170 if (StateIsRunningState (new_state)) 3171 PushProcessInputReader (); 3172 else 3173 PopProcessInputReader (); 3174 3175 BroadcastEvent (event_sp); 3176 } 3177 else 3178 { 3179 if (log) 3180 { 3181 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false", 3182 __FUNCTION__, 3183 GetID(), 3184 StateAsCString(new_state), 3185 StateAsCString (GetState ())); 3186 } 3187 } 3188 } 3189 3190 void * 3191 Process::PrivateStateThread (void *arg) 3192 { 3193 Process *proc = static_cast<Process*> (arg); 3194 void *result = proc->RunPrivateStateThread (); 3195 return result; 3196 } 3197 3198 void * 3199 Process::RunPrivateStateThread () 3200 { 3201 bool control_only = false; 3202 m_private_state_control_wait.SetValue (false, eBroadcastNever); 3203 3204 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3205 if (log) 3206 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID()); 3207 3208 bool exit_now = false; 3209 while (!exit_now) 3210 { 3211 EventSP event_sp; 3212 WaitForEventsPrivate (NULL, event_sp, control_only); 3213 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) 3214 { 3215 switch (event_sp->GetType()) 3216 { 3217 case eBroadcastInternalStateControlStop: 3218 exit_now = true; 3219 continue; // Go to next loop iteration so we exit without 3220 break; // doing any internal state managment below 3221 3222 case eBroadcastInternalStateControlPause: 3223 control_only = true; 3224 break; 3225 3226 case eBroadcastInternalStateControlResume: 3227 control_only = false; 3228 break; 3229 } 3230 3231 if (log) 3232 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType()); 3233 3234 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 3235 continue; 3236 } 3237 3238 3239 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3240 3241 if (internal_state != eStateInvalid) 3242 { 3243 HandlePrivateEvent (event_sp); 3244 } 3245 3246 if (internal_state == eStateInvalid || 3247 internal_state == eStateExited || 3248 internal_state == eStateDetached ) 3249 { 3250 if (log) 3251 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state)); 3252 3253 break; 3254 } 3255 } 3256 3257 // Verify log is still enabled before attempting to write to it... 3258 if (log) 3259 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID()); 3260 3261 m_private_state_control_wait.SetValue (true, eBroadcastAlways); 3262 m_private_state_thread = LLDB_INVALID_HOST_THREAD; 3263 return NULL; 3264 } 3265 3266 //------------------------------------------------------------------ 3267 // Process Event Data 3268 //------------------------------------------------------------------ 3269 3270 Process::ProcessEventData::ProcessEventData () : 3271 EventData (), 3272 m_process_sp (), 3273 m_state (eStateInvalid), 3274 m_restarted (false), 3275 m_update_state (0), 3276 m_interrupted (false) 3277 { 3278 } 3279 3280 Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) : 3281 EventData (), 3282 m_process_sp (process_sp), 3283 m_state (state), 3284 m_restarted (false), 3285 m_update_state (0), 3286 m_interrupted (false) 3287 { 3288 } 3289 3290 Process::ProcessEventData::~ProcessEventData() 3291 { 3292 } 3293 3294 const ConstString & 3295 Process::ProcessEventData::GetFlavorString () 3296 { 3297 static ConstString g_flavor ("Process::ProcessEventData"); 3298 return g_flavor; 3299 } 3300 3301 const ConstString & 3302 Process::ProcessEventData::GetFlavor () const 3303 { 3304 return ProcessEventData::GetFlavorString (); 3305 } 3306 3307 void 3308 Process::ProcessEventData::DoOnRemoval (Event *event_ptr) 3309 { 3310 // This function gets called twice for each event, once when the event gets pulled 3311 // off of the private process event queue, and then any number of times, first when it gets pulled off of 3312 // the public event queue, then other times when we're pretending that this is where we stopped at the 3313 // end of expression evaluation. m_update_state is used to distinguish these 3314 // three cases; it is 0 when we're just pulling it off for private handling, 3315 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then. 3316 3317 if (m_update_state != 1) 3318 return; 3319 3320 m_process_sp->SetPublicState (m_state); 3321 3322 // If we're stopped and haven't restarted, then do the breakpoint commands here: 3323 if (m_state == eStateStopped && ! m_restarted) 3324 { 3325 ThreadList &curr_thread_list = m_process_sp->GetThreadList(); 3326 uint32_t num_threads = curr_thread_list.GetSize(); 3327 uint32_t idx; 3328 3329 // The actions might change one of the thread's stop_info's opinions about whether we should 3330 // stop the process, so we need to query that as we go. 3331 3332 // One other complication here, is that we try to catch any case where the target has run (except for expressions) 3333 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and 3334 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like 3335 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back 3336 // against this list & bag out if anything differs. 3337 std::vector<uint32_t> thread_index_array(num_threads); 3338 for (idx = 0; idx < num_threads; ++idx) 3339 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID(); 3340 3341 bool still_should_stop = true; 3342 3343 for (idx = 0; idx < num_threads; ++idx) 3344 { 3345 curr_thread_list = m_process_sp->GetThreadList(); 3346 if (curr_thread_list.GetSize() != num_threads) 3347 { 3348 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 3349 if (log) 3350 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize()); 3351 break; 3352 } 3353 3354 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx); 3355 3356 if (thread_sp->GetIndexID() != thread_index_array[idx]) 3357 { 3358 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 3359 if (log) 3360 log->Printf("The thread at position %u changed from %u to %u while processing event.", 3361 idx, 3362 thread_index_array[idx], 3363 thread_sp->GetIndexID()); 3364 break; 3365 } 3366 3367 StopInfoSP stop_info_sp = thread_sp->GetStopInfo (); 3368 if (stop_info_sp) 3369 { 3370 stop_info_sp->PerformAction(event_ptr); 3371 // The stop action might restart the target. If it does, then we want to mark that in the 3372 // event so that whoever is receiving it will know to wait for the running event and reflect 3373 // that state appropriately. 3374 // We also need to stop processing actions, since they aren't expecting the target to be running. 3375 3376 // FIXME: we might have run. 3377 if (stop_info_sp->HasTargetRunSinceMe()) 3378 { 3379 SetRestarted (true); 3380 break; 3381 } 3382 else if (!stop_info_sp->ShouldStop(event_ptr)) 3383 { 3384 still_should_stop = false; 3385 } 3386 } 3387 } 3388 3389 3390 if (m_process_sp->GetPrivateState() != eStateRunning) 3391 { 3392 if (!still_should_stop) 3393 { 3394 // We've been asked to continue, so do that here. 3395 SetRestarted(true); 3396 m_process_sp->Resume(); 3397 } 3398 else 3399 { 3400 // If we didn't restart, run the Stop Hooks here: 3401 // They might also restart the target, so watch for that. 3402 m_process_sp->GetTarget().RunStopHooks(); 3403 if (m_process_sp->GetPrivateState() == eStateRunning) 3404 SetRestarted(true); 3405 } 3406 } 3407 3408 } 3409 } 3410 3411 void 3412 Process::ProcessEventData::Dump (Stream *s) const 3413 { 3414 if (m_process_sp) 3415 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID()); 3416 3417 s->Printf("state = %s", StateAsCString(GetState())); 3418 } 3419 3420 const Process::ProcessEventData * 3421 Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr) 3422 { 3423 if (event_ptr) 3424 { 3425 const EventData *event_data = event_ptr->GetData(); 3426 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString()) 3427 return static_cast <const ProcessEventData *> (event_ptr->GetData()); 3428 } 3429 return NULL; 3430 } 3431 3432 ProcessSP 3433 Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr) 3434 { 3435 ProcessSP process_sp; 3436 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3437 if (data) 3438 process_sp = data->GetProcessSP(); 3439 return process_sp; 3440 } 3441 3442 StateType 3443 Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr) 3444 { 3445 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3446 if (data == NULL) 3447 return eStateInvalid; 3448 else 3449 return data->GetState(); 3450 } 3451 3452 bool 3453 Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr) 3454 { 3455 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3456 if (data == NULL) 3457 return false; 3458 else 3459 return data->GetRestarted(); 3460 } 3461 3462 void 3463 Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value) 3464 { 3465 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 3466 if (data != NULL) 3467 data->SetRestarted(new_value); 3468 } 3469 3470 bool 3471 Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr) 3472 { 3473 const ProcessEventData *data = GetEventDataFromEvent (event_ptr); 3474 if (data == NULL) 3475 return false; 3476 else 3477 return data->GetInterrupted (); 3478 } 3479 3480 void 3481 Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value) 3482 { 3483 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 3484 if (data != NULL) 3485 data->SetInterrupted(new_value); 3486 } 3487 3488 bool 3489 Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr) 3490 { 3491 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr)); 3492 if (data) 3493 { 3494 data->SetUpdateStateOnRemoval(); 3495 return true; 3496 } 3497 return false; 3498 } 3499 3500 lldb::TargetSP 3501 Process::CalculateTarget () 3502 { 3503 return m_target.shared_from_this(); 3504 } 3505 3506 void 3507 Process::CalculateExecutionContext (ExecutionContext &exe_ctx) 3508 { 3509 exe_ctx.SetTargetPtr (&m_target); 3510 exe_ctx.SetProcessPtr (this); 3511 exe_ctx.SetThreadPtr(NULL); 3512 exe_ctx.SetFramePtr (NULL); 3513 } 3514 3515 //uint32_t 3516 //Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 3517 //{ 3518 // return 0; 3519 //} 3520 // 3521 //ArchSpec 3522 //Process::GetArchSpecForExistingProcess (lldb::pid_t pid) 3523 //{ 3524 // return Host::GetArchSpecForExistingProcess (pid); 3525 //} 3526 // 3527 //ArchSpec 3528 //Process::GetArchSpecForExistingProcess (const char *process_name) 3529 //{ 3530 // return Host::GetArchSpecForExistingProcess (process_name); 3531 //} 3532 // 3533 void 3534 Process::AppendSTDOUT (const char * s, size_t len) 3535 { 3536 Mutex::Locker locker (m_stdio_communication_mutex); 3537 m_stdout_data.append (s, len); 3538 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState())); 3539 } 3540 3541 void 3542 Process::AppendSTDERR (const char * s, size_t len) 3543 { 3544 Mutex::Locker locker (m_stdio_communication_mutex); 3545 m_stderr_data.append (s, len); 3546 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState())); 3547 } 3548 3549 //------------------------------------------------------------------ 3550 // Process STDIO 3551 //------------------------------------------------------------------ 3552 3553 size_t 3554 Process::GetSTDOUT (char *buf, size_t buf_size, Error &error) 3555 { 3556 Mutex::Locker locker(m_stdio_communication_mutex); 3557 size_t bytes_available = m_stdout_data.size(); 3558 if (bytes_available > 0) 3559 { 3560 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3561 if (log) 3562 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size); 3563 if (bytes_available > buf_size) 3564 { 3565 memcpy(buf, m_stdout_data.c_str(), buf_size); 3566 m_stdout_data.erase(0, buf_size); 3567 bytes_available = buf_size; 3568 } 3569 else 3570 { 3571 memcpy(buf, m_stdout_data.c_str(), bytes_available); 3572 m_stdout_data.clear(); 3573 } 3574 } 3575 return bytes_available; 3576 } 3577 3578 3579 size_t 3580 Process::GetSTDERR (char *buf, size_t buf_size, Error &error) 3581 { 3582 Mutex::Locker locker(m_stdio_communication_mutex); 3583 size_t bytes_available = m_stderr_data.size(); 3584 if (bytes_available > 0) 3585 { 3586 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3587 if (log) 3588 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size); 3589 if (bytes_available > buf_size) 3590 { 3591 memcpy(buf, m_stderr_data.c_str(), buf_size); 3592 m_stderr_data.erase(0, buf_size); 3593 bytes_available = buf_size; 3594 } 3595 else 3596 { 3597 memcpy(buf, m_stderr_data.c_str(), bytes_available); 3598 m_stderr_data.clear(); 3599 } 3600 } 3601 return bytes_available; 3602 } 3603 3604 void 3605 Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len) 3606 { 3607 Process *process = (Process *) baton; 3608 process->AppendSTDOUT (static_cast<const char *>(src), src_len); 3609 } 3610 3611 size_t 3612 Process::ProcessInputReaderCallback (void *baton, 3613 InputReader &reader, 3614 lldb::InputReaderAction notification, 3615 const char *bytes, 3616 size_t bytes_len) 3617 { 3618 Process *process = (Process *) baton; 3619 3620 switch (notification) 3621 { 3622 case eInputReaderActivate: 3623 break; 3624 3625 case eInputReaderDeactivate: 3626 break; 3627 3628 case eInputReaderReactivate: 3629 break; 3630 3631 case eInputReaderAsynchronousOutputWritten: 3632 break; 3633 3634 case eInputReaderGotToken: 3635 { 3636 Error error; 3637 process->PutSTDIN (bytes, bytes_len, error); 3638 } 3639 break; 3640 3641 case eInputReaderInterrupt: 3642 process->Halt (); 3643 break; 3644 3645 case eInputReaderEndOfFile: 3646 process->AppendSTDOUT ("^D", 2); 3647 break; 3648 3649 case eInputReaderDone: 3650 break; 3651 3652 } 3653 3654 return bytes_len; 3655 } 3656 3657 void 3658 Process::ResetProcessInputReader () 3659 { 3660 m_process_input_reader.reset(); 3661 } 3662 3663 void 3664 Process::SetSTDIOFileDescriptor (int file_descriptor) 3665 { 3666 // First set up the Read Thread for reading/handling process I/O 3667 3668 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true)); 3669 3670 if (conn_ap.get()) 3671 { 3672 m_stdio_communication.SetConnection (conn_ap.release()); 3673 if (m_stdio_communication.IsConnected()) 3674 { 3675 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this); 3676 m_stdio_communication.StartReadThread(); 3677 3678 // Now read thread is set up, set up input reader. 3679 3680 if (!m_process_input_reader.get()) 3681 { 3682 m_process_input_reader.reset (new InputReader(m_target.GetDebugger())); 3683 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback, 3684 this, 3685 eInputReaderGranularityByte, 3686 NULL, 3687 NULL, 3688 false)); 3689 3690 if (err.Fail()) 3691 m_process_input_reader.reset(); 3692 } 3693 } 3694 } 3695 } 3696 3697 void 3698 Process::PushProcessInputReader () 3699 { 3700 if (m_process_input_reader && !m_process_input_reader->IsActive()) 3701 m_target.GetDebugger().PushInputReader (m_process_input_reader); 3702 } 3703 3704 void 3705 Process::PopProcessInputReader () 3706 { 3707 if (m_process_input_reader && m_process_input_reader->IsActive()) 3708 m_target.GetDebugger().PopInputReader (m_process_input_reader); 3709 } 3710 3711 // The process needs to know about installed plug-ins 3712 void 3713 Process::SettingsInitialize () 3714 { 3715 static std::vector<OptionEnumValueElement> g_plugins; 3716 3717 int i=0; 3718 const char *name; 3719 OptionEnumValueElement option_enum; 3720 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL) 3721 { 3722 if (name) 3723 { 3724 option_enum.value = i; 3725 option_enum.string_value = name; 3726 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i); 3727 g_plugins.push_back (option_enum); 3728 } 3729 ++i; 3730 } 3731 option_enum.value = 0; 3732 option_enum.string_value = NULL; 3733 option_enum.usage = NULL; 3734 g_plugins.push_back (option_enum); 3735 3736 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i) 3737 { 3738 if (::strcmp (name, "plugin") == 0) 3739 { 3740 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0]; 3741 break; 3742 } 3743 } 3744 UserSettingsControllerSP &usc = GetSettingsController(); 3745 usc.reset (new SettingsController); 3746 UserSettingsController::InitializeSettingsController (usc, 3747 SettingsController::global_settings_table, 3748 SettingsController::instance_settings_table); 3749 3750 // Now call SettingsInitialize() for each 'child' of Process settings 3751 Thread::SettingsInitialize (); 3752 } 3753 3754 void 3755 Process::SettingsTerminate () 3756 { 3757 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings. 3758 3759 Thread::SettingsTerminate (); 3760 3761 // Now terminate Process Settings. 3762 3763 UserSettingsControllerSP &usc = GetSettingsController(); 3764 UserSettingsController::FinalizeSettingsController (usc); 3765 usc.reset(); 3766 } 3767 3768 UserSettingsControllerSP & 3769 Process::GetSettingsController () 3770 { 3771 static UserSettingsControllerSP g_settings_controller_sp; 3772 if (!g_settings_controller_sp) 3773 { 3774 g_settings_controller_sp.reset (new Process::SettingsController); 3775 // The first shared pointer to Process::SettingsController in 3776 // g_settings_controller_sp must be fully created above so that 3777 // the TargetInstanceSettings can use a weak_ptr to refer back 3778 // to the master setttings controller 3779 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp, 3780 false, 3781 InstanceSettings::GetDefaultName().AsCString())); 3782 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp); 3783 } 3784 return g_settings_controller_sp; 3785 3786 } 3787 3788 void 3789 Process::UpdateInstanceName () 3790 { 3791 Module *module = GetTarget().GetExecutableModulePointer(); 3792 if (module && module->GetFileSpec().GetFilename()) 3793 { 3794 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), 3795 module->GetFileSpec().GetFilename().AsCString()); 3796 } 3797 } 3798 3799 ExecutionResults 3800 Process::RunThreadPlan (ExecutionContext &exe_ctx, 3801 lldb::ThreadPlanSP &thread_plan_sp, 3802 bool stop_others, 3803 bool try_all_threads, 3804 bool discard_on_error, 3805 uint32_t single_thread_timeout_usec, 3806 Stream &errors) 3807 { 3808 ExecutionResults return_value = eExecutionSetupError; 3809 3810 if (thread_plan_sp.get() == NULL) 3811 { 3812 errors.Printf("RunThreadPlan called with empty thread plan."); 3813 return eExecutionSetupError; 3814 } 3815 3816 if (exe_ctx.GetProcessPtr() != this) 3817 { 3818 errors.Printf("RunThreadPlan called on wrong process."); 3819 return eExecutionSetupError; 3820 } 3821 3822 Thread *thread = exe_ctx.GetThreadPtr(); 3823 if (thread == NULL) 3824 { 3825 errors.Printf("RunThreadPlan called with invalid thread."); 3826 return eExecutionSetupError; 3827 } 3828 3829 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes. 3830 // For that to be true the plan can't be private - since private plans suppress themselves in the 3831 // GetCompletedPlan call. 3832 3833 bool orig_plan_private = thread_plan_sp->GetPrivate(); 3834 thread_plan_sp->SetPrivate(false); 3835 3836 if (m_private_state.GetValue() != eStateStopped) 3837 { 3838 errors.Printf ("RunThreadPlan called while the private state was not stopped."); 3839 return eExecutionSetupError; 3840 } 3841 3842 // Save the thread & frame from the exe_ctx for restoration after we run 3843 const uint32_t thread_idx_id = thread->GetIndexID(); 3844 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID(); 3845 3846 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either, 3847 // so we should arrange to reset them as well. 3848 3849 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread(); 3850 3851 uint32_t selected_tid; 3852 StackID selected_stack_id; 3853 if (selected_thread_sp) 3854 { 3855 selected_tid = selected_thread_sp->GetIndexID(); 3856 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID(); 3857 } 3858 else 3859 { 3860 selected_tid = LLDB_INVALID_THREAD_ID; 3861 } 3862 3863 thread->QueueThreadPlan(thread_plan_sp, true); 3864 3865 Listener listener("lldb.process.listener.run-thread-plan"); 3866 3867 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get 3868 // restored on exit to the function. 3869 3870 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener); 3871 3872 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS)); 3873 if (log) 3874 { 3875 StreamString s; 3876 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose); 3877 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".", 3878 thread->GetIndexID(), 3879 thread->GetID(), 3880 s.GetData()); 3881 } 3882 3883 bool got_event; 3884 lldb::EventSP event_sp; 3885 lldb::StateType stop_state = lldb::eStateInvalid; 3886 3887 TimeValue* timeout_ptr = NULL; 3888 TimeValue real_timeout; 3889 3890 bool first_timeout = true; 3891 bool do_resume = true; 3892 3893 while (1) 3894 { 3895 // We usually want to resume the process if we get to the top of the loop. 3896 // The only exception is if we get two running events with no intervening 3897 // stop, which can happen, we will just wait for then next stop event. 3898 3899 if (do_resume) 3900 { 3901 // Do the initial resume and wait for the running event before going further. 3902 3903 Error resume_error = Resume (); 3904 if (!resume_error.Success()) 3905 { 3906 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString()); 3907 return_value = eExecutionSetupError; 3908 break; 3909 } 3910 3911 real_timeout = TimeValue::Now(); 3912 real_timeout.OffsetWithMicroSeconds(500000); 3913 timeout_ptr = &real_timeout; 3914 3915 got_event = listener.WaitForEvent(timeout_ptr, event_sp); 3916 if (!got_event) 3917 { 3918 if (log) 3919 log->PutCString("Didn't get any event after initial resume, exiting."); 3920 3921 errors.Printf("Didn't get any event after initial resume, exiting."); 3922 return_value = eExecutionSetupError; 3923 break; 3924 } 3925 3926 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3927 if (stop_state != eStateRunning) 3928 { 3929 if (log) 3930 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state)); 3931 3932 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state)); 3933 return_value = eExecutionSetupError; 3934 break; 3935 } 3936 3937 if (log) 3938 log->PutCString ("Resuming succeeded."); 3939 // We need to call the function synchronously, so spin waiting for it to return. 3940 // If we get interrupted while executing, we're going to lose our context, and 3941 // won't be able to gather the result at this point. 3942 // We set the timeout AFTER the resume, since the resume takes some time and we 3943 // don't want to charge that to the timeout. 3944 3945 if (single_thread_timeout_usec != 0) 3946 { 3947 real_timeout = TimeValue::Now(); 3948 if (first_timeout) 3949 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec); 3950 else 3951 real_timeout.OffsetWithSeconds(10); 3952 3953 timeout_ptr = &real_timeout; 3954 } 3955 } 3956 else 3957 { 3958 if (log) 3959 log->PutCString ("Handled an extra running event."); 3960 do_resume = true; 3961 } 3962 3963 // Now wait for the process to stop again: 3964 stop_state = lldb::eStateInvalid; 3965 event_sp.reset(); 3966 got_event = listener.WaitForEvent (timeout_ptr, event_sp); 3967 3968 if (got_event) 3969 { 3970 if (event_sp.get()) 3971 { 3972 bool keep_going = false; 3973 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 3974 if (log) 3975 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state)); 3976 3977 switch (stop_state) 3978 { 3979 case lldb::eStateStopped: 3980 { 3981 // Yay, we're done. Now make sure that our thread plan actually completed. 3982 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id); 3983 if (!thread_sp) 3984 { 3985 // Ooh, our thread has vanished. Unlikely that this was successful execution... 3986 if (log) 3987 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id); 3988 return_value = eExecutionInterrupted; 3989 } 3990 else 3991 { 3992 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 3993 StopReason stop_reason = eStopReasonInvalid; 3994 if (stop_info_sp) 3995 stop_reason = stop_info_sp->GetStopReason(); 3996 if (stop_reason == eStopReasonPlanComplete) 3997 { 3998 if (log) 3999 log->PutCString ("Execution completed successfully."); 4000 // Now mark this plan as private so it doesn't get reported as the stop reason 4001 // after this point. 4002 if (thread_plan_sp) 4003 thread_plan_sp->SetPrivate (orig_plan_private); 4004 return_value = eExecutionCompleted; 4005 } 4006 else 4007 { 4008 if (log) 4009 log->PutCString ("Thread plan didn't successfully complete."); 4010 4011 return_value = eExecutionInterrupted; 4012 } 4013 } 4014 } 4015 break; 4016 4017 case lldb::eStateCrashed: 4018 if (log) 4019 log->PutCString ("Execution crashed."); 4020 return_value = eExecutionInterrupted; 4021 break; 4022 4023 case lldb::eStateRunning: 4024 do_resume = false; 4025 keep_going = true; 4026 break; 4027 4028 default: 4029 if (log) 4030 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state)); 4031 4032 errors.Printf ("Execution stopped with unexpected state."); 4033 return_value = eExecutionInterrupted; 4034 break; 4035 } 4036 if (keep_going) 4037 continue; 4038 else 4039 break; 4040 } 4041 else 4042 { 4043 if (log) 4044 log->PutCString ("got_event was true, but the event pointer was null. How odd..."); 4045 return_value = eExecutionInterrupted; 4046 break; 4047 } 4048 } 4049 else 4050 { 4051 // If we didn't get an event that means we've timed out... 4052 // We will interrupt the process here. Depending on what we were asked to do we will 4053 // either exit, or try with all threads running for the same timeout. 4054 // Not really sure what to do if Halt fails here... 4055 4056 if (log) { 4057 if (try_all_threads) 4058 { 4059 if (first_timeout) 4060 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, " 4061 "trying with all threads enabled.", 4062 single_thread_timeout_usec); 4063 else 4064 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled " 4065 "and timeout: %d timed out.", 4066 single_thread_timeout_usec); 4067 } 4068 else 4069 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, " 4070 "halt and abandoning execution.", 4071 single_thread_timeout_usec); 4072 } 4073 4074 Error halt_error = Halt(); 4075 if (halt_error.Success()) 4076 { 4077 if (log) 4078 log->PutCString ("Process::RunThreadPlan(): Halt succeeded."); 4079 4080 // If halt succeeds, it always produces a stopped event. Wait for that: 4081 4082 real_timeout = TimeValue::Now(); 4083 real_timeout.OffsetWithMicroSeconds(500000); 4084 4085 got_event = listener.WaitForEvent(&real_timeout, event_sp); 4086 4087 if (got_event) 4088 { 4089 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4090 if (log) 4091 { 4092 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state)); 4093 if (stop_state == lldb::eStateStopped 4094 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get())) 4095 log->PutCString (" Event was the Halt interruption event."); 4096 } 4097 4098 if (stop_state == lldb::eStateStopped) 4099 { 4100 // Between the time we initiated the Halt and the time we delivered it, the process could have 4101 // already finished its job. Check that here: 4102 4103 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 4104 { 4105 if (log) 4106 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. " 4107 "Exiting wait loop."); 4108 return_value = eExecutionCompleted; 4109 break; 4110 } 4111 4112 if (!try_all_threads) 4113 { 4114 if (log) 4115 log->PutCString ("try_all_threads was false, we stopped so now we're quitting."); 4116 return_value = eExecutionInterrupted; 4117 break; 4118 } 4119 4120 if (first_timeout) 4121 { 4122 // Set all the other threads to run, and return to the top of the loop, which will continue; 4123 first_timeout = false; 4124 thread_plan_sp->SetStopOthers (false); 4125 if (log) 4126 log->PutCString ("Process::RunThreadPlan(): About to resume."); 4127 4128 continue; 4129 } 4130 else 4131 { 4132 // Running all threads failed, so return Interrupted. 4133 if (log) 4134 log->PutCString("Process::RunThreadPlan(): running all threads timed out."); 4135 return_value = eExecutionInterrupted; 4136 break; 4137 } 4138 } 4139 } 4140 else 4141 { if (log) 4142 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. " 4143 "I'm getting out of here passing Interrupted."); 4144 return_value = eExecutionInterrupted; 4145 break; 4146 } 4147 } 4148 else 4149 { 4150 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return 4151 // an error from halt, but if you wait a bit you'll get a stopped event anyway. 4152 if (log) 4153 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.", 4154 halt_error.AsCString()); 4155 real_timeout = TimeValue::Now(); 4156 real_timeout.OffsetWithMicroSeconds(500000); 4157 timeout_ptr = &real_timeout; 4158 got_event = listener.WaitForEvent(&real_timeout, event_sp); 4159 if (!got_event || event_sp.get() == NULL) 4160 { 4161 // This is not going anywhere, bag out. 4162 if (log) 4163 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed."); 4164 return_value = eExecutionInterrupted; 4165 break; 4166 } 4167 else 4168 { 4169 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 4170 if (log) 4171 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever..."); 4172 if (stop_state == lldb::eStateStopped) 4173 { 4174 // Between the time we initiated the Halt and the time we delivered it, the process could have 4175 // already finished its job. Check that here: 4176 4177 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 4178 { 4179 if (log) 4180 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. " 4181 "Exiting wait loop."); 4182 return_value = eExecutionCompleted; 4183 break; 4184 } 4185 4186 if (first_timeout) 4187 { 4188 // Set all the other threads to run, and return to the top of the loop, which will continue; 4189 first_timeout = false; 4190 thread_plan_sp->SetStopOthers (false); 4191 if (log) 4192 log->PutCString ("Process::RunThreadPlan(): About to resume."); 4193 4194 continue; 4195 } 4196 else 4197 { 4198 // Running all threads failed, so return Interrupted. 4199 if (log) 4200 log->PutCString ("Process::RunThreadPlan(): running all threads timed out."); 4201 return_value = eExecutionInterrupted; 4202 break; 4203 } 4204 } 4205 else 4206 { 4207 if (log) 4208 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get" 4209 " a stopped event, instead got %s.", StateAsCString(stop_state)); 4210 return_value = eExecutionInterrupted; 4211 break; 4212 } 4213 } 4214 } 4215 4216 } 4217 4218 } // END WAIT LOOP 4219 4220 // Now do some processing on the results of the run: 4221 if (return_value == eExecutionInterrupted) 4222 { 4223 if (log) 4224 { 4225 StreamString s; 4226 if (event_sp) 4227 event_sp->Dump (&s); 4228 else 4229 { 4230 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL."); 4231 } 4232 4233 StreamString ts; 4234 4235 const char *event_explanation = NULL; 4236 4237 do 4238 { 4239 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get()); 4240 4241 if (!event_data) 4242 { 4243 event_explanation = "<no event data>"; 4244 break; 4245 } 4246 4247 Process *process = event_data->GetProcessSP().get(); 4248 4249 if (!process) 4250 { 4251 event_explanation = "<no process>"; 4252 break; 4253 } 4254 4255 ThreadList &thread_list = process->GetThreadList(); 4256 4257 uint32_t num_threads = thread_list.GetSize(); 4258 uint32_t thread_index; 4259 4260 ts.Printf("<%u threads> ", num_threads); 4261 4262 for (thread_index = 0; 4263 thread_index < num_threads; 4264 ++thread_index) 4265 { 4266 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get(); 4267 4268 if (!thread) 4269 { 4270 ts.Printf("<?> "); 4271 continue; 4272 } 4273 4274 ts.Printf("<0x%4.4llx ", thread->GetID()); 4275 RegisterContext *register_context = thread->GetRegisterContext().get(); 4276 4277 if (register_context) 4278 ts.Printf("[ip 0x%llx] ", register_context->GetPC()); 4279 else 4280 ts.Printf("[ip unknown] "); 4281 4282 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo(); 4283 if (stop_info_sp) 4284 { 4285 const char *stop_desc = stop_info_sp->GetDescription(); 4286 if (stop_desc) 4287 ts.PutCString (stop_desc); 4288 } 4289 ts.Printf(">"); 4290 } 4291 4292 event_explanation = ts.GetData(); 4293 } while (0); 4294 4295 if (log) 4296 { 4297 if (event_explanation) 4298 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation); 4299 else 4300 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData()); 4301 } 4302 4303 if (discard_on_error && thread_plan_sp) 4304 { 4305 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 4306 thread_plan_sp->SetPrivate (orig_plan_private); 4307 } 4308 } 4309 } 4310 else if (return_value == eExecutionSetupError) 4311 { 4312 if (log) 4313 log->PutCString("Process::RunThreadPlan(): execution set up error."); 4314 4315 if (discard_on_error && thread_plan_sp) 4316 { 4317 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 4318 thread_plan_sp->SetPrivate (orig_plan_private); 4319 } 4320 } 4321 else 4322 { 4323 if (thread->IsThreadPlanDone (thread_plan_sp.get())) 4324 { 4325 if (log) 4326 log->PutCString("Process::RunThreadPlan(): thread plan is done"); 4327 return_value = eExecutionCompleted; 4328 } 4329 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get())) 4330 { 4331 if (log) 4332 log->PutCString("Process::RunThreadPlan(): thread plan was discarded"); 4333 return_value = eExecutionDiscarded; 4334 } 4335 else 4336 { 4337 if (log) 4338 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course"); 4339 if (discard_on_error && thread_plan_sp) 4340 { 4341 if (log) 4342 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set."); 4343 thread->DiscardThreadPlansUpToPlan (thread_plan_sp); 4344 thread_plan_sp->SetPrivate (orig_plan_private); 4345 } 4346 } 4347 } 4348 4349 // Thread we ran the function in may have gone away because we ran the target 4350 // Check that it's still there, and if it is put it back in the context. Also restore the 4351 // frame in the context if it is still present. 4352 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get(); 4353 if (thread) 4354 { 4355 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id)); 4356 } 4357 4358 // Also restore the current process'es selected frame & thread, since this function calling may 4359 // be done behind the user's back. 4360 4361 if (selected_tid != LLDB_INVALID_THREAD_ID) 4362 { 4363 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid()) 4364 { 4365 // We were able to restore the selected thread, now restore the frame: 4366 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id); 4367 if (old_frame_sp) 4368 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get()); 4369 } 4370 } 4371 4372 return return_value; 4373 } 4374 4375 const char * 4376 Process::ExecutionResultAsCString (ExecutionResults result) 4377 { 4378 const char *result_name; 4379 4380 switch (result) 4381 { 4382 case eExecutionCompleted: 4383 result_name = "eExecutionCompleted"; 4384 break; 4385 case eExecutionDiscarded: 4386 result_name = "eExecutionDiscarded"; 4387 break; 4388 case eExecutionInterrupted: 4389 result_name = "eExecutionInterrupted"; 4390 break; 4391 case eExecutionSetupError: 4392 result_name = "eExecutionSetupError"; 4393 break; 4394 case eExecutionTimedOut: 4395 result_name = "eExecutionTimedOut"; 4396 break; 4397 } 4398 return result_name; 4399 } 4400 4401 void 4402 Process::GetStatus (Stream &strm) 4403 { 4404 const StateType state = GetState(); 4405 if (StateIsStoppedState(state, false)) 4406 { 4407 if (state == eStateExited) 4408 { 4409 int exit_status = GetExitStatus(); 4410 const char *exit_description = GetExitDescription(); 4411 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n", 4412 GetID(), 4413 exit_status, 4414 exit_status, 4415 exit_description ? exit_description : ""); 4416 } 4417 else 4418 { 4419 if (state == eStateConnected) 4420 strm.Printf ("Connected to remote target.\n"); 4421 else 4422 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state)); 4423 } 4424 } 4425 else 4426 { 4427 strm.Printf ("Process %llu is running.\n", GetID()); 4428 } 4429 } 4430 4431 size_t 4432 Process::GetThreadStatus (Stream &strm, 4433 bool only_threads_with_stop_reason, 4434 uint32_t start_frame, 4435 uint32_t num_frames, 4436 uint32_t num_frames_with_source) 4437 { 4438 size_t num_thread_infos_dumped = 0; 4439 4440 const size_t num_threads = GetThreadList().GetSize(); 4441 for (uint32_t i = 0; i < num_threads; i++) 4442 { 4443 Thread *thread = GetThreadList().GetThreadAtIndex(i).get(); 4444 if (thread) 4445 { 4446 if (only_threads_with_stop_reason) 4447 { 4448 if (thread->GetStopInfo().get() == NULL) 4449 continue; 4450 } 4451 thread->GetStatus (strm, 4452 start_frame, 4453 num_frames, 4454 num_frames_with_source); 4455 ++num_thread_infos_dumped; 4456 } 4457 } 4458 return num_thread_infos_dumped; 4459 } 4460 4461 void 4462 Process::AddInvalidMemoryRegion (const LoadRange ®ion) 4463 { 4464 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize()); 4465 } 4466 4467 bool 4468 Process::RemoveInvalidMemoryRange (const LoadRange ®ion) 4469 { 4470 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize()); 4471 } 4472 4473 4474 //-------------------------------------------------------------- 4475 // class Process::SettingsController 4476 //-------------------------------------------------------------- 4477 4478 Process::SettingsController::SettingsController () : 4479 UserSettingsController ("process", Target::GetSettingsController()) 4480 { 4481 } 4482 4483 Process::SettingsController::~SettingsController () 4484 { 4485 } 4486 4487 lldb::InstanceSettingsSP 4488 Process::SettingsController::CreateInstanceSettings (const char *instance_name) 4489 { 4490 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(), 4491 false, 4492 instance_name)); 4493 return new_settings_sp; 4494 } 4495 4496 //-------------------------------------------------------------- 4497 // class ProcessInstanceSettings 4498 //-------------------------------------------------------------- 4499 4500 ProcessInstanceSettings::ProcessInstanceSettings 4501 ( 4502 const UserSettingsControllerSP &owner_sp, 4503 bool live_instance, 4504 const char *name 4505 ) : 4506 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance) 4507 { 4508 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called 4509 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers. 4510 // For this reason it has to be called here, rather than in the initializer or in the parent constructor. 4511 // This is true for CreateInstanceName() too. 4512 4513 if (GetInstanceName () == InstanceSettings::InvalidName()) 4514 { 4515 ChangeInstanceName (std::string (CreateInstanceName().AsCString())); 4516 owner_sp->RegisterInstanceSettings (this); 4517 } 4518 4519 if (live_instance) 4520 { 4521 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name); 4522 CopyInstanceSettings (pending_settings,false); 4523 } 4524 } 4525 4526 ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) : 4527 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString()) 4528 { 4529 if (m_instance_name != InstanceSettings::GetDefaultName()) 4530 { 4531 UserSettingsControllerSP owner_sp (m_owner_wp.lock()); 4532 if (owner_sp) 4533 { 4534 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false); 4535 owner_sp->RemovePendingSettings (m_instance_name); 4536 } 4537 } 4538 } 4539 4540 ProcessInstanceSettings::~ProcessInstanceSettings () 4541 { 4542 } 4543 4544 ProcessInstanceSettings& 4545 ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs) 4546 { 4547 if (this != &rhs) 4548 { 4549 } 4550 4551 return *this; 4552 } 4553 4554 4555 void 4556 ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name, 4557 const char *index_value, 4558 const char *value, 4559 const ConstString &instance_name, 4560 const SettingEntry &entry, 4561 VarSetOperationType op, 4562 Error &err, 4563 bool pending) 4564 { 4565 } 4566 4567 void 4568 ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, 4569 bool pending) 4570 { 4571 // if (new_settings.get() == NULL) 4572 // return; 4573 // 4574 // ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get(); 4575 } 4576 4577 bool 4578 ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry, 4579 const ConstString &var_name, 4580 StringList &value, 4581 Error *err) 4582 { 4583 if (err) 4584 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString()); 4585 return false; 4586 } 4587 4588 const ConstString 4589 ProcessInstanceSettings::CreateInstanceName () 4590 { 4591 static int instance_count = 1; 4592 StreamString sstr; 4593 4594 sstr.Printf ("process_%d", instance_count); 4595 ++instance_count; 4596 4597 const ConstString ret_val (sstr.GetData()); 4598 return ret_val; 4599 } 4600 4601 //-------------------------------------------------- 4602 // SettingsController Variable Tables 4603 //-------------------------------------------------- 4604 4605 SettingEntry 4606 Process::SettingsController::global_settings_table[] = 4607 { 4608 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"}, 4609 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL } 4610 }; 4611 4612 4613 SettingEntry 4614 Process::SettingsController::instance_settings_table[] = 4615 { 4616 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"}, 4617 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL } 4618 }; 4619 4620 4621 4622 4623