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