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