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