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