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