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